babylon.viewer.max.js 5.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861
  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 = 22);
  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__(24); } catch(e) {}
  90. try { OIMO = OIMO || __webpack_require__(25); } catch(e) {}
  91. try { earcut = earcut || __webpack_require__(26); } 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. var scene = this._mesh.getScene();
  183. for (var index = 0; index < scene.meshes.length; index++) {
  184. var otherMesh = scene.meshes[index];
  185. if (!otherMesh.material) {
  186. continue;
  187. }
  188. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  189. continue;
  190. }
  191. if (otherMesh.material.getEffect() === effect) {
  192. otherMesh.computeBonesUsingShaders = false;
  193. }
  194. else {
  195. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  196. var subMesh = _a[_i];
  197. var subMeshEffect = subMesh.effect;
  198. if (subMeshEffect === effect) {
  199. otherMesh.computeBonesUsingShaders = false;
  200. break;
  201. }
  202. }
  203. }
  204. }
  205. }
  206. else {
  207. var currentFallbacks = this._defines[this._currentRank];
  208. if (currentFallbacks) {
  209. for (var index = 0; index < currentFallbacks.length; index++) {
  210. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  211. }
  212. }
  213. this._currentRank++;
  214. }
  215. return currentDefines;
  216. };
  217. return EffectFallbacks;
  218. }());
  219. BABYLON.EffectFallbacks = EffectFallbacks;
  220. /**
  221. * Options to be used when creating an effect.
  222. */
  223. var EffectCreationOptions = /** @class */ (function () {
  224. function EffectCreationOptions() {
  225. }
  226. return EffectCreationOptions;
  227. }());
  228. BABYLON.EffectCreationOptions = EffectCreationOptions;
  229. /**
  230. * Effect containing vertex and fragment shader that can be executed on an object.
  231. */
  232. var Effect = /** @class */ (function () {
  233. /**
  234. * Instantiates an effect.
  235. * An effect can be used to create/manage/execute vertex and fragment shaders.
  236. * @param baseName Name of the effect.
  237. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  238. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  239. * @param samplers List of sampler variables that will be passed to the shader.
  240. * @param engine Engine to be used to render the effect
  241. * @param defines Define statements to be added to the shader.
  242. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  243. * @param onCompiled Callback that will be called when the shader is compiled.
  244. * @param onError Callback that will be called if an error occurs during shader compilation.
  245. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  246. */
  247. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  248. if (samplers === void 0) { samplers = null; }
  249. if (defines === void 0) { defines = null; }
  250. if (fallbacks === void 0) { fallbacks = null; }
  251. if (onCompiled === void 0) { onCompiled = null; }
  252. if (onError === void 0) { onError = null; }
  253. var _this = this;
  254. /**
  255. * Unique ID of the effect.
  256. */
  257. this.uniqueId = 0;
  258. /**
  259. * Observable that will be called when the shader is compiled.
  260. */
  261. this.onCompileObservable = new BABYLON.Observable();
  262. /**
  263. * Observable that will be called if an error occurs during shader compilation.
  264. */
  265. this.onErrorObservable = new BABYLON.Observable();
  266. /**
  267. * Observable that will be called when effect is bound.
  268. */
  269. this.onBindObservable = new BABYLON.Observable();
  270. this._uniformBuffersNames = {};
  271. this._isReady = false;
  272. this._compilationError = "";
  273. this.name = baseName;
  274. if (attributesNamesOrOptions.attributes) {
  275. var options = attributesNamesOrOptions;
  276. this._engine = uniformsNamesOrEngine;
  277. this._attributesNames = options.attributes;
  278. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  279. this._samplers = options.samplers.slice();
  280. this.defines = options.defines;
  281. this.onError = options.onError;
  282. this.onCompiled = options.onCompiled;
  283. this._fallbacks = options.fallbacks;
  284. this._indexParameters = options.indexParameters;
  285. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  286. if (options.uniformBuffersNames) {
  287. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  288. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  289. }
  290. }
  291. }
  292. else {
  293. this._engine = engine;
  294. this.defines = defines;
  295. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  296. this._samplers = samplers ? samplers.slice() : [];
  297. this._attributesNames = attributesNamesOrOptions;
  298. this.onError = onError;
  299. this.onCompiled = onCompiled;
  300. this._indexParameters = indexParameters;
  301. this._fallbacks = fallbacks;
  302. }
  303. this.uniqueId = Effect._uniqueIdSeed++;
  304. var vertexSource;
  305. var fragmentSource;
  306. if (baseName.vertexElement) {
  307. vertexSource = document.getElementById(baseName.vertexElement);
  308. if (!vertexSource) {
  309. vertexSource = baseName.vertexElement;
  310. }
  311. }
  312. else {
  313. vertexSource = baseName.vertex || baseName;
  314. }
  315. if (baseName.fragmentElement) {
  316. fragmentSource = document.getElementById(baseName.fragmentElement);
  317. if (!fragmentSource) {
  318. fragmentSource = baseName.fragmentElement;
  319. }
  320. }
  321. else {
  322. fragmentSource = baseName.fragment || baseName;
  323. }
  324. this._loadVertexShader(vertexSource, function (vertexCode) {
  325. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  326. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  327. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  328. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  329. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  330. if (baseName) {
  331. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  332. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  333. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  334. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  335. }
  336. else {
  337. _this._vertexSourceCode = migratedVertexCode;
  338. _this._fragmentSourceCode = migratedFragmentCode;
  339. }
  340. _this._prepareEffect();
  341. });
  342. });
  343. });
  344. });
  345. });
  346. });
  347. }
  348. Object.defineProperty(Effect.prototype, "key", {
  349. /**
  350. * Unique key for this effect
  351. */
  352. get: function () {
  353. return this._key;
  354. },
  355. enumerable: true,
  356. configurable: true
  357. });
  358. /**
  359. * If the effect has been compiled and prepared.
  360. * @returns if the effect is compiled and prepared.
  361. */
  362. Effect.prototype.isReady = function () {
  363. return this._isReady;
  364. };
  365. /**
  366. * The engine the effect was initialized with.
  367. * @returns the engine.
  368. */
  369. Effect.prototype.getEngine = function () {
  370. return this._engine;
  371. };
  372. /**
  373. * The compiled webGL program for the effect
  374. * @returns the webGL program.
  375. */
  376. Effect.prototype.getProgram = function () {
  377. return this._program;
  378. };
  379. /**
  380. * The set of names of attribute variables for the shader.
  381. * @returns An array of attribute names.
  382. */
  383. Effect.prototype.getAttributesNames = function () {
  384. return this._attributesNames;
  385. };
  386. /**
  387. * Returns the attribute at the given index.
  388. * @param index The index of the attribute.
  389. * @returns The location of the attribute.
  390. */
  391. Effect.prototype.getAttributeLocation = function (index) {
  392. return this._attributes[index];
  393. };
  394. /**
  395. * Returns the attribute based on the name of the variable.
  396. * @param name of the attribute to look up.
  397. * @returns the attribute location.
  398. */
  399. Effect.prototype.getAttributeLocationByName = function (name) {
  400. var index = this._attributesNames.indexOf(name);
  401. return this._attributes[index];
  402. };
  403. /**
  404. * The number of attributes.
  405. * @returns the numnber of attributes.
  406. */
  407. Effect.prototype.getAttributesCount = function () {
  408. return this._attributes.length;
  409. };
  410. /**
  411. * Gets the index of a uniform variable.
  412. * @param uniformName of the uniform to look up.
  413. * @returns the index.
  414. */
  415. Effect.prototype.getUniformIndex = function (uniformName) {
  416. return this._uniformsNames.indexOf(uniformName);
  417. };
  418. /**
  419. * Returns the attribute based on the name of the variable.
  420. * @param uniformName of the uniform to look up.
  421. * @returns the location of the uniform.
  422. */
  423. Effect.prototype.getUniform = function (uniformName) {
  424. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  425. };
  426. /**
  427. * Returns an array of sampler variable names
  428. * @returns The array of sampler variable neames.
  429. */
  430. Effect.prototype.getSamplers = function () {
  431. return this._samplers;
  432. };
  433. /**
  434. * The error from the last compilation.
  435. * @returns the error string.
  436. */
  437. Effect.prototype.getCompilationError = function () {
  438. return this._compilationError;
  439. };
  440. /**
  441. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  442. * @param func The callback to be used.
  443. */
  444. Effect.prototype.executeWhenCompiled = function (func) {
  445. if (this.isReady()) {
  446. func(this);
  447. return;
  448. }
  449. this.onCompileObservable.add(function (effect) {
  450. func(effect);
  451. });
  452. };
  453. /** @hidden */
  454. Effect.prototype._loadVertexShader = function (vertex, callback) {
  455. if (BABYLON.Tools.IsWindowObjectExist()) {
  456. // DOM element ?
  457. if (vertex instanceof HTMLElement) {
  458. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  459. callback(vertexCode);
  460. return;
  461. }
  462. }
  463. // Base64 encoded ?
  464. if (vertex.substr(0, 7) === "base64:") {
  465. var vertexBinary = window.atob(vertex.substr(7));
  466. callback(vertexBinary);
  467. return;
  468. }
  469. // Is in local store ?
  470. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  471. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  472. return;
  473. }
  474. var vertexShaderUrl;
  475. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  476. vertexShaderUrl = vertex;
  477. }
  478. else {
  479. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  480. }
  481. // Vertex shader
  482. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  483. };
  484. /** @hidden */
  485. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  486. if (BABYLON.Tools.IsWindowObjectExist()) {
  487. // DOM element ?
  488. if (fragment instanceof HTMLElement) {
  489. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  490. callback(fragmentCode);
  491. return;
  492. }
  493. }
  494. // Base64 encoded ?
  495. if (fragment.substr(0, 7) === "base64:") {
  496. var fragmentBinary = window.atob(fragment.substr(7));
  497. callback(fragmentBinary);
  498. return;
  499. }
  500. // Is in local store ?
  501. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  502. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  503. return;
  504. }
  505. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  506. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  507. return;
  508. }
  509. var fragmentShaderUrl;
  510. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  511. fragmentShaderUrl = fragment;
  512. }
  513. else {
  514. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  515. }
  516. // Fragment shader
  517. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  518. };
  519. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  520. // Rebuild shaders source code
  521. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  522. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  523. vertexCode = prefix + vertexCode;
  524. fragmentCode = prefix + fragmentCode;
  525. // Number lines of shaders source code
  526. var i = 2;
  527. var regex = /\n/gm;
  528. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  529. i = 2;
  530. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  531. // Dump shaders name and formatted source code
  532. if (this.name.vertexElement) {
  533. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  534. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  535. }
  536. else if (this.name.vertex) {
  537. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  538. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  539. }
  540. else {
  541. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  542. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  543. }
  544. };
  545. ;
  546. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  547. var preparedSourceCode = this._processPrecision(sourceCode);
  548. if (this._engine.webGLVersion == 1) {
  549. callback(preparedSourceCode);
  550. return;
  551. }
  552. // Already converted
  553. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  554. callback(preparedSourceCode.replace("#version 300 es", ""));
  555. return;
  556. }
  557. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  558. // Remove extensions
  559. // #extension GL_OES_standard_derivatives : enable
  560. // #extension GL_EXT_shader_texture_lod : enable
  561. // #extension GL_EXT_frag_depth : enable
  562. // #extension GL_EXT_draw_buffers : require
  563. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  564. var result = preparedSourceCode.replace(regex, "");
  565. // Migrate to GLSL v300
  566. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  567. result = result.replace(/attribute[ \t]/g, "in ");
  568. result = result.replace(/[ \t]attribute/g, " in");
  569. if (isFragment) {
  570. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  571. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  572. result = result.replace(/texture2D\s*\(/g, "texture(");
  573. result = result.replace(/textureCube\s*\(/g, "texture(");
  574. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  575. result = result.replace(/gl_FragColor/g, "glFragColor");
  576. result = result.replace(/gl_FragData/g, "glFragData");
  577. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  578. }
  579. callback(result);
  580. };
  581. Effect.prototype._processIncludes = function (sourceCode, callback) {
  582. var _this = this;
  583. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  584. var match = regex.exec(sourceCode);
  585. var returnValue = new String(sourceCode);
  586. while (match != null) {
  587. var includeFile = match[1];
  588. // Uniform declaration
  589. if (includeFile.indexOf("__decl__") !== -1) {
  590. includeFile = includeFile.replace(/__decl__/, "");
  591. if (this._engine.supportsUniformBuffers) {
  592. includeFile = includeFile.replace(/Vertex/, "Ubo");
  593. includeFile = includeFile.replace(/Fragment/, "Ubo");
  594. }
  595. includeFile = includeFile + "Declaration";
  596. }
  597. if (Effect.IncludesShadersStore[includeFile]) {
  598. // Substitution
  599. var includeContent = Effect.IncludesShadersStore[includeFile];
  600. if (match[2]) {
  601. var splits = match[3].split(",");
  602. for (var index = 0; index < splits.length; index += 2) {
  603. var source = new RegExp(splits[index], "g");
  604. var dest = splits[index + 1];
  605. includeContent = includeContent.replace(source, dest);
  606. }
  607. }
  608. if (match[4]) {
  609. var indexString = match[5];
  610. if (indexString.indexOf("..") !== -1) {
  611. var indexSplits = indexString.split("..");
  612. var minIndex = parseInt(indexSplits[0]);
  613. var maxIndex = parseInt(indexSplits[1]);
  614. var sourceIncludeContent = includeContent.slice(0);
  615. includeContent = "";
  616. if (isNaN(maxIndex)) {
  617. maxIndex = this._indexParameters[indexSplits[1]];
  618. }
  619. for (var i = minIndex; i < maxIndex; i++) {
  620. if (!this._engine.supportsUniformBuffers) {
  621. // Ubo replacement
  622. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  623. return p1 + "{X}";
  624. });
  625. }
  626. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  627. }
  628. }
  629. else {
  630. if (!this._engine.supportsUniformBuffers) {
  631. // Ubo replacement
  632. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  633. return p1 + "{X}";
  634. });
  635. }
  636. includeContent = includeContent.replace(/\{X\}/g, indexString);
  637. }
  638. }
  639. // Replace
  640. returnValue = returnValue.replace(match[0], includeContent);
  641. }
  642. else {
  643. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  644. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  645. Effect.IncludesShadersStore[includeFile] = fileContent;
  646. _this._processIncludes(returnValue, callback);
  647. });
  648. return;
  649. }
  650. match = regex.exec(sourceCode);
  651. }
  652. callback(returnValue);
  653. };
  654. Effect.prototype._processPrecision = function (source) {
  655. if (source.indexOf("precision highp float") === -1) {
  656. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  657. source = "precision mediump float;\n" + source;
  658. }
  659. else {
  660. source = "precision highp float;\n" + source;
  661. }
  662. }
  663. else {
  664. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  665. source = source.replace("precision highp float", "precision mediump float");
  666. }
  667. }
  668. return source;
  669. };
  670. /**
  671. * Recompiles the webGL program
  672. * @param vertexSourceCode The source code for the vertex shader.
  673. * @param fragmentSourceCode The source code for the fragment shader.
  674. * @param onCompiled Callback called when completed.
  675. * @param onError Callback called on error.
  676. */
  677. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  678. var _this = this;
  679. this._isReady = false;
  680. this._vertexSourceCodeOverride = vertexSourceCode;
  681. this._fragmentSourceCodeOverride = fragmentSourceCode;
  682. this.onError = function (effect, error) {
  683. if (onError) {
  684. onError(error);
  685. }
  686. };
  687. this.onCompiled = function () {
  688. var scenes = _this.getEngine().scenes;
  689. for (var i = 0; i < scenes.length; i++) {
  690. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  691. }
  692. if (onCompiled) {
  693. onCompiled(_this._program);
  694. }
  695. };
  696. this._fallbacks = null;
  697. this._prepareEffect();
  698. };
  699. /**
  700. * Gets the uniform locations of the the specified variable names
  701. * @param names THe names of the variables to lookup.
  702. * @returns Array of locations in the same order as variable names.
  703. */
  704. Effect.prototype.getSpecificUniformLocations = function (names) {
  705. var engine = this._engine;
  706. return engine.getUniforms(this._program, names);
  707. };
  708. /**
  709. * Prepares the effect
  710. */
  711. Effect.prototype._prepareEffect = function () {
  712. var attributesNames = this._attributesNames;
  713. var defines = this.defines;
  714. var fallbacks = this._fallbacks;
  715. this._valueCache = {};
  716. var previousProgram = this._program;
  717. try {
  718. var engine = this._engine;
  719. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  720. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  721. }
  722. else {
  723. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  724. }
  725. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  726. if (engine.supportsUniformBuffers) {
  727. for (var name in this._uniformBuffersNames) {
  728. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  729. }
  730. }
  731. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  732. this._attributes = engine.getAttributes(this._program, attributesNames);
  733. var index;
  734. for (index = 0; index < this._samplers.length; index++) {
  735. var sampler = this.getUniform(this._samplers[index]);
  736. if (sampler == null) {
  737. this._samplers.splice(index, 1);
  738. index--;
  739. }
  740. }
  741. engine.bindSamplers(this);
  742. this._compilationError = "";
  743. this._isReady = true;
  744. if (this.onCompiled) {
  745. this.onCompiled(this);
  746. }
  747. this.onCompileObservable.notifyObservers(this);
  748. this.onCompileObservable.clear();
  749. // Unbind mesh reference in fallbacks
  750. if (this._fallbacks) {
  751. this._fallbacks.unBindMesh();
  752. }
  753. if (previousProgram) {
  754. this.getEngine()._deleteProgram(previousProgram);
  755. }
  756. }
  757. catch (e) {
  758. this._compilationError = e.message;
  759. // Let's go through fallbacks then
  760. BABYLON.Tools.Error("Unable to compile effect:");
  761. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  762. return " " + uniform;
  763. }));
  764. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  765. return " " + attribute;
  766. }));
  767. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  768. BABYLON.Tools.Error("Error: " + this._compilationError);
  769. if (previousProgram) {
  770. this._program = previousProgram;
  771. this._isReady = true;
  772. if (this.onError) {
  773. this.onError(this, this._compilationError);
  774. }
  775. this.onErrorObservable.notifyObservers(this);
  776. }
  777. if (fallbacks && fallbacks.isMoreFallbacks) {
  778. BABYLON.Tools.Error("Trying next fallback.");
  779. this.defines = fallbacks.reduce(this.defines, this);
  780. this._prepareEffect();
  781. }
  782. else { // Sorry we did everything we can
  783. if (this.onError) {
  784. this.onError(this, this._compilationError);
  785. }
  786. this.onErrorObservable.notifyObservers(this);
  787. this.onErrorObservable.clear();
  788. // Unbind mesh reference in fallbacks
  789. if (this._fallbacks) {
  790. this._fallbacks.unBindMesh();
  791. }
  792. }
  793. }
  794. };
  795. Object.defineProperty(Effect.prototype, "isSupported", {
  796. /**
  797. * Checks if the effect is supported. (Must be called after compilation)
  798. */
  799. get: function () {
  800. return this._compilationError === "";
  801. },
  802. enumerable: true,
  803. configurable: true
  804. });
  805. /**
  806. * Binds a texture to the engine to be used as output of the shader.
  807. * @param channel Name of the output variable.
  808. * @param texture Texture to bind.
  809. */
  810. Effect.prototype._bindTexture = function (channel, texture) {
  811. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  812. };
  813. /**
  814. * Sets a texture on the engine to be used in the shader.
  815. * @param channel Name of the sampler variable.
  816. * @param texture Texture to set.
  817. */
  818. Effect.prototype.setTexture = function (channel, texture) {
  819. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  820. };
  821. /**
  822. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  823. * @param channel Name of the sampler variable.
  824. * @param texture Texture to set.
  825. */
  826. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  827. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  828. };
  829. /**
  830. * Sets an array of textures on the engine to be used in the shader.
  831. * @param channel Name of the variable.
  832. * @param textures Textures to set.
  833. */
  834. Effect.prototype.setTextureArray = function (channel, textures) {
  835. if (this._samplers.indexOf(channel + "Ex") === -1) {
  836. var initialPos = this._samplers.indexOf(channel);
  837. for (var index = 1; index < textures.length; index++) {
  838. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  839. }
  840. }
  841. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  842. };
  843. /**
  844. * 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)
  845. * @param channel Name of the sampler variable.
  846. * @param postProcess Post process to get the input texture from.
  847. */
  848. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  849. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  850. };
  851. /**
  852. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  853. * 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)
  854. * @param channel Name of the sampler variable.
  855. * @param postProcess Post process to get the output texture from.
  856. */
  857. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  858. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  859. };
  860. /** @hidden */
  861. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  862. var cache = this._valueCache[uniformName];
  863. var flag = matrix.updateFlag;
  864. if (cache !== undefined && cache === flag) {
  865. return false;
  866. }
  867. this._valueCache[uniformName] = flag;
  868. return true;
  869. };
  870. /** @hidden */
  871. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  872. var cache = this._valueCache[uniformName];
  873. if (!cache) {
  874. cache = [x, y];
  875. this._valueCache[uniformName] = cache;
  876. return true;
  877. }
  878. var changed = false;
  879. if (cache[0] !== x) {
  880. cache[0] = x;
  881. changed = true;
  882. }
  883. if (cache[1] !== y) {
  884. cache[1] = y;
  885. changed = true;
  886. }
  887. return changed;
  888. };
  889. /** @hidden */
  890. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  891. var cache = this._valueCache[uniformName];
  892. if (!cache) {
  893. cache = [x, y, z];
  894. this._valueCache[uniformName] = cache;
  895. return true;
  896. }
  897. var changed = false;
  898. if (cache[0] !== x) {
  899. cache[0] = x;
  900. changed = true;
  901. }
  902. if (cache[1] !== y) {
  903. cache[1] = y;
  904. changed = true;
  905. }
  906. if (cache[2] !== z) {
  907. cache[2] = z;
  908. changed = true;
  909. }
  910. return changed;
  911. };
  912. /** @hidden */
  913. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  914. var cache = this._valueCache[uniformName];
  915. if (!cache) {
  916. cache = [x, y, z, w];
  917. this._valueCache[uniformName] = cache;
  918. return true;
  919. }
  920. var changed = false;
  921. if (cache[0] !== x) {
  922. cache[0] = x;
  923. changed = true;
  924. }
  925. if (cache[1] !== y) {
  926. cache[1] = y;
  927. changed = true;
  928. }
  929. if (cache[2] !== z) {
  930. cache[2] = z;
  931. changed = true;
  932. }
  933. if (cache[3] !== w) {
  934. cache[3] = w;
  935. changed = true;
  936. }
  937. return changed;
  938. };
  939. /**
  940. * Binds a buffer to a uniform.
  941. * @param buffer Buffer to bind.
  942. * @param name Name of the uniform variable to bind to.
  943. */
  944. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  945. var bufferName = this._uniformBuffersNames[name];
  946. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  947. return;
  948. }
  949. Effect._baseCache[bufferName] = buffer;
  950. this._engine.bindUniformBufferBase(buffer, bufferName);
  951. };
  952. /**
  953. * Binds block to a uniform.
  954. * @param blockName Name of the block to bind.
  955. * @param index Index to bind.
  956. */
  957. Effect.prototype.bindUniformBlock = function (blockName, index) {
  958. this._engine.bindUniformBlock(this._program, blockName, index);
  959. };
  960. /**
  961. * Sets an interger value on a uniform variable.
  962. * @param uniformName Name of the variable.
  963. * @param value Value to be set.
  964. * @returns this effect.
  965. */
  966. Effect.prototype.setInt = function (uniformName, value) {
  967. var cache = this._valueCache[uniformName];
  968. if (cache !== undefined && cache === value)
  969. return this;
  970. this._valueCache[uniformName] = value;
  971. this._engine.setInt(this.getUniform(uniformName), value);
  972. return this;
  973. };
  974. /**
  975. * Sets an int array on a uniform variable.
  976. * @param uniformName Name of the variable.
  977. * @param array array to be set.
  978. * @returns this effect.
  979. */
  980. Effect.prototype.setIntArray = function (uniformName, array) {
  981. this._valueCache[uniformName] = null;
  982. this._engine.setIntArray(this.getUniform(uniformName), array);
  983. return this;
  984. };
  985. /**
  986. * 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)
  987. * @param uniformName Name of the variable.
  988. * @param array array to be set.
  989. * @returns this effect.
  990. */
  991. Effect.prototype.setIntArray2 = function (uniformName, array) {
  992. this._valueCache[uniformName] = null;
  993. this._engine.setIntArray2(this.getUniform(uniformName), array);
  994. return this;
  995. };
  996. /**
  997. * 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)
  998. * @param uniformName Name of the variable.
  999. * @param array array to be set.
  1000. * @returns this effect.
  1001. */
  1002. Effect.prototype.setIntArray3 = function (uniformName, array) {
  1003. this._valueCache[uniformName] = null;
  1004. this._engine.setIntArray3(this.getUniform(uniformName), array);
  1005. return this;
  1006. };
  1007. /**
  1008. * 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)
  1009. * @param uniformName Name of the variable.
  1010. * @param array array to be set.
  1011. * @returns this effect.
  1012. */
  1013. Effect.prototype.setIntArray4 = function (uniformName, array) {
  1014. this._valueCache[uniformName] = null;
  1015. this._engine.setIntArray4(this.getUniform(uniformName), array);
  1016. return this;
  1017. };
  1018. /**
  1019. * Sets an float array on a uniform variable.
  1020. * @param uniformName Name of the variable.
  1021. * @param array array to be set.
  1022. * @returns this effect.
  1023. */
  1024. Effect.prototype.setFloatArray = function (uniformName, array) {
  1025. this._valueCache[uniformName] = null;
  1026. this._engine.setFloatArray(this.getUniform(uniformName), array);
  1027. return this;
  1028. };
  1029. /**
  1030. * 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)
  1031. * @param uniformName Name of the variable.
  1032. * @param array array to be set.
  1033. * @returns this effect.
  1034. */
  1035. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  1036. this._valueCache[uniformName] = null;
  1037. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  1038. return this;
  1039. };
  1040. /**
  1041. * 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)
  1042. * @param uniformName Name of the variable.
  1043. * @param array array to be set.
  1044. * @returns this effect.
  1045. */
  1046. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  1047. this._valueCache[uniformName] = null;
  1048. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  1049. return this;
  1050. };
  1051. /**
  1052. * 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)
  1053. * @param uniformName Name of the variable.
  1054. * @param array array to be set.
  1055. * @returns this effect.
  1056. */
  1057. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  1058. this._valueCache[uniformName] = null;
  1059. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1060. return this;
  1061. };
  1062. /**
  1063. * Sets an array on a uniform variable.
  1064. * @param uniformName Name of the variable.
  1065. * @param array array to be set.
  1066. * @returns this effect.
  1067. */
  1068. Effect.prototype.setArray = function (uniformName, array) {
  1069. this._valueCache[uniformName] = null;
  1070. this._engine.setArray(this.getUniform(uniformName), array);
  1071. return this;
  1072. };
  1073. /**
  1074. * 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)
  1075. * @param uniformName Name of the variable.
  1076. * @param array array to be set.
  1077. * @returns this effect.
  1078. */
  1079. Effect.prototype.setArray2 = function (uniformName, array) {
  1080. this._valueCache[uniformName] = null;
  1081. this._engine.setArray2(this.getUniform(uniformName), array);
  1082. return this;
  1083. };
  1084. /**
  1085. * 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)
  1086. * @param uniformName Name of the variable.
  1087. * @param array array to be set.
  1088. * @returns this effect.
  1089. */
  1090. Effect.prototype.setArray3 = function (uniformName, array) {
  1091. this._valueCache[uniformName] = null;
  1092. this._engine.setArray3(this.getUniform(uniformName), array);
  1093. return this;
  1094. };
  1095. /**
  1096. * 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)
  1097. * @param uniformName Name of the variable.
  1098. * @param array array to be set.
  1099. * @returns this effect.
  1100. */
  1101. Effect.prototype.setArray4 = function (uniformName, array) {
  1102. this._valueCache[uniformName] = null;
  1103. this._engine.setArray4(this.getUniform(uniformName), array);
  1104. return this;
  1105. };
  1106. /**
  1107. * Sets matrices on a uniform variable.
  1108. * @param uniformName Name of the variable.
  1109. * @param matrices matrices to be set.
  1110. * @returns this effect.
  1111. */
  1112. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1113. if (!matrices) {
  1114. return this;
  1115. }
  1116. this._valueCache[uniformName] = null;
  1117. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1118. return this;
  1119. };
  1120. /**
  1121. * Sets matrix on a uniform variable.
  1122. * @param uniformName Name of the variable.
  1123. * @param matrix matrix to be set.
  1124. * @returns this effect.
  1125. */
  1126. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1127. if (this._cacheMatrix(uniformName, matrix)) {
  1128. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1129. }
  1130. return this;
  1131. };
  1132. /**
  1133. * 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)
  1134. * @param uniformName Name of the variable.
  1135. * @param matrix matrix to be set.
  1136. * @returns this effect.
  1137. */
  1138. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1139. this._valueCache[uniformName] = null;
  1140. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1141. return this;
  1142. };
  1143. /**
  1144. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1145. * @param uniformName Name of the variable.
  1146. * @param matrix matrix to be set.
  1147. * @returns this effect.
  1148. */
  1149. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1150. this._valueCache[uniformName] = null;
  1151. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a float on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param value value to be set.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setFloat = function (uniformName, value) {
  1161. var cache = this._valueCache[uniformName];
  1162. if (cache !== undefined && cache === value)
  1163. return this;
  1164. this._valueCache[uniformName] = value;
  1165. this._engine.setFloat(this.getUniform(uniformName), value);
  1166. return this;
  1167. };
  1168. /**
  1169. * Sets a boolean on a uniform variable.
  1170. * @param uniformName Name of the variable.
  1171. * @param bool value to be set.
  1172. * @returns this effect.
  1173. */
  1174. Effect.prototype.setBool = function (uniformName, bool) {
  1175. var cache = this._valueCache[uniformName];
  1176. if (cache !== undefined && cache === bool)
  1177. return this;
  1178. this._valueCache[uniformName] = bool;
  1179. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1180. return this;
  1181. };
  1182. /**
  1183. * Sets a Vector2 on a uniform variable.
  1184. * @param uniformName Name of the variable.
  1185. * @param vector2 vector2 to be set.
  1186. * @returns this effect.
  1187. */
  1188. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1189. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1190. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1191. }
  1192. return this;
  1193. };
  1194. /**
  1195. * Sets a float2 on a uniform variable.
  1196. * @param uniformName Name of the variable.
  1197. * @param x First float in float2.
  1198. * @param y Second float in float2.
  1199. * @returns this effect.
  1200. */
  1201. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1202. if (this._cacheFloat2(uniformName, x, y)) {
  1203. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1204. }
  1205. return this;
  1206. };
  1207. /**
  1208. * Sets a Vector3 on a uniform variable.
  1209. * @param uniformName Name of the variable.
  1210. * @param vector3 Value to be set.
  1211. * @returns this effect.
  1212. */
  1213. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1214. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1215. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1216. }
  1217. return this;
  1218. };
  1219. /**
  1220. * Sets a float3 on a uniform variable.
  1221. * @param uniformName Name of the variable.
  1222. * @param x First float in float3.
  1223. * @param y Second float in float3.
  1224. * @param z Third float in float3.
  1225. * @returns this effect.
  1226. */
  1227. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1228. if (this._cacheFloat3(uniformName, x, y, z)) {
  1229. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1230. }
  1231. return this;
  1232. };
  1233. /**
  1234. * Sets a Vector4 on a uniform variable.
  1235. * @param uniformName Name of the variable.
  1236. * @param vector4 Value to be set.
  1237. * @returns this effect.
  1238. */
  1239. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1240. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1241. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1242. }
  1243. return this;
  1244. };
  1245. /**
  1246. * Sets a float4 on a uniform variable.
  1247. * @param uniformName Name of the variable.
  1248. * @param x First float in float4.
  1249. * @param y Second float in float4.
  1250. * @param z Third float in float4.
  1251. * @param w Fourth float in float4.
  1252. * @returns this effect.
  1253. */
  1254. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1255. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1256. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1257. }
  1258. return this;
  1259. };
  1260. /**
  1261. * Sets a Color3 on a uniform variable.
  1262. * @param uniformName Name of the variable.
  1263. * @param color3 Value to be set.
  1264. * @returns this effect.
  1265. */
  1266. Effect.prototype.setColor3 = function (uniformName, color3) {
  1267. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1268. this._engine.setColor3(this.getUniform(uniformName), color3);
  1269. }
  1270. return this;
  1271. };
  1272. /**
  1273. * Sets a Color4 on a uniform variable.
  1274. * @param uniformName Name of the variable.
  1275. * @param color3 Value to be set.
  1276. * @param alpha Alpha value to be set.
  1277. * @returns this effect.
  1278. */
  1279. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1280. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1281. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1282. }
  1283. return this;
  1284. };
  1285. /**
  1286. * Sets a Color4 on a uniform variable
  1287. * @param uniformName defines the name of the variable
  1288. * @param color4 defines the value to be set
  1289. * @returns this effect.
  1290. */
  1291. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1292. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1293. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1294. }
  1295. return this;
  1296. };
  1297. /**
  1298. * Resets the cache of effects.
  1299. */
  1300. Effect.ResetCache = function () {
  1301. Effect._baseCache = {};
  1302. };
  1303. Effect._uniqueIdSeed = 0;
  1304. Effect._baseCache = {};
  1305. /**
  1306. * Store of each shader (The can be looked up using effect.key)
  1307. */
  1308. Effect.ShadersStore = {};
  1309. /**
  1310. * Store of each included file for a shader (The can be looked up using effect.key)
  1311. */
  1312. Effect.IncludesShadersStore = {};
  1313. return Effect;
  1314. }());
  1315. BABYLON.Effect = Effect;
  1316. })(BABYLON || (BABYLON = {}));
  1317. //# sourceMappingURL=babylon.effect.js.map
  1318. //# sourceMappingURL=babylon.types.js.map
  1319. var BABYLON;
  1320. (function (BABYLON) {
  1321. var KeyboardEventTypes = /** @class */ (function () {
  1322. function KeyboardEventTypes() {
  1323. }
  1324. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1325. get: function () {
  1326. return KeyboardEventTypes._KEYDOWN;
  1327. },
  1328. enumerable: true,
  1329. configurable: true
  1330. });
  1331. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1332. get: function () {
  1333. return KeyboardEventTypes._KEYUP;
  1334. },
  1335. enumerable: true,
  1336. configurable: true
  1337. });
  1338. KeyboardEventTypes._KEYDOWN = 0x01;
  1339. KeyboardEventTypes._KEYUP = 0x02;
  1340. return KeyboardEventTypes;
  1341. }());
  1342. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1343. var KeyboardInfo = /** @class */ (function () {
  1344. function KeyboardInfo(type, event) {
  1345. this.type = type;
  1346. this.event = event;
  1347. }
  1348. return KeyboardInfo;
  1349. }());
  1350. BABYLON.KeyboardInfo = KeyboardInfo;
  1351. /**
  1352. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1353. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1354. */
  1355. var KeyboardInfoPre = /** @class */ (function (_super) {
  1356. __extends(KeyboardInfoPre, _super);
  1357. function KeyboardInfoPre(type, event) {
  1358. var _this = _super.call(this, type, event) || this;
  1359. _this.skipOnPointerObservable = false;
  1360. return _this;
  1361. }
  1362. return KeyboardInfoPre;
  1363. }(KeyboardInfo));
  1364. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1365. })(BABYLON || (BABYLON = {}));
  1366. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1367. var BABYLON;
  1368. (function (BABYLON) {
  1369. var PointerEventTypes = /** @class */ (function () {
  1370. function PointerEventTypes() {
  1371. }
  1372. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1373. get: function () {
  1374. return PointerEventTypes._POINTERDOWN;
  1375. },
  1376. enumerable: true,
  1377. configurable: true
  1378. });
  1379. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1380. get: function () {
  1381. return PointerEventTypes._POINTERUP;
  1382. },
  1383. enumerable: true,
  1384. configurable: true
  1385. });
  1386. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1387. get: function () {
  1388. return PointerEventTypes._POINTERMOVE;
  1389. },
  1390. enumerable: true,
  1391. configurable: true
  1392. });
  1393. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1394. get: function () {
  1395. return PointerEventTypes._POINTERWHEEL;
  1396. },
  1397. enumerable: true,
  1398. configurable: true
  1399. });
  1400. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1401. get: function () {
  1402. return PointerEventTypes._POINTERPICK;
  1403. },
  1404. enumerable: true,
  1405. configurable: true
  1406. });
  1407. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1408. get: function () {
  1409. return PointerEventTypes._POINTERTAP;
  1410. },
  1411. enumerable: true,
  1412. configurable: true
  1413. });
  1414. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1415. get: function () {
  1416. return PointerEventTypes._POINTERDOUBLETAP;
  1417. },
  1418. enumerable: true,
  1419. configurable: true
  1420. });
  1421. PointerEventTypes._POINTERDOWN = 0x01;
  1422. PointerEventTypes._POINTERUP = 0x02;
  1423. PointerEventTypes._POINTERMOVE = 0x04;
  1424. PointerEventTypes._POINTERWHEEL = 0x08;
  1425. PointerEventTypes._POINTERPICK = 0x10;
  1426. PointerEventTypes._POINTERTAP = 0x20;
  1427. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1428. return PointerEventTypes;
  1429. }());
  1430. BABYLON.PointerEventTypes = PointerEventTypes;
  1431. var PointerInfoBase = /** @class */ (function () {
  1432. function PointerInfoBase(type, event) {
  1433. this.type = type;
  1434. this.event = event;
  1435. }
  1436. return PointerInfoBase;
  1437. }());
  1438. BABYLON.PointerInfoBase = PointerInfoBase;
  1439. /**
  1440. * This class is used to store pointer related info for the onPrePointerObservable event.
  1441. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1442. */
  1443. var PointerInfoPre = /** @class */ (function (_super) {
  1444. __extends(PointerInfoPre, _super);
  1445. function PointerInfoPre(type, event, localX, localY) {
  1446. var _this = _super.call(this, type, event) || this;
  1447. _this.skipOnPointerObservable = false;
  1448. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1449. return _this;
  1450. }
  1451. return PointerInfoPre;
  1452. }(PointerInfoBase));
  1453. BABYLON.PointerInfoPre = PointerInfoPre;
  1454. /**
  1455. * This type contains all the data related to a pointer event in Babylon.js.
  1456. * 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.
  1457. */
  1458. var PointerInfo = /** @class */ (function (_super) {
  1459. __extends(PointerInfo, _super);
  1460. function PointerInfo(type, event, pickInfo) {
  1461. var _this = _super.call(this, type, event) || this;
  1462. _this.pickInfo = pickInfo;
  1463. return _this;
  1464. }
  1465. return PointerInfo;
  1466. }(PointerInfoBase));
  1467. BABYLON.PointerInfo = PointerInfo;
  1468. })(BABYLON || (BABYLON = {}));
  1469. //# sourceMappingURL=babylon.pointerEvents.js.map
  1470. var BABYLON;
  1471. (function (BABYLON) {
  1472. BABYLON.ToGammaSpace = 1 / 2.2;
  1473. BABYLON.ToLinearSpace = 2.2;
  1474. BABYLON.Epsilon = 0.001;
  1475. /**
  1476. * Class used to hold a RBG color
  1477. */
  1478. var Color3 = /** @class */ (function () {
  1479. /**
  1480. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1481. * @param r defines the red component (between 0 and 1, default is 0)
  1482. * @param g defines the green component (between 0 and 1, default is 0)
  1483. * @param b defines the blue component (between 0 and 1, default is 0)
  1484. */
  1485. function Color3(
  1486. /**
  1487. * Defines the red component (between 0 and 1, default is 0)
  1488. */
  1489. r,
  1490. /**
  1491. * Defines the green component (between 0 and 1, default is 0)
  1492. */
  1493. g,
  1494. /**
  1495. * Defines the blue component (between 0 and 1, default is 0)
  1496. */
  1497. b) {
  1498. if (r === void 0) { r = 0; }
  1499. if (g === void 0) { g = 0; }
  1500. if (b === void 0) { b = 0; }
  1501. this.r = r;
  1502. this.g = g;
  1503. this.b = b;
  1504. }
  1505. /**
  1506. * Creates a string with the Color3 current values
  1507. * @returns the string representation of the Color3 object
  1508. */
  1509. Color3.prototype.toString = function () {
  1510. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1511. };
  1512. /**
  1513. * Returns the string "Color3"
  1514. * @returns "Color3"
  1515. */
  1516. Color3.prototype.getClassName = function () {
  1517. return "Color3";
  1518. };
  1519. /**
  1520. * Compute the Color3 hash code
  1521. * @returns an unique number that can be used to hash Color3 objects
  1522. */
  1523. Color3.prototype.getHashCode = function () {
  1524. var hash = this.r || 0;
  1525. hash = (hash * 397) ^ (this.g || 0);
  1526. hash = (hash * 397) ^ (this.b || 0);
  1527. return hash;
  1528. };
  1529. // Operators
  1530. /**
  1531. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1532. * @param array defines the array where to store the r,g,b components
  1533. * @param index defines an optional index in the target array to define where to start storing values
  1534. * @returns the current Color3 object
  1535. */
  1536. Color3.prototype.toArray = function (array, index) {
  1537. if (index === undefined) {
  1538. index = 0;
  1539. }
  1540. array[index] = this.r;
  1541. array[index + 1] = this.g;
  1542. array[index + 2] = this.b;
  1543. return this;
  1544. };
  1545. /**
  1546. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1547. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1548. * @returns a new {BABYLON.Color4} object
  1549. */
  1550. Color3.prototype.toColor4 = function (alpha) {
  1551. if (alpha === void 0) { alpha = 1; }
  1552. return new Color4(this.r, this.g, this.b, alpha);
  1553. };
  1554. /**
  1555. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1556. * @returns the new array
  1557. */
  1558. Color3.prototype.asArray = function () {
  1559. var result = new Array();
  1560. this.toArray(result, 0);
  1561. return result;
  1562. };
  1563. /**
  1564. * Returns the luminance value
  1565. * @returns a float value
  1566. */
  1567. Color3.prototype.toLuminance = function () {
  1568. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1569. };
  1570. /**
  1571. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1572. * @param otherColor defines the second operand
  1573. * @returns the new Color3 object
  1574. */
  1575. Color3.prototype.multiply = function (otherColor) {
  1576. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1577. };
  1578. /**
  1579. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1580. * @param otherColor defines the second operand
  1581. * @param result defines the Color3 object where to store the result
  1582. * @returns the current Color3
  1583. */
  1584. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1585. result.r = this.r * otherColor.r;
  1586. result.g = this.g * otherColor.g;
  1587. result.b = this.b * otherColor.b;
  1588. return this;
  1589. };
  1590. /**
  1591. * Determines equality between Color3 objects
  1592. * @param otherColor defines the second operand
  1593. * @returns true if the rgb values are equal to the given ones
  1594. */
  1595. Color3.prototype.equals = function (otherColor) {
  1596. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1597. };
  1598. /**
  1599. * Determines equality between the current Color3 object and a set of r,b,g values
  1600. * @param r defines the red component to check
  1601. * @param g defines the green component to check
  1602. * @param b defines the blue component to check
  1603. * @returns true if the rgb values are equal to the given ones
  1604. */
  1605. Color3.prototype.equalsFloats = function (r, g, b) {
  1606. return this.r === r && this.g === g && this.b === b;
  1607. };
  1608. /**
  1609. * Multiplies in place each rgb value by scale
  1610. * @param scale defines the scaling factor
  1611. * @returns the updated Color3
  1612. */
  1613. Color3.prototype.scale = function (scale) {
  1614. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1615. };
  1616. /**
  1617. * Multiplies the rgb values by scale and stores the result into "result"
  1618. * @param scale defines the scaling factor
  1619. * @param result defines the Color3 object where to store the result
  1620. * @returns the unmodified current Color3
  1621. */
  1622. Color3.prototype.scaleToRef = function (scale, result) {
  1623. result.r = this.r * scale;
  1624. result.g = this.g * scale;
  1625. result.b = this.b * scale;
  1626. return this;
  1627. };
  1628. /**
  1629. * Scale the current Color3 values by a factor and add the result to a given Color3
  1630. * @param scale defines the scale factor
  1631. * @param result defines color to store the result into
  1632. * @returns the unmodified current Color3
  1633. */
  1634. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1635. result.r += this.r * scale;
  1636. result.g += this.g * scale;
  1637. result.b += this.b * scale;
  1638. return this;
  1639. };
  1640. /**
  1641. * Clamps the rgb values by the min and max values and stores the result into "result"
  1642. * @param min defines minimum clamping value (default is 0)
  1643. * @param max defines maximum clamping value (default is 1)
  1644. * @param result defines color to store the result into
  1645. * @returns the original Color3
  1646. */
  1647. Color3.prototype.clampToRef = function (min, max, result) {
  1648. if (min === void 0) { min = 0; }
  1649. if (max === void 0) { max = 1; }
  1650. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1651. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1652. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1653. return this;
  1654. };
  1655. /**
  1656. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1657. * @param otherColor defines the second operand
  1658. * @returns the new Color3
  1659. */
  1660. Color3.prototype.add = function (otherColor) {
  1661. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1662. };
  1663. /**
  1664. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1665. * @param otherColor defines the second operand
  1666. * @param result defines Color3 object to store the result into
  1667. * @returns the unmodified current Color3
  1668. */
  1669. Color3.prototype.addToRef = function (otherColor, result) {
  1670. result.r = this.r + otherColor.r;
  1671. result.g = this.g + otherColor.g;
  1672. result.b = this.b + otherColor.b;
  1673. return this;
  1674. };
  1675. /**
  1676. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1677. * @param otherColor defines the second operand
  1678. * @returns the new Color3
  1679. */
  1680. Color3.prototype.subtract = function (otherColor) {
  1681. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1682. };
  1683. /**
  1684. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1685. * @param otherColor defines the second operand
  1686. * @param result defines Color3 object to store the result into
  1687. * @returns the unmodified current Color3
  1688. */
  1689. Color3.prototype.subtractToRef = function (otherColor, result) {
  1690. result.r = this.r - otherColor.r;
  1691. result.g = this.g - otherColor.g;
  1692. result.b = this.b - otherColor.b;
  1693. return this;
  1694. };
  1695. /**
  1696. * Copy the current object
  1697. * @returns a new Color3 copied the current one
  1698. */
  1699. Color3.prototype.clone = function () {
  1700. return new Color3(this.r, this.g, this.b);
  1701. };
  1702. /**
  1703. * Copies the rgb values from the source in the current Color3
  1704. * @param source defines the source Color3 object
  1705. * @returns the updated Color3 object
  1706. */
  1707. Color3.prototype.copyFrom = function (source) {
  1708. this.r = source.r;
  1709. this.g = source.g;
  1710. this.b = source.b;
  1711. return this;
  1712. };
  1713. /**
  1714. * Updates the Color3 rgb values from the given floats
  1715. * @param r defines the red component to read from
  1716. * @param g defines the green component to read from
  1717. * @param b defines the blue component to read from
  1718. * @returns the current Color3 object
  1719. */
  1720. Color3.prototype.copyFromFloats = function (r, g, b) {
  1721. this.r = r;
  1722. this.g = g;
  1723. this.b = b;
  1724. return this;
  1725. };
  1726. /**
  1727. * Updates the Color3 rgb values from the given floats
  1728. * @param r defines the red component to read from
  1729. * @param g defines the green component to read from
  1730. * @param b defines the blue component to read from
  1731. * @returns the current Color3 object
  1732. */
  1733. Color3.prototype.set = function (r, g, b) {
  1734. return this.copyFromFloats(r, g, b);
  1735. };
  1736. /**
  1737. * Compute the Color3 hexadecimal code as a string
  1738. * @returns a string containing the hexadecimal representation of the Color3 object
  1739. */
  1740. Color3.prototype.toHexString = function () {
  1741. var intR = (this.r * 255) | 0;
  1742. var intG = (this.g * 255) | 0;
  1743. var intB = (this.b * 255) | 0;
  1744. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1745. };
  1746. /**
  1747. * Computes a new Color3 converted from the current one to linear space
  1748. * @returns a new Color3 object
  1749. */
  1750. Color3.prototype.toLinearSpace = function () {
  1751. var convertedColor = new Color3();
  1752. this.toLinearSpaceToRef(convertedColor);
  1753. return convertedColor;
  1754. };
  1755. /**
  1756. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1757. * @param convertedColor defines the Color3 object where to store the linear space version
  1758. * @returns the unmodified Color3
  1759. */
  1760. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1761. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1762. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1763. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1764. return this;
  1765. };
  1766. /**
  1767. * Computes a new Color3 converted from the current one to gamma space
  1768. * @returns a new Color3 object
  1769. */
  1770. Color3.prototype.toGammaSpace = function () {
  1771. var convertedColor = new Color3();
  1772. this.toGammaSpaceToRef(convertedColor);
  1773. return convertedColor;
  1774. };
  1775. /**
  1776. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1777. * @param convertedColor defines the Color3 object where to store the gamma space version
  1778. * @returns the unmodified Color3
  1779. */
  1780. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1781. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1782. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1783. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1784. return this;
  1785. };
  1786. // Statics
  1787. /**
  1788. * Creates a new Color3 from the string containing valid hexadecimal values
  1789. * @param hex defines a string containing valid hexadecimal values
  1790. * @returns a new Color3 object
  1791. */
  1792. Color3.FromHexString = function (hex) {
  1793. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1794. return new Color3(0, 0, 0);
  1795. }
  1796. var r = parseInt(hex.substring(1, 3), 16);
  1797. var g = parseInt(hex.substring(3, 5), 16);
  1798. var b = parseInt(hex.substring(5, 7), 16);
  1799. return Color3.FromInts(r, g, b);
  1800. };
  1801. /**
  1802. * Creates a new Vector3 from the starting index of the given array
  1803. * @param array defines the source array
  1804. * @param offset defines an offset in the source array
  1805. * @returns a new Color3 object
  1806. */
  1807. Color3.FromArray = function (array, offset) {
  1808. if (offset === void 0) { offset = 0; }
  1809. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1810. };
  1811. /**
  1812. * Creates a new Color3 from integer values (< 256)
  1813. * @param r defines the red component to read from (value between 0 and 255)
  1814. * @param g defines the green component to read from (value between 0 and 255)
  1815. * @param b defines the blue component to read from (value between 0 and 255)
  1816. * @returns a new Color3 object
  1817. */
  1818. Color3.FromInts = function (r, g, b) {
  1819. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1820. };
  1821. /**
  1822. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1823. * @param start defines the start Color3 value
  1824. * @param end defines the end Color3 value
  1825. * @param amount defines the gradient value between start and end
  1826. * @returns a new Color3 object
  1827. */
  1828. Color3.Lerp = function (start, end, amount) {
  1829. var r = start.r + ((end.r - start.r) * amount);
  1830. var g = start.g + ((end.g - start.g) * amount);
  1831. var b = start.b + ((end.b - start.b) * amount);
  1832. return new Color3(r, g, b);
  1833. };
  1834. /**
  1835. * Returns a Color3 value containing a red color
  1836. * @returns a new Color3 object
  1837. */
  1838. Color3.Red = function () { return new Color3(1, 0, 0); };
  1839. /**
  1840. * Returns a Color3 value containing a green color
  1841. * @returns a new Color3 object
  1842. */
  1843. Color3.Green = function () { return new Color3(0, 1, 0); };
  1844. /**
  1845. * Returns a Color3 value containing a blue color
  1846. * @returns a new Color3 object
  1847. */
  1848. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1849. /**
  1850. * Returns a Color3 value containing a black color
  1851. * @returns a new Color3 object
  1852. */
  1853. Color3.Black = function () { return new Color3(0, 0, 0); };
  1854. /**
  1855. * Returns a Color3 value containing a white color
  1856. * @returns a new Color3 object
  1857. */
  1858. Color3.White = function () { return new Color3(1, 1, 1); };
  1859. /**
  1860. * Returns a Color3 value containing a purple color
  1861. * @returns a new Color3 object
  1862. */
  1863. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1864. /**
  1865. * Returns a Color3 value containing a magenta color
  1866. * @returns a new Color3 object
  1867. */
  1868. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1869. /**
  1870. * Returns a Color3 value containing a yellow color
  1871. * @returns a new Color3 object
  1872. */
  1873. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1874. /**
  1875. * Returns a Color3 value containing a gray color
  1876. * @returns a new Color3 object
  1877. */
  1878. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1879. /**
  1880. * Returns a Color3 value containing a teal color
  1881. * @returns a new Color3 object
  1882. */
  1883. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1884. /**
  1885. * Returns a Color3 value containing a random color
  1886. * @returns a new Color3 object
  1887. */
  1888. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1889. return Color3;
  1890. }());
  1891. BABYLON.Color3 = Color3;
  1892. /**
  1893. * Class used to hold a RBGA color
  1894. */
  1895. var Color4 = /** @class */ (function () {
  1896. /**
  1897. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1898. * @param r defines the red component (between 0 and 1, default is 0)
  1899. * @param g defines the green component (between 0 and 1, default is 0)
  1900. * @param b defines the blue component (between 0 and 1, default is 0)
  1901. * @param a defines the alpha component (between 0 and 1, default is 1)
  1902. */
  1903. function Color4(
  1904. /**
  1905. * Defines the red component (between 0 and 1, default is 0)
  1906. */
  1907. r,
  1908. /**
  1909. * Defines the green component (between 0 and 1, default is 0)
  1910. */
  1911. g,
  1912. /**
  1913. * Defines the blue component (between 0 and 1, default is 0)
  1914. */
  1915. b,
  1916. /**
  1917. * Defines the alpha component (between 0 and 1, default is 1)
  1918. */
  1919. a) {
  1920. if (r === void 0) { r = 0; }
  1921. if (g === void 0) { g = 0; }
  1922. if (b === void 0) { b = 0; }
  1923. if (a === void 0) { a = 1; }
  1924. this.r = r;
  1925. this.g = g;
  1926. this.b = b;
  1927. this.a = a;
  1928. }
  1929. // Operators
  1930. /**
  1931. * Adds in place the given Color4 values to the current Color4 object
  1932. * @param right defines the second operand
  1933. * @returns the current updated Color4 object
  1934. */
  1935. Color4.prototype.addInPlace = function (right) {
  1936. this.r += right.r;
  1937. this.g += right.g;
  1938. this.b += right.b;
  1939. this.a += right.a;
  1940. return this;
  1941. };
  1942. /**
  1943. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1944. * @returns the new array
  1945. */
  1946. Color4.prototype.asArray = function () {
  1947. var result = new Array();
  1948. this.toArray(result, 0);
  1949. return result;
  1950. };
  1951. /**
  1952. * Stores from the starting index in the given array the Color4 successive values
  1953. * @param array defines the array where to store the r,g,b components
  1954. * @param index defines an optional index in the target array to define where to start storing values
  1955. * @returns the current Color4 object
  1956. */
  1957. Color4.prototype.toArray = function (array, index) {
  1958. if (index === undefined) {
  1959. index = 0;
  1960. }
  1961. array[index] = this.r;
  1962. array[index + 1] = this.g;
  1963. array[index + 2] = this.b;
  1964. array[index + 3] = this.a;
  1965. return this;
  1966. };
  1967. /**
  1968. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1969. * @param right defines the second operand
  1970. * @returns a new Color4 object
  1971. */
  1972. Color4.prototype.add = function (right) {
  1973. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1974. };
  1975. /**
  1976. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1977. * @param right defines the second operand
  1978. * @returns a new Color4 object
  1979. */
  1980. Color4.prototype.subtract = function (right) {
  1981. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1982. };
  1983. /**
  1984. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1985. * @param right defines the second operand
  1986. * @param result defines the Color4 object where to store the result
  1987. * @returns the current Color4 object
  1988. */
  1989. Color4.prototype.subtractToRef = function (right, result) {
  1990. result.r = this.r - right.r;
  1991. result.g = this.g - right.g;
  1992. result.b = this.b - right.b;
  1993. result.a = this.a - right.a;
  1994. return this;
  1995. };
  1996. /**
  1997. * Creates a new Color4 with the current Color4 values multiplied by scale
  1998. * @param scale defines the scaling factor to apply
  1999. * @returns a new Color4 object
  2000. */
  2001. Color4.prototype.scale = function (scale) {
  2002. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  2003. };
  2004. /**
  2005. * Multiplies the current Color4 values by scale and stores the result in "result"
  2006. * @param scale defines the scaling factor to apply
  2007. * @param result defines the Color4 object where to store the result
  2008. * @returns the current unmodified Color4
  2009. */
  2010. Color4.prototype.scaleToRef = function (scale, result) {
  2011. result.r = this.r * scale;
  2012. result.g = this.g * scale;
  2013. result.b = this.b * scale;
  2014. result.a = this.a * scale;
  2015. return this;
  2016. };
  2017. /**
  2018. * Scale the current Color4 values by a factor and add the result to a given Color4
  2019. * @param scale defines the scale factor
  2020. * @param result defines the Color4 object where to store the result
  2021. * @returns the unmodified current Color4
  2022. */
  2023. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2024. result.r += this.r * scale;
  2025. result.g += this.g * scale;
  2026. result.b += this.b * scale;
  2027. result.a += this.a * scale;
  2028. return this;
  2029. };
  2030. /**
  2031. * Clamps the rgb values by the min and max values and stores the result into "result"
  2032. * @param min defines minimum clamping value (default is 0)
  2033. * @param max defines maximum clamping value (default is 1)
  2034. * @param result defines color to store the result into.
  2035. * @returns the cuurent Color4
  2036. */
  2037. Color4.prototype.clampToRef = function (min, max, result) {
  2038. if (min === void 0) { min = 0; }
  2039. if (max === void 0) { max = 1; }
  2040. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2041. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2042. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2043. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2044. return this;
  2045. };
  2046. /**
  2047. * Multipy an Color4 value by another and return a new Color4 object
  2048. * @param color defines the Color4 value to multiply by
  2049. * @returns a new Color4 object
  2050. */
  2051. Color4.prototype.multiply = function (color) {
  2052. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2053. };
  2054. /**
  2055. * Multipy a Color4 value by another and push the result in a reference value
  2056. * @param color defines the Color4 value to multiply by
  2057. * @param result defines the Color4 to fill the result in
  2058. * @returns the result Color4
  2059. */
  2060. Color4.prototype.multiplyToRef = function (color, result) {
  2061. result.r = this.r * color.r;
  2062. result.g = this.g * color.g;
  2063. result.b = this.b * color.b;
  2064. result.a = this.a * color.a;
  2065. return result;
  2066. };
  2067. /**
  2068. * Creates a string with the Color4 current values
  2069. * @returns the string representation of the Color4 object
  2070. */
  2071. Color4.prototype.toString = function () {
  2072. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2073. };
  2074. /**
  2075. * Returns the string "Color4"
  2076. * @returns "Color4"
  2077. */
  2078. Color4.prototype.getClassName = function () {
  2079. return "Color4";
  2080. };
  2081. /**
  2082. * Compute the Color4 hash code
  2083. * @returns an unique number that can be used to hash Color4 objects
  2084. */
  2085. Color4.prototype.getHashCode = function () {
  2086. var hash = this.r || 0;
  2087. hash = (hash * 397) ^ (this.g || 0);
  2088. hash = (hash * 397) ^ (this.b || 0);
  2089. hash = (hash * 397) ^ (this.a || 0);
  2090. return hash;
  2091. };
  2092. /**
  2093. * Creates a new Color4 copied from the current one
  2094. * @returns a new Color4 object
  2095. */
  2096. Color4.prototype.clone = function () {
  2097. return new Color4(this.r, this.g, this.b, this.a);
  2098. };
  2099. /**
  2100. * Copies the given Color4 values into the current one
  2101. * @param source defines the source Color4 object
  2102. * @returns the current updated Color4 object
  2103. */
  2104. Color4.prototype.copyFrom = function (source) {
  2105. this.r = source.r;
  2106. this.g = source.g;
  2107. this.b = source.b;
  2108. this.a = source.a;
  2109. return this;
  2110. };
  2111. /**
  2112. * Copies the given float values into the current one
  2113. * @param r defines the red component to read from
  2114. * @param g defines the green component to read from
  2115. * @param b defines the blue component to read from
  2116. * @param a defines the alpha component to read from
  2117. * @returns the current updated Color4 object
  2118. */
  2119. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2120. this.r = r;
  2121. this.g = g;
  2122. this.b = b;
  2123. this.a = a;
  2124. return this;
  2125. };
  2126. /**
  2127. * Copies the given float values into the current one
  2128. * @param r defines the red component to read from
  2129. * @param g defines the green component to read from
  2130. * @param b defines the blue component to read from
  2131. * @param a defines the alpha component to read from
  2132. * @returns the current updated Color4 object
  2133. */
  2134. Color4.prototype.set = function (r, g, b, a) {
  2135. return this.copyFromFloats(r, g, b, a);
  2136. };
  2137. /**
  2138. * Compute the Color4 hexadecimal code as a string
  2139. * @returns a string containing the hexadecimal representation of the Color4 object
  2140. */
  2141. Color4.prototype.toHexString = function () {
  2142. var intR = (this.r * 255) | 0;
  2143. var intG = (this.g * 255) | 0;
  2144. var intB = (this.b * 255) | 0;
  2145. var intA = (this.a * 255) | 0;
  2146. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2147. };
  2148. /**
  2149. * Computes a new Color4 converted from the current one to linear space
  2150. * @returns a new Color4 object
  2151. */
  2152. Color4.prototype.toLinearSpace = function () {
  2153. var convertedColor = new Color4();
  2154. this.toLinearSpaceToRef(convertedColor);
  2155. return convertedColor;
  2156. };
  2157. /**
  2158. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2159. * @param convertedColor defines the Color4 object where to store the linear space version
  2160. * @returns the unmodified Color4
  2161. */
  2162. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2163. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2164. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2165. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2166. convertedColor.a = this.a;
  2167. return this;
  2168. };
  2169. /**
  2170. * Computes a new Color4 converted from the current one to gamma space
  2171. * @returns a new Color4 object
  2172. */
  2173. Color4.prototype.toGammaSpace = function () {
  2174. var convertedColor = new Color4();
  2175. this.toGammaSpaceToRef(convertedColor);
  2176. return convertedColor;
  2177. };
  2178. /**
  2179. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2180. * @param convertedColor defines the Color4 object where to store the gamma space version
  2181. * @returns the unmodified Color4
  2182. */
  2183. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2184. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2185. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2186. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2187. convertedColor.a = this.a;
  2188. return this;
  2189. };
  2190. // Statics
  2191. /**
  2192. * Creates a new Color4 from the string containing valid hexadecimal values
  2193. * @param hex defines a string containing valid hexadecimal values
  2194. * @returns a new Color4 object
  2195. */
  2196. Color4.FromHexString = function (hex) {
  2197. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2198. return new Color4(0.0, 0.0, 0.0, 0.0);
  2199. }
  2200. var r = parseInt(hex.substring(1, 3), 16);
  2201. var g = parseInt(hex.substring(3, 5), 16);
  2202. var b = parseInt(hex.substring(5, 7), 16);
  2203. var a = parseInt(hex.substring(7, 9), 16);
  2204. return Color4.FromInts(r, g, b, a);
  2205. };
  2206. /**
  2207. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2208. * @param left defines the start value
  2209. * @param right defines the end value
  2210. * @param amount defines the gradient factor
  2211. * @returns a new Color4 object
  2212. */
  2213. Color4.Lerp = function (left, right, amount) {
  2214. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2215. Color4.LerpToRef(left, right, amount, result);
  2216. return result;
  2217. };
  2218. /**
  2219. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2220. * @param left defines the start value
  2221. * @param right defines the end value
  2222. * @param amount defines the gradient factor
  2223. * @param result defines the Color4 object where to store data
  2224. */
  2225. Color4.LerpToRef = function (left, right, amount, result) {
  2226. result.r = left.r + (right.r - left.r) * amount;
  2227. result.g = left.g + (right.g - left.g) * amount;
  2228. result.b = left.b + (right.b - left.b) * amount;
  2229. result.a = left.a + (right.a - left.a) * amount;
  2230. };
  2231. /**
  2232. * Creates a new Color4 from the starting index element of the given array
  2233. * @param array defines the source array to read from
  2234. * @param offset defines the offset in the source array
  2235. * @returns a new Color4 object
  2236. */
  2237. Color4.FromArray = function (array, offset) {
  2238. if (offset === void 0) { offset = 0; }
  2239. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2240. };
  2241. /**
  2242. * Creates a new Color3 from integer values (< 256)
  2243. * @param r defines the red component to read from (value between 0 and 255)
  2244. * @param g defines the green component to read from (value between 0 and 255)
  2245. * @param b defines the blue component to read from (value between 0 and 255)
  2246. * @param a defines the alpha component to read from (value between 0 and 255)
  2247. * @returns a new Color3 object
  2248. */
  2249. Color4.FromInts = function (r, g, b, a) {
  2250. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2251. };
  2252. /**
  2253. * Check the content of a given array and convert it to an array containing RGBA data
  2254. * If the original array was already containing count * 4 values then it is returned directly
  2255. * @param colors defines the array to check
  2256. * @param count defines the number of RGBA data to expect
  2257. * @returns an array containing count * 4 values (RGBA)
  2258. */
  2259. Color4.CheckColors4 = function (colors, count) {
  2260. // Check if color3 was used
  2261. if (colors.length === count * 3) {
  2262. var colors4 = [];
  2263. for (var index = 0; index < colors.length; index += 3) {
  2264. var newIndex = (index / 3) * 4;
  2265. colors4[newIndex] = colors[index];
  2266. colors4[newIndex + 1] = colors[index + 1];
  2267. colors4[newIndex + 2] = colors[index + 2];
  2268. colors4[newIndex + 3] = 1.0;
  2269. }
  2270. return colors4;
  2271. }
  2272. return colors;
  2273. };
  2274. return Color4;
  2275. }());
  2276. BABYLON.Color4 = Color4;
  2277. /**
  2278. * Class representing a vector containing 2 coordinates
  2279. */
  2280. var Vector2 = /** @class */ (function () {
  2281. /**
  2282. * Creates a new Vector2 from the given x and y coordinates
  2283. * @param x defines the first coordinate
  2284. * @param y defines the second coordinate
  2285. */
  2286. function Vector2(
  2287. /** defines the first coordinate */
  2288. x,
  2289. /** defines the second coordinate */
  2290. y) {
  2291. this.x = x;
  2292. this.y = y;
  2293. }
  2294. /**
  2295. * Gets a string with the Vector2 coordinates
  2296. * @returns a string with the Vector2 coordinates
  2297. */
  2298. Vector2.prototype.toString = function () {
  2299. return "{X: " + this.x + " Y:" + this.y + "}";
  2300. };
  2301. /**
  2302. * Gets class name
  2303. * @returns the string "Vector2"
  2304. */
  2305. Vector2.prototype.getClassName = function () {
  2306. return "Vector2";
  2307. };
  2308. /**
  2309. * Gets current vector hash code
  2310. * @returns the Vector2 hash code as a number
  2311. */
  2312. Vector2.prototype.getHashCode = function () {
  2313. var hash = this.x || 0;
  2314. hash = (hash * 397) ^ (this.y || 0);
  2315. return hash;
  2316. };
  2317. // Operators
  2318. /**
  2319. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2320. * @param array defines the source array
  2321. * @param index defines the offset in source array
  2322. * @returns the current Vector2
  2323. */
  2324. Vector2.prototype.toArray = function (array, index) {
  2325. if (index === void 0) { index = 0; }
  2326. array[index] = this.x;
  2327. array[index + 1] = this.y;
  2328. return this;
  2329. };
  2330. /**
  2331. * Copy the current vector to an array
  2332. * @returns a new array with 2 elements: the Vector2 coordinates.
  2333. */
  2334. Vector2.prototype.asArray = function () {
  2335. var result = new Array();
  2336. this.toArray(result, 0);
  2337. return result;
  2338. };
  2339. /**
  2340. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2341. * @param source defines the source Vector2
  2342. * @returns the current updated Vector2
  2343. */
  2344. Vector2.prototype.copyFrom = function (source) {
  2345. this.x = source.x;
  2346. this.y = source.y;
  2347. return this;
  2348. };
  2349. /**
  2350. * Sets the Vector2 coordinates with the given floats
  2351. * @param x defines the first coordinate
  2352. * @param y defines the second coordinate
  2353. * @returns the current updated Vector2
  2354. */
  2355. Vector2.prototype.copyFromFloats = function (x, y) {
  2356. this.x = x;
  2357. this.y = y;
  2358. return this;
  2359. };
  2360. /**
  2361. * Sets the Vector2 coordinates with the given floats
  2362. * @param x defines the first coordinate
  2363. * @param y defines the second coordinate
  2364. * @returns the current updated Vector2
  2365. */
  2366. Vector2.prototype.set = function (x, y) {
  2367. return this.copyFromFloats(x, y);
  2368. };
  2369. /**
  2370. * Add another vector with the current one
  2371. * @param otherVector defines the other vector
  2372. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2373. */
  2374. Vector2.prototype.add = function (otherVector) {
  2375. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2376. };
  2377. /**
  2378. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2379. * @param otherVector defines the other vector
  2380. * @param result defines the target vector
  2381. * @returns the unmodified current Vector2
  2382. */
  2383. Vector2.prototype.addToRef = function (otherVector, result) {
  2384. result.x = this.x + otherVector.x;
  2385. result.y = this.y + otherVector.y;
  2386. return this;
  2387. };
  2388. /**
  2389. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2390. * @param otherVector defines the other vector
  2391. * @returns the current updated Vector2
  2392. */
  2393. Vector2.prototype.addInPlace = function (otherVector) {
  2394. this.x += otherVector.x;
  2395. this.y += otherVector.y;
  2396. return this;
  2397. };
  2398. /**
  2399. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2400. * @param otherVector defines the other vector
  2401. * @returns a new Vector2
  2402. */
  2403. Vector2.prototype.addVector3 = function (otherVector) {
  2404. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2405. };
  2406. /**
  2407. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2408. * @param otherVector defines the other vector
  2409. * @returns a new Vector2
  2410. */
  2411. Vector2.prototype.subtract = function (otherVector) {
  2412. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2413. };
  2414. /**
  2415. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2416. * @param otherVector defines the other vector
  2417. * @param result defines the target vector
  2418. * @returns the unmodified current Vector2
  2419. */
  2420. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2421. result.x = this.x - otherVector.x;
  2422. result.y = this.y - otherVector.y;
  2423. return this;
  2424. };
  2425. /**
  2426. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2427. * @param otherVector defines the other vector
  2428. * @returns the current updated Vector2
  2429. */
  2430. Vector2.prototype.subtractInPlace = function (otherVector) {
  2431. this.x -= otherVector.x;
  2432. this.y -= otherVector.y;
  2433. return this;
  2434. };
  2435. /**
  2436. * Multiplies in place the current Vector2 coordinates by the given ones
  2437. * @param otherVector defines the other vector
  2438. * @returns the current updated Vector2
  2439. */
  2440. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2441. this.x *= otherVector.x;
  2442. this.y *= otherVector.y;
  2443. return this;
  2444. };
  2445. /**
  2446. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2447. * @param otherVector defines the other vector
  2448. * @returns a new Vector2
  2449. */
  2450. Vector2.prototype.multiply = function (otherVector) {
  2451. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2452. };
  2453. /**
  2454. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2455. * @param otherVector defines the other vector
  2456. * @param result defines the target vector
  2457. * @returns the unmodified current Vector2
  2458. */
  2459. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2460. result.x = this.x * otherVector.x;
  2461. result.y = this.y * otherVector.y;
  2462. return this;
  2463. };
  2464. /**
  2465. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2466. * @param x defines the first coordinate
  2467. * @param y defines the second coordinate
  2468. * @returns a new Vector2
  2469. */
  2470. Vector2.prototype.multiplyByFloats = function (x, y) {
  2471. return new Vector2(this.x * x, this.y * y);
  2472. };
  2473. /**
  2474. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2475. * @param otherVector defines the other vector
  2476. * @returns a new Vector2
  2477. */
  2478. Vector2.prototype.divide = function (otherVector) {
  2479. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2480. };
  2481. /**
  2482. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2483. * @param otherVector defines the other vector
  2484. * @param result defines the target vector
  2485. * @returns the unmodified current Vector2
  2486. */
  2487. Vector2.prototype.divideToRef = function (otherVector, result) {
  2488. result.x = this.x / otherVector.x;
  2489. result.y = this.y / otherVector.y;
  2490. return this;
  2491. };
  2492. /**
  2493. * Divides the current Vector3 coordinates by the given ones
  2494. * @param otherVector defines the other vector
  2495. * @returns the current updated Vector2
  2496. */
  2497. Vector2.prototype.divideInPlace = function (otherVector) {
  2498. return this.divideToRef(otherVector, this);
  2499. };
  2500. /**
  2501. * Gets a new Vector2 with current Vector2 negated coordinates
  2502. * @returns a new Vector2
  2503. */
  2504. Vector2.prototype.negate = function () {
  2505. return new Vector2(-this.x, -this.y);
  2506. };
  2507. /**
  2508. * Multiply the Vector2 coordinates by scale
  2509. * @param scale defines the scaling factor
  2510. * @returns the current updated Vector2
  2511. */
  2512. Vector2.prototype.scaleInPlace = function (scale) {
  2513. this.x *= scale;
  2514. this.y *= scale;
  2515. return this;
  2516. };
  2517. /**
  2518. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2519. * @param scale defines the scaling factor
  2520. * @returns a new Vector2
  2521. */
  2522. Vector2.prototype.scale = function (scale) {
  2523. var result = new Vector2(0, 0);
  2524. this.scaleToRef(scale, result);
  2525. return result;
  2526. };
  2527. /**
  2528. * Scale the current Vector2 values by a factor to a given Vector2
  2529. * @param scale defines the scale factor
  2530. * @param result defines the Vector2 object where to store the result
  2531. * @returns the unmodified current Vector2
  2532. */
  2533. Vector2.prototype.scaleToRef = function (scale, result) {
  2534. result.x = this.x * scale;
  2535. result.y = this.y * scale;
  2536. return this;
  2537. };
  2538. /**
  2539. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2540. * @param scale defines the scale factor
  2541. * @param result defines the Vector2 object where to store the result
  2542. * @returns the unmodified current Vector2
  2543. */
  2544. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2545. result.x += this.x * scale;
  2546. result.y += this.y * scale;
  2547. return this;
  2548. };
  2549. /**
  2550. * Gets a boolean if two vectors are equals
  2551. * @param otherVector defines the other vector
  2552. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2553. */
  2554. Vector2.prototype.equals = function (otherVector) {
  2555. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2556. };
  2557. /**
  2558. * Gets a boolean if two vectors are equals (using an epsilon value)
  2559. * @param otherVector defines the other vector
  2560. * @param epsilon defines the minimal distance to consider equality
  2561. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2562. */
  2563. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2564. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2565. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2566. };
  2567. // Properties
  2568. /**
  2569. * Gets the length of the vector
  2570. * @returns the vector length (float)
  2571. */
  2572. Vector2.prototype.length = function () {
  2573. return Math.sqrt(this.x * this.x + this.y * this.y);
  2574. };
  2575. /**
  2576. * Gets the vector squared length
  2577. * @returns the vector squared length (float)
  2578. */
  2579. Vector2.prototype.lengthSquared = function () {
  2580. return (this.x * this.x + this.y * this.y);
  2581. };
  2582. // Methods
  2583. /**
  2584. * Normalize the vector
  2585. * @returns the current updated Vector2
  2586. */
  2587. Vector2.prototype.normalize = function () {
  2588. var len = this.length();
  2589. if (len === 0)
  2590. return this;
  2591. var num = 1.0 / len;
  2592. this.x *= num;
  2593. this.y *= num;
  2594. return this;
  2595. };
  2596. /**
  2597. * Gets a new Vector2 copied from the Vector2
  2598. * @returns a new Vector2
  2599. */
  2600. Vector2.prototype.clone = function () {
  2601. return new Vector2(this.x, this.y);
  2602. };
  2603. // Statics
  2604. /**
  2605. * Gets a new Vector2(0, 0)
  2606. * @returns a new Vector2
  2607. */
  2608. Vector2.Zero = function () {
  2609. return new Vector2(0, 0);
  2610. };
  2611. /**
  2612. * Gets a new Vector2(1, 1)
  2613. * @returns a new Vector2
  2614. */
  2615. Vector2.One = function () {
  2616. return new Vector2(1, 1);
  2617. };
  2618. /**
  2619. * Gets a new Vector2 set from the given index element of the given array
  2620. * @param array defines the data source
  2621. * @param offset defines the offset in the data source
  2622. * @returns a new Vector2
  2623. */
  2624. Vector2.FromArray = function (array, offset) {
  2625. if (offset === void 0) { offset = 0; }
  2626. return new Vector2(array[offset], array[offset + 1]);
  2627. };
  2628. /**
  2629. * Sets "result" from the given index element of the given array
  2630. * @param array defines the data source
  2631. * @param offset defines the offset in the data source
  2632. * @param result defines the target vector
  2633. */
  2634. Vector2.FromArrayToRef = function (array, offset, result) {
  2635. result.x = array[offset];
  2636. result.y = array[offset + 1];
  2637. };
  2638. /**
  2639. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2640. * @param value1 defines 1st point of control
  2641. * @param value2 defines 2nd point of control
  2642. * @param value3 defines 3rd point of control
  2643. * @param value4 defines 4th point of control
  2644. * @param amount defines the interpolation factor
  2645. * @returns a new Vector2
  2646. */
  2647. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2648. var squared = amount * amount;
  2649. var cubed = amount * squared;
  2650. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2651. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2652. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2653. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2654. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2655. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2656. return new Vector2(x, y);
  2657. };
  2658. /**
  2659. * 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".
  2660. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2661. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2662. * @param value defines the value to clamp
  2663. * @param min defines the lower limit
  2664. * @param max defines the upper limit
  2665. * @returns a new Vector2
  2666. */
  2667. Vector2.Clamp = function (value, min, max) {
  2668. var x = value.x;
  2669. x = (x > max.x) ? max.x : x;
  2670. x = (x < min.x) ? min.x : x;
  2671. var y = value.y;
  2672. y = (y > max.y) ? max.y : y;
  2673. y = (y < min.y) ? min.y : y;
  2674. return new Vector2(x, y);
  2675. };
  2676. /**
  2677. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2678. * @param value1 defines the 1st control point
  2679. * @param tangent1 defines the outgoing tangent
  2680. * @param value2 defines the 2nd control point
  2681. * @param tangent2 defines the incoming tangent
  2682. * @param amount defines the interpolation factor
  2683. * @returns a new Vector2
  2684. */
  2685. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2686. var squared = amount * amount;
  2687. var cubed = amount * squared;
  2688. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2689. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2690. var part3 = (cubed - (2.0 * squared)) + amount;
  2691. var part4 = cubed - squared;
  2692. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2693. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2694. return new Vector2(x, y);
  2695. };
  2696. /**
  2697. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2698. * @param start defines the start vector
  2699. * @param end defines the end vector
  2700. * @param amount defines the interpolation factor
  2701. * @returns a new Vector2
  2702. */
  2703. Vector2.Lerp = function (start, end, amount) {
  2704. var x = start.x + ((end.x - start.x) * amount);
  2705. var y = start.y + ((end.y - start.y) * amount);
  2706. return new Vector2(x, y);
  2707. };
  2708. /**
  2709. * Gets the dot product of the vector "left" and the vector "right"
  2710. * @param left defines first vector
  2711. * @param right defines second vector
  2712. * @returns the dot product (float)
  2713. */
  2714. Vector2.Dot = function (left, right) {
  2715. return left.x * right.x + left.y * right.y;
  2716. };
  2717. /**
  2718. * Returns a new Vector2 equal to the normalized given vector
  2719. * @param vector defines the vector to normalize
  2720. * @returns a new Vector2
  2721. */
  2722. Vector2.Normalize = function (vector) {
  2723. var newVector = vector.clone();
  2724. newVector.normalize();
  2725. return newVector;
  2726. };
  2727. /**
  2728. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2729. * @param left defines 1st vector
  2730. * @param right defines 2nd vector
  2731. * @returns a new Vector2
  2732. */
  2733. Vector2.Minimize = function (left, right) {
  2734. var x = (left.x < right.x) ? left.x : right.x;
  2735. var y = (left.y < right.y) ? left.y : right.y;
  2736. return new Vector2(x, y);
  2737. };
  2738. /**
  2739. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2740. * @param left defines 1st vector
  2741. * @param right defines 2nd vector
  2742. * @returns a new Vector2
  2743. */
  2744. Vector2.Maximize = function (left, right) {
  2745. var x = (left.x > right.x) ? left.x : right.x;
  2746. var y = (left.y > right.y) ? left.y : right.y;
  2747. return new Vector2(x, y);
  2748. };
  2749. /**
  2750. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2751. * @param vector defines the vector to transform
  2752. * @param transformation defines the matrix to apply
  2753. * @returns a new Vector2
  2754. */
  2755. Vector2.Transform = function (vector, transformation) {
  2756. var r = Vector2.Zero();
  2757. Vector2.TransformToRef(vector, transformation, r);
  2758. return r;
  2759. };
  2760. /**
  2761. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2762. * @param vector defines the vector to transform
  2763. * @param transformation defines the matrix to apply
  2764. * @param result defines the target vector
  2765. */
  2766. Vector2.TransformToRef = function (vector, transformation, result) {
  2767. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2768. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2769. result.x = x;
  2770. result.y = y;
  2771. };
  2772. /**
  2773. * Determines if a given vector is included in a triangle
  2774. * @param p defines the vector to test
  2775. * @param p0 defines 1st triangle point
  2776. * @param p1 defines 2nd triangle point
  2777. * @param p2 defines 3rd triangle point
  2778. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2779. */
  2780. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2781. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2782. var sign = a < 0 ? -1 : 1;
  2783. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2784. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2785. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2786. };
  2787. /**
  2788. * Gets the distance between the vectors "value1" and "value2"
  2789. * @param value1 defines first vector
  2790. * @param value2 defines second vector
  2791. * @returns the distance between vectors
  2792. */
  2793. Vector2.Distance = function (value1, value2) {
  2794. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2795. };
  2796. /**
  2797. * Returns the squared distance between the vectors "value1" and "value2"
  2798. * @param value1 defines first vector
  2799. * @param value2 defines second vector
  2800. * @returns the squared distance between vectors
  2801. */
  2802. Vector2.DistanceSquared = function (value1, value2) {
  2803. var x = value1.x - value2.x;
  2804. var y = value1.y - value2.y;
  2805. return (x * x) + (y * y);
  2806. };
  2807. /**
  2808. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2809. * @param value1 defines first vector
  2810. * @param value2 defines second vector
  2811. * @returns a new Vector2
  2812. */
  2813. Vector2.Center = function (value1, value2) {
  2814. var center = value1.add(value2);
  2815. center.scaleInPlace(0.5);
  2816. return center;
  2817. };
  2818. /**
  2819. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2820. * @param p defines the middle point
  2821. * @param segA defines one point of the segment
  2822. * @param segB defines the other point of the segment
  2823. * @returns the shortest distance
  2824. */
  2825. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2826. var l2 = Vector2.DistanceSquared(segA, segB);
  2827. if (l2 === 0.0) {
  2828. return Vector2.Distance(p, segA);
  2829. }
  2830. var v = segB.subtract(segA);
  2831. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2832. var proj = segA.add(v.multiplyByFloats(t, t));
  2833. return Vector2.Distance(p, proj);
  2834. };
  2835. return Vector2;
  2836. }());
  2837. BABYLON.Vector2 = Vector2;
  2838. /**
  2839. * Classed used to store (x,y,z) vector representation
  2840. * A Vector3 is the main object used in 3D geometry
  2841. * It can represent etiher the coordinates of a point the space, either a direction
  2842. * Reminder: Babylon.js uses a left handed forward facing system
  2843. */
  2844. var Vector3 = /** @class */ (function () {
  2845. /**
  2846. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2847. * @param x defines the first coordinates (on X axis)
  2848. * @param y defines the second coordinates (on Y axis)
  2849. * @param z defines the third coordinates (on Z axis)
  2850. */
  2851. function Vector3(
  2852. /**
  2853. * Defines the first coordinates (on X axis)
  2854. */
  2855. x,
  2856. /**
  2857. * Defines the second coordinates (on Y axis)
  2858. */
  2859. y,
  2860. /**
  2861. * Defines the third coordinates (on Z axis)
  2862. */
  2863. z) {
  2864. this.x = x;
  2865. this.y = y;
  2866. this.z = z;
  2867. }
  2868. /**
  2869. * Creates a string representation of the Vector3
  2870. * @returns a string with the Vector3 coordinates.
  2871. */
  2872. Vector3.prototype.toString = function () {
  2873. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2874. };
  2875. /**
  2876. * Gets the class name
  2877. * @returns the string "Vector3"
  2878. */
  2879. Vector3.prototype.getClassName = function () {
  2880. return "Vector3";
  2881. };
  2882. /**
  2883. * Creates the Vector3 hash code
  2884. * @returns a number which tends to be unique between Vector3 instances
  2885. */
  2886. Vector3.prototype.getHashCode = function () {
  2887. var hash = this.x || 0;
  2888. hash = (hash * 397) ^ (this.y || 0);
  2889. hash = (hash * 397) ^ (this.z || 0);
  2890. return hash;
  2891. };
  2892. // Operators
  2893. /**
  2894. * Creates an array containing three elements : the coordinates of the Vector3
  2895. * @returns a new array of numbers
  2896. */
  2897. Vector3.prototype.asArray = function () {
  2898. var result = [];
  2899. this.toArray(result, 0);
  2900. return result;
  2901. };
  2902. /**
  2903. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2904. * @param array defines the destination array
  2905. * @param index defines the offset in the destination array
  2906. * @returns the current Vector3
  2907. */
  2908. Vector3.prototype.toArray = function (array, index) {
  2909. if (index === void 0) { index = 0; }
  2910. array[index] = this.x;
  2911. array[index + 1] = this.y;
  2912. array[index + 2] = this.z;
  2913. return this;
  2914. };
  2915. /**
  2916. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2917. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2918. */
  2919. Vector3.prototype.toQuaternion = function () {
  2920. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2921. };
  2922. /**
  2923. * Adds the given vector to the current Vector3
  2924. * @param otherVector defines the second operand
  2925. * @returns the current updated Vector3
  2926. */
  2927. Vector3.prototype.addInPlace = function (otherVector) {
  2928. this.x += otherVector.x;
  2929. this.y += otherVector.y;
  2930. this.z += otherVector.z;
  2931. return this;
  2932. };
  2933. /**
  2934. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2935. * @param otherVector defines the second operand
  2936. * @returns the resulting Vector3
  2937. */
  2938. Vector3.prototype.add = function (otherVector) {
  2939. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2940. };
  2941. /**
  2942. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2943. * @param otherVector defines the second operand
  2944. * @param result defines the Vector3 object where to store the result
  2945. * @returns the current Vector3
  2946. */
  2947. Vector3.prototype.addToRef = function (otherVector, result) {
  2948. result.x = this.x + otherVector.x;
  2949. result.y = this.y + otherVector.y;
  2950. result.z = this.z + otherVector.z;
  2951. return this;
  2952. };
  2953. /**
  2954. * Subtract the given vector from the current Vector3
  2955. * @param otherVector defines the second operand
  2956. * @returns the current updated Vector3
  2957. */
  2958. Vector3.prototype.subtractInPlace = function (otherVector) {
  2959. this.x -= otherVector.x;
  2960. this.y -= otherVector.y;
  2961. this.z -= otherVector.z;
  2962. return this;
  2963. };
  2964. /**
  2965. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2966. * @param otherVector defines the second operand
  2967. * @returns the resulting Vector3
  2968. */
  2969. Vector3.prototype.subtract = function (otherVector) {
  2970. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2971. };
  2972. /**
  2973. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2974. * @param otherVector defines the second operand
  2975. * @param result defines the Vector3 object where to store the result
  2976. * @returns the current Vector3
  2977. */
  2978. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2979. result.x = this.x - otherVector.x;
  2980. result.y = this.y - otherVector.y;
  2981. result.z = this.z - otherVector.z;
  2982. return this;
  2983. };
  2984. /**
  2985. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2986. * @param x defines the x coordinate of the operand
  2987. * @param y defines the y coordinate of the operand
  2988. * @param z defines the z coordinate of the operand
  2989. * @returns the resulting Vector3
  2990. */
  2991. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2992. return new Vector3(this.x - x, this.y - y, this.z - z);
  2993. };
  2994. /**
  2995. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2996. * @param x defines the x coordinate of the operand
  2997. * @param y defines the y coordinate of the operand
  2998. * @param z defines the z coordinate of the operand
  2999. * @param result defines the Vector3 object where to store the result
  3000. * @returns the current Vector3
  3001. */
  3002. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  3003. result.x = this.x - x;
  3004. result.y = this.y - y;
  3005. result.z = this.z - z;
  3006. return this;
  3007. };
  3008. /**
  3009. * Gets a new Vector3 set with the current Vector3 negated coordinates
  3010. * @returns a new Vector3
  3011. */
  3012. Vector3.prototype.negate = function () {
  3013. return new Vector3(-this.x, -this.y, -this.z);
  3014. };
  3015. /**
  3016. * Multiplies the Vector3 coordinates by the float "scale"
  3017. * @param scale defines the multiplier factor
  3018. * @returns the current updated Vector3
  3019. */
  3020. Vector3.prototype.scaleInPlace = function (scale) {
  3021. this.x *= scale;
  3022. this.y *= scale;
  3023. this.z *= scale;
  3024. return this;
  3025. };
  3026. /**
  3027. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3028. * @param scale defines the multiplier factor
  3029. * @returns a new Vector3
  3030. */
  3031. Vector3.prototype.scale = function (scale) {
  3032. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3033. };
  3034. /**
  3035. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3036. * @param scale defines the multiplier factor
  3037. * @param result defines the Vector3 object where to store the result
  3038. * @returns the current Vector3
  3039. */
  3040. Vector3.prototype.scaleToRef = function (scale, result) {
  3041. result.x = this.x * scale;
  3042. result.y = this.y * scale;
  3043. result.z = this.z * scale;
  3044. return this;
  3045. };
  3046. /**
  3047. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3048. * @param scale defines the scale factor
  3049. * @param result defines the Vector3 object where to store the result
  3050. * @returns the unmodified current Vector3
  3051. */
  3052. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3053. result.x += this.x * scale;
  3054. result.y += this.y * scale;
  3055. result.z += this.z * scale;
  3056. return this;
  3057. };
  3058. /**
  3059. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3060. * @param otherVector defines the second operand
  3061. * @returns true if both vectors are equals
  3062. */
  3063. Vector3.prototype.equals = function (otherVector) {
  3064. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3065. };
  3066. /**
  3067. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3068. * @param otherVector defines the second operand
  3069. * @param epsilon defines the minimal distance to define values as equals
  3070. * @returns true if both vectors are distant less than epsilon
  3071. */
  3072. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3073. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3074. 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);
  3075. };
  3076. /**
  3077. * Returns true if the current Vector3 coordinates equals the given floats
  3078. * @param x defines the x coordinate of the operand
  3079. * @param y defines the y coordinate of the operand
  3080. * @param z defines the z coordinate of the operand
  3081. * @returns true if both vectors are equals
  3082. */
  3083. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3084. return this.x === x && this.y === y && this.z === z;
  3085. };
  3086. /**
  3087. * Multiplies the current Vector3 coordinates by the given ones
  3088. * @param otherVector defines the second operand
  3089. * @returns the current updated Vector3
  3090. */
  3091. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3092. this.x *= otherVector.x;
  3093. this.y *= otherVector.y;
  3094. this.z *= otherVector.z;
  3095. return this;
  3096. };
  3097. /**
  3098. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3099. * @param otherVector defines the second operand
  3100. * @returns the new Vector3
  3101. */
  3102. Vector3.prototype.multiply = function (otherVector) {
  3103. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3104. };
  3105. /**
  3106. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3107. * @param otherVector defines the second operand
  3108. * @param result defines the Vector3 object where to store the result
  3109. * @returns the current Vector3
  3110. */
  3111. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3112. result.x = this.x * otherVector.x;
  3113. result.y = this.y * otherVector.y;
  3114. result.z = this.z * otherVector.z;
  3115. return this;
  3116. };
  3117. /**
  3118. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3119. * @param x defines the x coordinate of the operand
  3120. * @param y defines the y coordinate of the operand
  3121. * @param z defines the z coordinate of the operand
  3122. * @returns the new Vector3
  3123. */
  3124. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3125. return new Vector3(this.x * x, this.y * y, this.z * z);
  3126. };
  3127. /**
  3128. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3129. * @param otherVector defines the second operand
  3130. * @returns the new Vector3
  3131. */
  3132. Vector3.prototype.divide = function (otherVector) {
  3133. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3134. };
  3135. /**
  3136. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3137. * @param otherVector defines the second operand
  3138. * @param result defines the Vector3 object where to store the result
  3139. * @returns the current Vector3
  3140. */
  3141. Vector3.prototype.divideToRef = function (otherVector, result) {
  3142. result.x = this.x / otherVector.x;
  3143. result.y = this.y / otherVector.y;
  3144. result.z = this.z / otherVector.z;
  3145. return this;
  3146. };
  3147. /**
  3148. * Divides the current Vector3 coordinates by the given ones.
  3149. * @param otherVector defines the second operand
  3150. * @returns the current updated Vector3
  3151. */
  3152. Vector3.prototype.divideInPlace = function (otherVector) {
  3153. return this.divideToRef(otherVector, this);
  3154. };
  3155. /**
  3156. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3157. * @param other defines the second operand
  3158. * @returns the current updated Vector3
  3159. */
  3160. Vector3.prototype.minimizeInPlace = function (other) {
  3161. if (other.x < this.x)
  3162. this.x = other.x;
  3163. if (other.y < this.y)
  3164. this.y = other.y;
  3165. if (other.z < this.z)
  3166. this.z = other.z;
  3167. return this;
  3168. };
  3169. /**
  3170. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3171. * @param other defines the second operand
  3172. * @returns the current updated Vector3
  3173. */
  3174. Vector3.prototype.maximizeInPlace = function (other) {
  3175. if (other.x > this.x)
  3176. this.x = other.x;
  3177. if (other.y > this.y)
  3178. this.y = other.y;
  3179. if (other.z > this.z)
  3180. this.z = other.z;
  3181. return this;
  3182. };
  3183. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3184. /**
  3185. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3186. */
  3187. get: function () {
  3188. var absX = Math.abs(this.x);
  3189. var absY = Math.abs(this.y);
  3190. if (absX !== absY) {
  3191. return true;
  3192. }
  3193. var absZ = Math.abs(this.z);
  3194. if (absX !== absZ) {
  3195. return true;
  3196. }
  3197. if (absY !== absZ) {
  3198. return true;
  3199. }
  3200. return false;
  3201. },
  3202. enumerable: true,
  3203. configurable: true
  3204. });
  3205. // Properties
  3206. /**
  3207. * Gets the length of the Vector3
  3208. * @returns the length of the Vecto3
  3209. */
  3210. Vector3.prototype.length = function () {
  3211. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3212. };
  3213. /**
  3214. * Gets the squared length of the Vector3
  3215. * @returns squared length of the Vector3
  3216. */
  3217. Vector3.prototype.lengthSquared = function () {
  3218. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3219. };
  3220. /**
  3221. * Normalize the current Vector3.
  3222. * Please note that this is an in place operation.
  3223. * @returns the current updated Vector3
  3224. */
  3225. Vector3.prototype.normalize = function () {
  3226. var len = this.length();
  3227. if (len === 0 || len === 1.0)
  3228. return this;
  3229. var num = 1.0 / len;
  3230. this.x *= num;
  3231. this.y *= num;
  3232. this.z *= num;
  3233. return this;
  3234. };
  3235. /**
  3236. * Normalize the current Vector3 to a new vector
  3237. * @returns the new Vector3
  3238. */
  3239. Vector3.prototype.normalizeToNew = function () {
  3240. var normalized = new Vector3(0, 0, 0);
  3241. this.normalizeToRef(normalized);
  3242. return normalized;
  3243. };
  3244. /**
  3245. * Normalize the current Vector3 to the reference
  3246. * @param reference define the Vector3 to update
  3247. * @returns the updated Vector3
  3248. */
  3249. Vector3.prototype.normalizeToRef = function (reference) {
  3250. var len = this.length();
  3251. if (len === 0 || len === 1.0) {
  3252. reference.set(this.x, this.y, this.z);
  3253. return reference;
  3254. }
  3255. var scale = 1.0 / len;
  3256. this.scaleToRef(scale, reference);
  3257. return reference;
  3258. };
  3259. /**
  3260. * Creates a new Vector3 copied from the current Vector3
  3261. * @returns the new Vector3
  3262. */
  3263. Vector3.prototype.clone = function () {
  3264. return new Vector3(this.x, this.y, this.z);
  3265. };
  3266. /**
  3267. * Copies the given vector coordinates to the current Vector3 ones
  3268. * @param source defines the source Vector3
  3269. * @returns the current updated Vector3
  3270. */
  3271. Vector3.prototype.copyFrom = function (source) {
  3272. this.x = source.x;
  3273. this.y = source.y;
  3274. this.z = source.z;
  3275. return this;
  3276. };
  3277. /**
  3278. * Copies the given floats to the current Vector3 coordinates
  3279. * @param x defines the x coordinate of the operand
  3280. * @param y defines the y coordinate of the operand
  3281. * @param z defines the z coordinate of the operand
  3282. * @returns the current updated Vector3
  3283. */
  3284. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3285. this.x = x;
  3286. this.y = y;
  3287. this.z = z;
  3288. return this;
  3289. };
  3290. /**
  3291. * Copies the given floats to the current Vector3 coordinates
  3292. * @param x defines the x coordinate of the operand
  3293. * @param y defines the y coordinate of the operand
  3294. * @param z defines the z coordinate of the operand
  3295. * @returns the current updated Vector3
  3296. */
  3297. Vector3.prototype.set = function (x, y, z) {
  3298. return this.copyFromFloats(x, y, z);
  3299. };
  3300. // Statics
  3301. /**
  3302. * Get the clip factor between two vectors
  3303. * @param vector0 defines the first operand
  3304. * @param vector1 defines the second operand
  3305. * @param axis defines the axis to use
  3306. * @param size defines the size along the axis
  3307. * @returns the clip factor
  3308. */
  3309. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3310. var d0 = Vector3.Dot(vector0, axis) - size;
  3311. var d1 = Vector3.Dot(vector1, axis) - size;
  3312. var s = d0 / (d0 - d1);
  3313. return s;
  3314. };
  3315. /**
  3316. * Get angle between two vectors
  3317. * @param vector0 angle between vector0 and vector1
  3318. * @param vector1 angle between vector0 and vector1
  3319. * @param normal direction of the normal
  3320. * @return the angle between vector0 and vector1
  3321. */
  3322. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3323. var v0 = vector0.clone().normalize();
  3324. var v1 = vector1.clone().normalize();
  3325. var dot = Vector3.Dot(v0, v1);
  3326. var n = Vector3.Cross(v0, v1);
  3327. if (Vector3.Dot(n, normal) > 0) {
  3328. return Math.acos(dot);
  3329. }
  3330. return -Math.acos(dot);
  3331. };
  3332. /**
  3333. * Returns a new Vector3 set from the index "offset" of the given array
  3334. * @param array defines the source array
  3335. * @param offset defines the offset in the source array
  3336. * @returns the new Vector3
  3337. */
  3338. Vector3.FromArray = function (array, offset) {
  3339. if (!offset) {
  3340. offset = 0;
  3341. }
  3342. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3343. };
  3344. /**
  3345. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3346. * This function is deprecated. Use FromArray instead
  3347. * @param array defines the source array
  3348. * @param offset defines the offset in the source array
  3349. * @returns the new Vector3
  3350. */
  3351. Vector3.FromFloatArray = function (array, offset) {
  3352. return Vector3.FromArray(array, offset);
  3353. };
  3354. /**
  3355. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3356. * @param array defines the source array
  3357. * @param offset defines the offset in the source array
  3358. * @param result defines the Vector3 where to store the result
  3359. */
  3360. Vector3.FromArrayToRef = function (array, offset, result) {
  3361. result.x = array[offset];
  3362. result.y = array[offset + 1];
  3363. result.z = array[offset + 2];
  3364. };
  3365. /**
  3366. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3367. * This function is deprecated. Use FromArrayToRef instead.
  3368. * @param array defines the source array
  3369. * @param offset defines the offset in the source array
  3370. * @param result defines the Vector3 where to store the result
  3371. */
  3372. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3373. return Vector3.FromArrayToRef(array, offset, result);
  3374. };
  3375. /**
  3376. * Sets the given vector "result" with the given floats.
  3377. * @param x defines the x coordinate of the source
  3378. * @param y defines the y coordinate of the source
  3379. * @param z defines the z coordinate of the source
  3380. * @param result defines the Vector3 where to store the result
  3381. */
  3382. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3383. result.x = x;
  3384. result.y = y;
  3385. result.z = z;
  3386. };
  3387. /**
  3388. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3389. * @returns a new empty Vector3
  3390. */
  3391. Vector3.Zero = function () {
  3392. return new Vector3(0.0, 0.0, 0.0);
  3393. };
  3394. /**
  3395. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3396. * @returns a new unit Vector3
  3397. */
  3398. Vector3.One = function () {
  3399. return new Vector3(1.0, 1.0, 1.0);
  3400. };
  3401. /**
  3402. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3403. * @returns a new up Vector3
  3404. */
  3405. Vector3.Up = function () {
  3406. return new Vector3(0.0, 1.0, 0.0);
  3407. };
  3408. /**
  3409. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3410. * @returns a new forward Vector3
  3411. */
  3412. Vector3.Forward = function () {
  3413. return new Vector3(0.0, 0.0, 1.0);
  3414. };
  3415. /**
  3416. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3417. * @returns a new right Vector3
  3418. */
  3419. Vector3.Right = function () {
  3420. return new Vector3(1.0, 0.0, 0.0);
  3421. };
  3422. /**
  3423. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3424. * @returns a new left Vector3
  3425. */
  3426. Vector3.Left = function () {
  3427. return new Vector3(-1.0, 0.0, 0.0);
  3428. };
  3429. /**
  3430. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3431. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3432. * @param vector defines the Vector3 to transform
  3433. * @param transformation defines the transformation matrix
  3434. * @returns the transformed Vector3
  3435. */
  3436. Vector3.TransformCoordinates = function (vector, transformation) {
  3437. var result = Vector3.Zero();
  3438. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3439. return result;
  3440. };
  3441. /**
  3442. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3443. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3444. * @param vector defines the Vector3 to transform
  3445. * @param transformation defines the transformation matrix
  3446. * @param result defines the Vector3 where to store the result
  3447. */
  3448. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3449. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3450. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3451. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3452. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3453. result.x = x / w;
  3454. result.y = y / w;
  3455. result.z = z / w;
  3456. };
  3457. /**
  3458. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3459. * This method computes tranformed coordinates only, not transformed direction vectors
  3460. * @param x define the x coordinate of the source vector
  3461. * @param y define the y coordinate of the source vector
  3462. * @param z define the z coordinate of the source vector
  3463. * @param transformation defines the transformation matrix
  3464. * @param result defines the Vector3 where to store the result
  3465. */
  3466. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3467. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3468. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3469. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3470. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3471. result.x = rx / rw;
  3472. result.y = ry / rw;
  3473. result.z = rz / rw;
  3474. };
  3475. /**
  3476. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3477. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3478. * @param vector defines the Vector3 to transform
  3479. * @param transformation defines the transformation matrix
  3480. * @returns the new Vector3
  3481. */
  3482. Vector3.TransformNormal = function (vector, transformation) {
  3483. var result = Vector3.Zero();
  3484. Vector3.TransformNormalToRef(vector, transformation, result);
  3485. return result;
  3486. };
  3487. /**
  3488. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3489. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3490. * @param vector defines the Vector3 to transform
  3491. * @param transformation defines the transformation matrix
  3492. * @param result defines the Vector3 where to store the result
  3493. */
  3494. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3495. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3496. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3497. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3498. result.x = x;
  3499. result.y = y;
  3500. result.z = z;
  3501. };
  3502. /**
  3503. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3504. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3505. * @param x define the x coordinate of the source vector
  3506. * @param y define the y coordinate of the source vector
  3507. * @param z define the z coordinate of the source vector
  3508. * @param transformation defines the transformation matrix
  3509. * @param result defines the Vector3 where to store the result
  3510. */
  3511. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3512. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3513. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3514. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3515. };
  3516. /**
  3517. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3518. * @param value1 defines the first control point
  3519. * @param value2 defines the second control point
  3520. * @param value3 defines the third control point
  3521. * @param value4 defines the fourth control point
  3522. * @param amount defines the amount on the spline to use
  3523. * @returns the new Vector3
  3524. */
  3525. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3526. var squared = amount * amount;
  3527. var cubed = amount * squared;
  3528. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3529. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3530. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3531. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3532. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3533. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3534. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3535. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3536. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3537. return new Vector3(x, y, z);
  3538. };
  3539. /**
  3540. * 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"
  3541. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3542. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3543. * @param value defines the current value
  3544. * @param min defines the lower range value
  3545. * @param max defines the upper range value
  3546. * @returns the new Vector3
  3547. */
  3548. Vector3.Clamp = function (value, min, max) {
  3549. var x = value.x;
  3550. x = (x > max.x) ? max.x : x;
  3551. x = (x < min.x) ? min.x : x;
  3552. var y = value.y;
  3553. y = (y > max.y) ? max.y : y;
  3554. y = (y < min.y) ? min.y : y;
  3555. var z = value.z;
  3556. z = (z > max.z) ? max.z : z;
  3557. z = (z < min.z) ? min.z : z;
  3558. return new Vector3(x, y, z);
  3559. };
  3560. /**
  3561. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3562. * @param value1 defines the first control point
  3563. * @param tangent1 defines the first tangent vector
  3564. * @param value2 defines the second control point
  3565. * @param tangent2 defines the second tangent vector
  3566. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3567. * @returns the new Vector3
  3568. */
  3569. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3570. var squared = amount * amount;
  3571. var cubed = amount * squared;
  3572. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3573. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3574. var part3 = (cubed - (2.0 * squared)) + amount;
  3575. var part4 = cubed - squared;
  3576. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3577. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3578. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3579. return new Vector3(x, y, z);
  3580. };
  3581. /**
  3582. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3583. * @param start defines the start value
  3584. * @param end defines the end value
  3585. * @param amount max defines amount between both (between 0 and 1)
  3586. * @returns the new Vector3
  3587. */
  3588. Vector3.Lerp = function (start, end, amount) {
  3589. var result = new Vector3(0, 0, 0);
  3590. Vector3.LerpToRef(start, end, amount, result);
  3591. return result;
  3592. };
  3593. /**
  3594. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3595. * @param start defines the start value
  3596. * @param end defines the end value
  3597. * @param amount max defines amount between both (between 0 and 1)
  3598. * @param result defines the Vector3 where to store the result
  3599. */
  3600. Vector3.LerpToRef = function (start, end, amount, result) {
  3601. result.x = start.x + ((end.x - start.x) * amount);
  3602. result.y = start.y + ((end.y - start.y) * amount);
  3603. result.z = start.z + ((end.z - start.z) * amount);
  3604. };
  3605. /**
  3606. * Returns the dot product (float) between the vectors "left" and "right"
  3607. * @param left defines the left operand
  3608. * @param right defines the right operand
  3609. * @returns the dot product
  3610. */
  3611. Vector3.Dot = function (left, right) {
  3612. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3613. };
  3614. /**
  3615. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3616. * The cross product is then orthogonal to both "left" and "right"
  3617. * @param left defines the left operand
  3618. * @param right defines the right operand
  3619. * @returns the cross product
  3620. */
  3621. Vector3.Cross = function (left, right) {
  3622. var result = Vector3.Zero();
  3623. Vector3.CrossToRef(left, right, result);
  3624. return result;
  3625. };
  3626. /**
  3627. * Sets the given vector "result" with the cross product of "left" and "right"
  3628. * The cross product is then orthogonal to both "left" and "right"
  3629. * @param left defines the left operand
  3630. * @param right defines the right operand
  3631. * @param result defines the Vector3 where to store the result
  3632. */
  3633. Vector3.CrossToRef = function (left, right, result) {
  3634. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3635. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3636. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3637. result.copyFrom(MathTmp.Vector3[0]);
  3638. };
  3639. /**
  3640. * Returns a new Vector3 as the normalization of the given vector
  3641. * @param vector defines the Vector3 to normalize
  3642. * @returns the new Vector3
  3643. */
  3644. Vector3.Normalize = function (vector) {
  3645. var result = Vector3.Zero();
  3646. Vector3.NormalizeToRef(vector, result);
  3647. return result;
  3648. };
  3649. /**
  3650. * Sets the given vector "result" with the normalization of the given first vector
  3651. * @param vector defines the Vector3 to normalize
  3652. * @param result defines the Vector3 where to store the result
  3653. */
  3654. Vector3.NormalizeToRef = function (vector, result) {
  3655. result.copyFrom(vector);
  3656. result.normalize();
  3657. };
  3658. /**
  3659. * Project a Vector3 onto screen space
  3660. * @param vector defines the Vector3 to project
  3661. * @param world defines the world matrix to use
  3662. * @param transform defines the transform (view x projection) matrix to use
  3663. * @param viewport defines the screen viewport to use
  3664. * @returns the new Vector3
  3665. */
  3666. Vector3.Project = function (vector, world, transform, viewport) {
  3667. var cw = viewport.width;
  3668. var ch = viewport.height;
  3669. var cx = viewport.x;
  3670. var cy = viewport.y;
  3671. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3672. 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);
  3673. var matrix = MathTmp.Matrix[0];
  3674. world.multiplyToRef(transform, matrix);
  3675. matrix.multiplyToRef(viewportMatrix, matrix);
  3676. return Vector3.TransformCoordinates(vector, matrix);
  3677. };
  3678. /**
  3679. * Unproject from screen space to object space
  3680. * @param source defines the screen space Vector3 to use
  3681. * @param viewportWidth defines the current width of the viewport
  3682. * @param viewportHeight defines the current height of the viewport
  3683. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3684. * @param transform defines the transform (view x projection) matrix to use
  3685. * @returns the new Vector3
  3686. */
  3687. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3688. var matrix = MathTmp.Matrix[0];
  3689. world.multiplyToRef(transform, matrix);
  3690. matrix.invert();
  3691. source.x = source.x / viewportWidth * 2 - 1;
  3692. source.y = -(source.y / viewportHeight * 2 - 1);
  3693. var vector = Vector3.TransformCoordinates(source, matrix);
  3694. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3695. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3696. vector = vector.scale(1.0 / num);
  3697. }
  3698. return vector;
  3699. };
  3700. /**
  3701. * Unproject from screen space to object space
  3702. * @param source defines the screen space Vector3 to use
  3703. * @param viewportWidth defines the current width of the viewport
  3704. * @param viewportHeight defines the current height of the viewport
  3705. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3706. * @param view defines the view matrix to use
  3707. * @param projection defines the projection matrix to use
  3708. * @returns the new Vector3
  3709. */
  3710. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3711. var result = Vector3.Zero();
  3712. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3713. return result;
  3714. };
  3715. /**
  3716. * Unproject from screen space to object space
  3717. * @param source defines the screen space Vector3 to use
  3718. * @param viewportWidth defines the current width of the viewport
  3719. * @param viewportHeight defines the current height of the viewport
  3720. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3721. * @param view defines the view matrix to use
  3722. * @param projection defines the projection matrix to use
  3723. * @param result defines the Vector3 where to store the result
  3724. */
  3725. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3726. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3727. };
  3728. /**
  3729. * Unproject from screen space to object space
  3730. * @param sourceX defines the screen space x coordinate to use
  3731. * @param sourceY defines the screen space y coordinate to use
  3732. * @param sourceZ defines the screen space z coordinate to use
  3733. * @param viewportWidth defines the current width of the viewport
  3734. * @param viewportHeight defines the current height of the viewport
  3735. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3736. * @param view defines the view matrix to use
  3737. * @param projection defines the projection matrix to use
  3738. * @param result defines the Vector3 where to store the result
  3739. */
  3740. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3741. var matrix = MathTmp.Matrix[0];
  3742. world.multiplyToRef(view, matrix);
  3743. matrix.multiplyToRef(projection, matrix);
  3744. matrix.invert();
  3745. var screenSource = MathTmp.Vector3[0];
  3746. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3747. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3748. screenSource.z = 2 * sourceZ - 1.0;
  3749. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3750. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3751. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3752. result.scaleInPlace(1.0 / num);
  3753. }
  3754. };
  3755. /**
  3756. * Gets the minimal coordinate values between two Vector3
  3757. * @param left defines the first operand
  3758. * @param right defines the second operand
  3759. * @returns the new Vector3
  3760. */
  3761. Vector3.Minimize = function (left, right) {
  3762. var min = left.clone();
  3763. min.minimizeInPlace(right);
  3764. return min;
  3765. };
  3766. /**
  3767. * Gets the maximal coordinate values between two Vector3
  3768. * @param left defines the first operand
  3769. * @param right defines the second operand
  3770. * @returns the new Vector3
  3771. */
  3772. Vector3.Maximize = function (left, right) {
  3773. var max = left.clone();
  3774. max.maximizeInPlace(right);
  3775. return max;
  3776. };
  3777. /**
  3778. * Returns the distance between the vectors "value1" and "value2"
  3779. * @param value1 defines the first operand
  3780. * @param value2 defines the second operand
  3781. * @returns the distance
  3782. */
  3783. Vector3.Distance = function (value1, value2) {
  3784. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3785. };
  3786. /**
  3787. * Returns the squared distance between the vectors "value1" and "value2"
  3788. * @param value1 defines the first operand
  3789. * @param value2 defines the second operand
  3790. * @returns the squared distance
  3791. */
  3792. Vector3.DistanceSquared = function (value1, value2) {
  3793. var x = value1.x - value2.x;
  3794. var y = value1.y - value2.y;
  3795. var z = value1.z - value2.z;
  3796. return (x * x) + (y * y) + (z * z);
  3797. };
  3798. /**
  3799. * Returns a new Vector3 located at the center between "value1" and "value2"
  3800. * @param value1 defines the first operand
  3801. * @param value2 defines the second operand
  3802. * @returns the new Vector3
  3803. */
  3804. Vector3.Center = function (value1, value2) {
  3805. var center = value1.add(value2);
  3806. center.scaleInPlace(0.5);
  3807. return center;
  3808. };
  3809. /**
  3810. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3811. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3812. * to something in order to rotate it from its local system to the given target system
  3813. * Note: axis1, axis2 and axis3 are normalized during this operation
  3814. * @param axis1 defines the first axis
  3815. * @param axis2 defines the second axis
  3816. * @param axis3 defines the third axis
  3817. * @returns a new Vector3
  3818. */
  3819. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3820. var rotation = Vector3.Zero();
  3821. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3822. return rotation;
  3823. };
  3824. /**
  3825. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3826. * @param axis1 defines the first axis
  3827. * @param axis2 defines the second axis
  3828. * @param axis3 defines the third axis
  3829. * @param ref defines the Vector3 where to store the result
  3830. */
  3831. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3832. var quat = MathTmp.Quaternion[0];
  3833. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3834. quat.toEulerAnglesToRef(ref);
  3835. };
  3836. return Vector3;
  3837. }());
  3838. BABYLON.Vector3 = Vector3;
  3839. //Vector4 class created for EulerAngle class conversion to Quaternion
  3840. var Vector4 = /** @class */ (function () {
  3841. /**
  3842. * Creates a Vector4 object from the given floats.
  3843. */
  3844. function Vector4(x, y, z, w) {
  3845. this.x = x;
  3846. this.y = y;
  3847. this.z = z;
  3848. this.w = w;
  3849. }
  3850. /**
  3851. * Returns the string with the Vector4 coordinates.
  3852. */
  3853. Vector4.prototype.toString = function () {
  3854. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3855. };
  3856. /**
  3857. * Returns the string "Vector4".
  3858. */
  3859. Vector4.prototype.getClassName = function () {
  3860. return "Vector4";
  3861. };
  3862. /**
  3863. * Returns the Vector4 hash code.
  3864. */
  3865. Vector4.prototype.getHashCode = function () {
  3866. var hash = this.x || 0;
  3867. hash = (hash * 397) ^ (this.y || 0);
  3868. hash = (hash * 397) ^ (this.z || 0);
  3869. hash = (hash * 397) ^ (this.w || 0);
  3870. return hash;
  3871. };
  3872. // Operators
  3873. /**
  3874. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3875. */
  3876. Vector4.prototype.asArray = function () {
  3877. var result = new Array();
  3878. this.toArray(result, 0);
  3879. return result;
  3880. };
  3881. /**
  3882. * Populates the given array from the given index with the Vector4 coordinates.
  3883. * Returns the Vector4.
  3884. */
  3885. Vector4.prototype.toArray = function (array, index) {
  3886. if (index === undefined) {
  3887. index = 0;
  3888. }
  3889. array[index] = this.x;
  3890. array[index + 1] = this.y;
  3891. array[index + 2] = this.z;
  3892. array[index + 3] = this.w;
  3893. return this;
  3894. };
  3895. /**
  3896. * Adds the given vector to the current Vector4.
  3897. * Returns the updated Vector4.
  3898. */
  3899. Vector4.prototype.addInPlace = function (otherVector) {
  3900. this.x += otherVector.x;
  3901. this.y += otherVector.y;
  3902. this.z += otherVector.z;
  3903. this.w += otherVector.w;
  3904. return this;
  3905. };
  3906. /**
  3907. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3908. */
  3909. Vector4.prototype.add = function (otherVector) {
  3910. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3911. };
  3912. /**
  3913. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3914. * Returns the current Vector4.
  3915. */
  3916. Vector4.prototype.addToRef = function (otherVector, result) {
  3917. result.x = this.x + otherVector.x;
  3918. result.y = this.y + otherVector.y;
  3919. result.z = this.z + otherVector.z;
  3920. result.w = this.w + otherVector.w;
  3921. return this;
  3922. };
  3923. /**
  3924. * Subtract in place the given vector from the current Vector4.
  3925. * Returns the updated Vector4.
  3926. */
  3927. Vector4.prototype.subtractInPlace = function (otherVector) {
  3928. this.x -= otherVector.x;
  3929. this.y -= otherVector.y;
  3930. this.z -= otherVector.z;
  3931. this.w -= otherVector.w;
  3932. return this;
  3933. };
  3934. /**
  3935. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3936. */
  3937. Vector4.prototype.subtract = function (otherVector) {
  3938. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3939. };
  3940. /**
  3941. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3942. * Returns the current Vector4.
  3943. */
  3944. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3945. result.x = this.x - otherVector.x;
  3946. result.y = this.y - otherVector.y;
  3947. result.z = this.z - otherVector.z;
  3948. result.w = this.w - otherVector.w;
  3949. return this;
  3950. };
  3951. /**
  3952. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3953. */
  3954. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3955. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3956. };
  3957. /**
  3958. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3959. * Returns the current Vector4.
  3960. */
  3961. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3962. result.x = this.x - x;
  3963. result.y = this.y - y;
  3964. result.z = this.z - z;
  3965. result.w = this.w - w;
  3966. return this;
  3967. };
  3968. /**
  3969. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3970. */
  3971. Vector4.prototype.negate = function () {
  3972. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3973. };
  3974. /**
  3975. * Multiplies the current Vector4 coordinates by scale (float).
  3976. * Returns the updated Vector4.
  3977. */
  3978. Vector4.prototype.scaleInPlace = function (scale) {
  3979. this.x *= scale;
  3980. this.y *= scale;
  3981. this.z *= scale;
  3982. this.w *= scale;
  3983. return this;
  3984. };
  3985. /**
  3986. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3987. */
  3988. Vector4.prototype.scale = function (scale) {
  3989. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3990. };
  3991. /**
  3992. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3993. * Returns the current Vector4.
  3994. */
  3995. Vector4.prototype.scaleToRef = function (scale, result) {
  3996. result.x = this.x * scale;
  3997. result.y = this.y * scale;
  3998. result.z = this.z * scale;
  3999. result.w = this.w * scale;
  4000. return this;
  4001. };
  4002. /**
  4003. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4004. * @param scale defines the scale factor
  4005. * @param result defines the Vector4 object where to store the result
  4006. * @returns the unmodified current Vector4
  4007. */
  4008. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4009. result.x += this.x * scale;
  4010. result.y += this.y * scale;
  4011. result.z += this.z * scale;
  4012. result.w += this.w * scale;
  4013. return this;
  4014. };
  4015. /**
  4016. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4017. */
  4018. Vector4.prototype.equals = function (otherVector) {
  4019. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4020. };
  4021. /**
  4022. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4023. */
  4024. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4025. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4026. return otherVector
  4027. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4028. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4029. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4030. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4031. };
  4032. /**
  4033. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4034. */
  4035. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4036. return this.x === x && this.y === y && this.z === z && this.w === w;
  4037. };
  4038. /**
  4039. * Multiplies in place the current Vector4 by the given one.
  4040. * Returns the updated Vector4.
  4041. */
  4042. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4043. this.x *= otherVector.x;
  4044. this.y *= otherVector.y;
  4045. this.z *= otherVector.z;
  4046. this.w *= otherVector.w;
  4047. return this;
  4048. };
  4049. /**
  4050. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4051. */
  4052. Vector4.prototype.multiply = function (otherVector) {
  4053. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4054. };
  4055. /**
  4056. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4057. * Returns the current Vector4.
  4058. */
  4059. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4060. result.x = this.x * otherVector.x;
  4061. result.y = this.y * otherVector.y;
  4062. result.z = this.z * otherVector.z;
  4063. result.w = this.w * otherVector.w;
  4064. return this;
  4065. };
  4066. /**
  4067. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4068. */
  4069. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4070. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4071. };
  4072. /**
  4073. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4074. */
  4075. Vector4.prototype.divide = function (otherVector) {
  4076. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4077. };
  4078. /**
  4079. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4080. * Returns the current Vector4.
  4081. */
  4082. Vector4.prototype.divideToRef = function (otherVector, result) {
  4083. result.x = this.x / otherVector.x;
  4084. result.y = this.y / otherVector.y;
  4085. result.z = this.z / otherVector.z;
  4086. result.w = this.w / otherVector.w;
  4087. return this;
  4088. };
  4089. /**
  4090. * Divides the current Vector3 coordinates by the given ones.
  4091. * @returns the updated Vector3.
  4092. */
  4093. Vector4.prototype.divideInPlace = function (otherVector) {
  4094. return this.divideToRef(otherVector, this);
  4095. };
  4096. /**
  4097. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4098. * @param other defines the second operand
  4099. * @returns the current updated Vector4
  4100. */
  4101. Vector4.prototype.minimizeInPlace = function (other) {
  4102. if (other.x < this.x)
  4103. this.x = other.x;
  4104. if (other.y < this.y)
  4105. this.y = other.y;
  4106. if (other.z < this.z)
  4107. this.z = other.z;
  4108. if (other.w < this.w)
  4109. this.w = other.w;
  4110. return this;
  4111. };
  4112. /**
  4113. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4114. * @param other defines the second operand
  4115. * @returns the current updated Vector4
  4116. */
  4117. Vector4.prototype.maximizeInPlace = function (other) {
  4118. if (other.x > this.x)
  4119. this.x = other.x;
  4120. if (other.y > this.y)
  4121. this.y = other.y;
  4122. if (other.z > this.z)
  4123. this.z = other.z;
  4124. if (other.w > this.w)
  4125. this.w = other.w;
  4126. return this;
  4127. };
  4128. // Properties
  4129. /**
  4130. * Returns the Vector4 length (float).
  4131. */
  4132. Vector4.prototype.length = function () {
  4133. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4134. };
  4135. /**
  4136. * Returns the Vector4 squared length (float).
  4137. */
  4138. Vector4.prototype.lengthSquared = function () {
  4139. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4140. };
  4141. // Methods
  4142. /**
  4143. * Normalizes in place the Vector4.
  4144. * Returns the updated Vector4.
  4145. */
  4146. Vector4.prototype.normalize = function () {
  4147. var len = this.length();
  4148. if (len === 0)
  4149. return this;
  4150. var num = 1.0 / len;
  4151. this.x *= num;
  4152. this.y *= num;
  4153. this.z *= num;
  4154. this.w *= num;
  4155. return this;
  4156. };
  4157. /**
  4158. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4159. */
  4160. Vector4.prototype.toVector3 = function () {
  4161. return new Vector3(this.x, this.y, this.z);
  4162. };
  4163. /**
  4164. * Returns a new Vector4 copied from the current one.
  4165. */
  4166. Vector4.prototype.clone = function () {
  4167. return new Vector4(this.x, this.y, this.z, this.w);
  4168. };
  4169. /**
  4170. * Updates the current Vector4 with the given one coordinates.
  4171. * Returns the updated Vector4.
  4172. */
  4173. Vector4.prototype.copyFrom = function (source) {
  4174. this.x = source.x;
  4175. this.y = source.y;
  4176. this.z = source.z;
  4177. this.w = source.w;
  4178. return this;
  4179. };
  4180. /**
  4181. * Updates the current Vector4 coordinates with the given floats.
  4182. * Returns the updated Vector4.
  4183. */
  4184. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4185. this.x = x;
  4186. this.y = y;
  4187. this.z = z;
  4188. this.w = w;
  4189. return this;
  4190. };
  4191. /**
  4192. * Updates the current Vector4 coordinates with the given floats.
  4193. * Returns the updated Vector4.
  4194. */
  4195. Vector4.prototype.set = function (x, y, z, w) {
  4196. return this.copyFromFloats(x, y, z, w);
  4197. };
  4198. // Statics
  4199. /**
  4200. * Returns a new Vector4 set from the starting index of the given array.
  4201. */
  4202. Vector4.FromArray = function (array, offset) {
  4203. if (!offset) {
  4204. offset = 0;
  4205. }
  4206. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4207. };
  4208. /**
  4209. * Updates the given vector "result" from the starting index of the given array.
  4210. */
  4211. Vector4.FromArrayToRef = function (array, offset, result) {
  4212. result.x = array[offset];
  4213. result.y = array[offset + 1];
  4214. result.z = array[offset + 2];
  4215. result.w = array[offset + 3];
  4216. };
  4217. /**
  4218. * Updates the given vector "result" from the starting index of the given Float32Array.
  4219. */
  4220. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4221. Vector4.FromArrayToRef(array, offset, result);
  4222. };
  4223. /**
  4224. * Updates the given vector "result" coordinates from the given floats.
  4225. */
  4226. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4227. result.x = x;
  4228. result.y = y;
  4229. result.z = z;
  4230. result.w = w;
  4231. };
  4232. /**
  4233. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4234. */
  4235. Vector4.Zero = function () {
  4236. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4237. };
  4238. /**
  4239. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4240. */
  4241. Vector4.One = function () {
  4242. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4243. };
  4244. /**
  4245. * Returns a new normalized Vector4 from the given one.
  4246. */
  4247. Vector4.Normalize = function (vector) {
  4248. var result = Vector4.Zero();
  4249. Vector4.NormalizeToRef(vector, result);
  4250. return result;
  4251. };
  4252. /**
  4253. * Updates the given vector "result" from the normalization of the given one.
  4254. */
  4255. Vector4.NormalizeToRef = function (vector, result) {
  4256. result.copyFrom(vector);
  4257. result.normalize();
  4258. };
  4259. Vector4.Minimize = function (left, right) {
  4260. var min = left.clone();
  4261. min.minimizeInPlace(right);
  4262. return min;
  4263. };
  4264. Vector4.Maximize = function (left, right) {
  4265. var max = left.clone();
  4266. max.maximizeInPlace(right);
  4267. return max;
  4268. };
  4269. /**
  4270. * Returns the distance (float) between the vectors "value1" and "value2".
  4271. */
  4272. Vector4.Distance = function (value1, value2) {
  4273. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4274. };
  4275. /**
  4276. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4277. */
  4278. Vector4.DistanceSquared = function (value1, value2) {
  4279. var x = value1.x - value2.x;
  4280. var y = value1.y - value2.y;
  4281. var z = value1.z - value2.z;
  4282. var w = value1.w - value2.w;
  4283. return (x * x) + (y * y) + (z * z) + (w * w);
  4284. };
  4285. /**
  4286. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4287. */
  4288. Vector4.Center = function (value1, value2) {
  4289. var center = value1.add(value2);
  4290. center.scaleInPlace(0.5);
  4291. return center;
  4292. };
  4293. /**
  4294. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4295. * This methods computes transformed normalized direction vectors only.
  4296. */
  4297. Vector4.TransformNormal = function (vector, transformation) {
  4298. var result = Vector4.Zero();
  4299. Vector4.TransformNormalToRef(vector, transformation, result);
  4300. return result;
  4301. };
  4302. /**
  4303. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4304. * This methods computes transformed normalized direction vectors only.
  4305. */
  4306. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4307. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4308. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4309. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4310. result.x = x;
  4311. result.y = y;
  4312. result.z = z;
  4313. result.w = vector.w;
  4314. };
  4315. /**
  4316. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4317. * This methods computes transformed normalized direction vectors only.
  4318. */
  4319. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4320. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4321. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4322. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4323. result.w = w;
  4324. };
  4325. return Vector4;
  4326. }());
  4327. BABYLON.Vector4 = Vector4;
  4328. var Size = /** @class */ (function () {
  4329. /**
  4330. * Creates a Size object from the given width and height (floats).
  4331. */
  4332. function Size(width, height) {
  4333. this.width = width;
  4334. this.height = height;
  4335. }
  4336. // Returns a string with the Size width and height.
  4337. Size.prototype.toString = function () {
  4338. return "{W: " + this.width + ", H: " + this.height + "}";
  4339. };
  4340. /**
  4341. * Returns the string "Size"
  4342. */
  4343. Size.prototype.getClassName = function () {
  4344. return "Size";
  4345. };
  4346. /**
  4347. * Returns the Size hash code.
  4348. */
  4349. Size.prototype.getHashCode = function () {
  4350. var hash = this.width || 0;
  4351. hash = (hash * 397) ^ (this.height || 0);
  4352. return hash;
  4353. };
  4354. /**
  4355. * Updates the current size from the given one.
  4356. * Returns the updated Size.
  4357. */
  4358. Size.prototype.copyFrom = function (src) {
  4359. this.width = src.width;
  4360. this.height = src.height;
  4361. };
  4362. /**
  4363. * Updates in place the current Size from the given floats.
  4364. * Returns the updated Size.
  4365. */
  4366. Size.prototype.copyFromFloats = function (width, height) {
  4367. this.width = width;
  4368. this.height = height;
  4369. return this;
  4370. };
  4371. /**
  4372. * Updates in place the current Size from the given floats.
  4373. * Returns the updated Size.
  4374. */
  4375. Size.prototype.set = function (width, height) {
  4376. return this.copyFromFloats(width, height);
  4377. };
  4378. /**
  4379. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4380. */
  4381. Size.prototype.multiplyByFloats = function (w, h) {
  4382. return new Size(this.width * w, this.height * h);
  4383. };
  4384. /**
  4385. * Returns a new Size copied from the given one.
  4386. */
  4387. Size.prototype.clone = function () {
  4388. return new Size(this.width, this.height);
  4389. };
  4390. /**
  4391. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4392. */
  4393. Size.prototype.equals = function (other) {
  4394. if (!other) {
  4395. return false;
  4396. }
  4397. return (this.width === other.width) && (this.height === other.height);
  4398. };
  4399. Object.defineProperty(Size.prototype, "surface", {
  4400. /**
  4401. * Returns the surface of the Size : width * height (float).
  4402. */
  4403. get: function () {
  4404. return this.width * this.height;
  4405. },
  4406. enumerable: true,
  4407. configurable: true
  4408. });
  4409. /**
  4410. * Returns a new Size set to (0.0, 0.0)
  4411. */
  4412. Size.Zero = function () {
  4413. return new Size(0.0, 0.0);
  4414. };
  4415. /**
  4416. * Returns a new Size set as the addition result of the current Size and the given one.
  4417. */
  4418. Size.prototype.add = function (otherSize) {
  4419. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4420. return r;
  4421. };
  4422. /**
  4423. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4424. */
  4425. Size.prototype.subtract = function (otherSize) {
  4426. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4427. return r;
  4428. };
  4429. /**
  4430. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4431. */
  4432. Size.Lerp = function (start, end, amount) {
  4433. var w = start.width + ((end.width - start.width) * amount);
  4434. var h = start.height + ((end.height - start.height) * amount);
  4435. return new Size(w, h);
  4436. };
  4437. return Size;
  4438. }());
  4439. BABYLON.Size = Size;
  4440. /**
  4441. * Class used to store quaternion data
  4442. * @see https://en.wikipedia.org/wiki/Quaternion
  4443. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4444. */
  4445. var Quaternion = /** @class */ (function () {
  4446. /**
  4447. * Creates a new Quaternion from the given floats
  4448. * @param x defines the first component (0 by default)
  4449. * @param y defines the second component (0 by default)
  4450. * @param z defines the third component (0 by default)
  4451. * @param w defines the fourth component (1.0 by default)
  4452. */
  4453. function Quaternion(
  4454. /** defines the first component (0 by default) */
  4455. x,
  4456. /** defines the second component (0 by default) */
  4457. y,
  4458. /** defines the third component (0 by default) */
  4459. z,
  4460. /** defines the fourth component (1.0 by default) */
  4461. w) {
  4462. if (x === void 0) { x = 0.0; }
  4463. if (y === void 0) { y = 0.0; }
  4464. if (z === void 0) { z = 0.0; }
  4465. if (w === void 0) { w = 1.0; }
  4466. this.x = x;
  4467. this.y = y;
  4468. this.z = z;
  4469. this.w = w;
  4470. }
  4471. /**
  4472. * Gets a string representation for the current quaternion
  4473. * @returns a string with the Quaternion coordinates
  4474. */
  4475. Quaternion.prototype.toString = function () {
  4476. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4477. };
  4478. /**
  4479. * Gets the class name of the quaternion
  4480. * @returns the string "Quaternion"
  4481. */
  4482. Quaternion.prototype.getClassName = function () {
  4483. return "Quaternion";
  4484. };
  4485. /**
  4486. * Gets a hash code for this quaternion
  4487. * @returns the quaternion hash code
  4488. */
  4489. Quaternion.prototype.getHashCode = function () {
  4490. var hash = this.x || 0;
  4491. hash = (hash * 397) ^ (this.y || 0);
  4492. hash = (hash * 397) ^ (this.z || 0);
  4493. hash = (hash * 397) ^ (this.w || 0);
  4494. return hash;
  4495. };
  4496. /**
  4497. * Copy the quaternion to an array
  4498. * @returns a new array populated with 4 elements from the quaternion coordinates
  4499. */
  4500. Quaternion.prototype.asArray = function () {
  4501. return [this.x, this.y, this.z, this.w];
  4502. };
  4503. /**
  4504. * Check if two quaternions are equals
  4505. * @param otherQuaternion defines the second operand
  4506. * @return true if the current quaternion and the given one coordinates are strictly equals
  4507. */
  4508. Quaternion.prototype.equals = function (otherQuaternion) {
  4509. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4510. };
  4511. /**
  4512. * Clone the current quaternion
  4513. * @returns a new quaternion copied from the current one
  4514. */
  4515. Quaternion.prototype.clone = function () {
  4516. return new Quaternion(this.x, this.y, this.z, this.w);
  4517. };
  4518. /**
  4519. * Copy a quaternion to the current one
  4520. * @param other defines the other quaternion
  4521. * @returns the updated current quaternion
  4522. */
  4523. Quaternion.prototype.copyFrom = function (other) {
  4524. this.x = other.x;
  4525. this.y = other.y;
  4526. this.z = other.z;
  4527. this.w = other.w;
  4528. return this;
  4529. };
  4530. /**
  4531. * Updates the current quaternion with the given float coordinates
  4532. * @param x defines the x coordinate
  4533. * @param y defines the y coordinate
  4534. * @param z defines the z coordinate
  4535. * @param w defines the w coordinate
  4536. * @returns the updated current quaternion
  4537. */
  4538. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4539. this.x = x;
  4540. this.y = y;
  4541. this.z = z;
  4542. this.w = w;
  4543. return this;
  4544. };
  4545. /**
  4546. * Updates the current quaternion from the given float coordinates
  4547. * @param x defines the x coordinate
  4548. * @param y defines the y coordinate
  4549. * @param z defines the z coordinate
  4550. * @param w defines the w coordinate
  4551. * @returns the updated current quaternion
  4552. */
  4553. Quaternion.prototype.set = function (x, y, z, w) {
  4554. return this.copyFromFloats(x, y, z, w);
  4555. };
  4556. /**
  4557. * Adds two quaternions
  4558. * @param other defines the second operand
  4559. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4560. */
  4561. Quaternion.prototype.add = function (other) {
  4562. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4563. };
  4564. /**
  4565. * Add a quaternion to the current one
  4566. * @param other defines the quaternion to add
  4567. * @returns the current quaternion
  4568. */
  4569. Quaternion.prototype.addInPlace = function (other) {
  4570. this.x += other.x;
  4571. this.y += other.y;
  4572. this.z += other.z;
  4573. this.w += other.w;
  4574. return this;
  4575. };
  4576. /**
  4577. * Subtract two quaternions
  4578. * @param other defines the second operand
  4579. * @returns a new quaternion as the subtraction result of the given one from the current one
  4580. */
  4581. Quaternion.prototype.subtract = function (other) {
  4582. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4583. };
  4584. /**
  4585. * Multiplies the current quaternion by a scale factor
  4586. * @param value defines the scale factor
  4587. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4588. */
  4589. Quaternion.prototype.scale = function (value) {
  4590. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4591. };
  4592. /**
  4593. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4594. * @param scale defines the scale factor
  4595. * @param result defines the Quaternion object where to store the result
  4596. * @returns the unmodified current quaternion
  4597. */
  4598. Quaternion.prototype.scaleToRef = function (scale, result) {
  4599. result.x = this.x * scale;
  4600. result.y = this.y * scale;
  4601. result.z = this.z * scale;
  4602. result.w = this.w * scale;
  4603. return this;
  4604. };
  4605. /**
  4606. * Multiplies in place the current quaternion by a scale factor
  4607. * @param value defines the scale factor
  4608. * @returns the current modified quaternion
  4609. */
  4610. Quaternion.prototype.scaleInPlace = function (value) {
  4611. this.x *= value;
  4612. this.y *= value;
  4613. this.z *= value;
  4614. this.w *= value;
  4615. return this;
  4616. };
  4617. /**
  4618. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4619. * @param scale defines the scale factor
  4620. * @param result defines the Quaternion object where to store the result
  4621. * @returns the unmodified current quaternion
  4622. */
  4623. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4624. result.x += this.x * scale;
  4625. result.y += this.y * scale;
  4626. result.z += this.z * scale;
  4627. result.w += this.w * scale;
  4628. return this;
  4629. };
  4630. /**
  4631. * Multiplies two quaternions
  4632. * @param q1 defines the second operand
  4633. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4634. */
  4635. Quaternion.prototype.multiply = function (q1) {
  4636. var result = new Quaternion(0, 0, 0, 1.0);
  4637. this.multiplyToRef(q1, result);
  4638. return result;
  4639. };
  4640. /**
  4641. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4642. * @param q1 defines the second operand
  4643. * @param result defines the target quaternion
  4644. * @returns the current quaternion
  4645. */
  4646. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4647. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4648. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4649. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4650. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4651. result.copyFromFloats(x, y, z, w);
  4652. return this;
  4653. };
  4654. /**
  4655. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4656. * @param q1 defines the second operand
  4657. * @returns the currentupdated quaternion
  4658. */
  4659. Quaternion.prototype.multiplyInPlace = function (q1) {
  4660. this.multiplyToRef(q1, this);
  4661. return this;
  4662. };
  4663. /**
  4664. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4665. * @param ref defines the target quaternion
  4666. * @returns the current quaternion
  4667. */
  4668. Quaternion.prototype.conjugateToRef = function (ref) {
  4669. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4670. return this;
  4671. };
  4672. /**
  4673. * Conjugates in place (1-q) the current quaternion
  4674. * @returns the current updated quaternion
  4675. */
  4676. Quaternion.prototype.conjugateInPlace = function () {
  4677. this.x *= -1;
  4678. this.y *= -1;
  4679. this.z *= -1;
  4680. return this;
  4681. };
  4682. /**
  4683. * Conjugates in place (1-q) the current quaternion
  4684. * @returns a new quaternion
  4685. */
  4686. Quaternion.prototype.conjugate = function () {
  4687. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4688. return result;
  4689. };
  4690. /**
  4691. * Gets length of current quaternion
  4692. * @returns the quaternion length (float)
  4693. */
  4694. Quaternion.prototype.length = function () {
  4695. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4696. };
  4697. /**
  4698. * Normalize in place the current quaternion
  4699. * @returns the current updated quaternion
  4700. */
  4701. Quaternion.prototype.normalize = function () {
  4702. var length = 1.0 / this.length();
  4703. this.x *= length;
  4704. this.y *= length;
  4705. this.z *= length;
  4706. this.w *= length;
  4707. return this;
  4708. };
  4709. /**
  4710. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4711. * @param order is a reserved parameter and is ignore for now
  4712. * @returns a new Vector3 containing the Euler angles
  4713. */
  4714. Quaternion.prototype.toEulerAngles = function (order) {
  4715. if (order === void 0) { order = "YZX"; }
  4716. var result = Vector3.Zero();
  4717. this.toEulerAnglesToRef(result, order);
  4718. return result;
  4719. };
  4720. /**
  4721. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4722. * @param result defines the vector which will be filled with the Euler angles
  4723. * @param order is a reserved parameter and is ignore for now
  4724. * @returns the current unchanged quaternion
  4725. */
  4726. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4727. if (order === void 0) { order = "YZX"; }
  4728. var qz = this.z;
  4729. var qx = this.x;
  4730. var qy = this.y;
  4731. var qw = this.w;
  4732. var sqw = qw * qw;
  4733. var sqz = qz * qz;
  4734. var sqx = qx * qx;
  4735. var sqy = qy * qy;
  4736. var zAxisY = qy * qz - qx * qw;
  4737. var limit = .4999999;
  4738. if (zAxisY < -limit) {
  4739. result.y = 2 * Math.atan2(qy, qw);
  4740. result.x = Math.PI / 2;
  4741. result.z = 0;
  4742. }
  4743. else if (zAxisY > limit) {
  4744. result.y = 2 * Math.atan2(qy, qw);
  4745. result.x = -Math.PI / 2;
  4746. result.z = 0;
  4747. }
  4748. else {
  4749. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4750. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4751. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4752. }
  4753. return this;
  4754. };
  4755. /**
  4756. * Updates the given rotation matrix with the current quaternion values
  4757. * @param result defines the target matrix
  4758. * @returns the current unchanged quaternion
  4759. */
  4760. Quaternion.prototype.toRotationMatrix = function (result) {
  4761. var xx = this.x * this.x;
  4762. var yy = this.y * this.y;
  4763. var zz = this.z * this.z;
  4764. var xy = this.x * this.y;
  4765. var zw = this.z * this.w;
  4766. var zx = this.z * this.x;
  4767. var yw = this.y * this.w;
  4768. var yz = this.y * this.z;
  4769. var xw = this.x * this.w;
  4770. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4771. result.m[1] = 2.0 * (xy + zw);
  4772. result.m[2] = 2.0 * (zx - yw);
  4773. result.m[3] = 0;
  4774. result.m[4] = 2.0 * (xy - zw);
  4775. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4776. result.m[6] = 2.0 * (yz + xw);
  4777. result.m[7] = 0;
  4778. result.m[8] = 2.0 * (zx + yw);
  4779. result.m[9] = 2.0 * (yz - xw);
  4780. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4781. result.m[11] = 0;
  4782. result.m[12] = 0;
  4783. result.m[13] = 0;
  4784. result.m[14] = 0;
  4785. result.m[15] = 1.0;
  4786. result._markAsUpdated();
  4787. return this;
  4788. };
  4789. /**
  4790. * Updates the current quaternion from the given rotation matrix values
  4791. * @param matrix defines the source matrix
  4792. * @returns the current updated quaternion
  4793. */
  4794. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4795. Quaternion.FromRotationMatrixToRef(matrix, this);
  4796. return this;
  4797. };
  4798. // Statics
  4799. /**
  4800. * Creates a new quaternion from a rotation matrix
  4801. * @param matrix defines the source matrix
  4802. * @returns a new quaternion created from the given rotation matrix values
  4803. */
  4804. Quaternion.FromRotationMatrix = function (matrix) {
  4805. var result = new Quaternion();
  4806. Quaternion.FromRotationMatrixToRef(matrix, result);
  4807. return result;
  4808. };
  4809. /**
  4810. * Updates the given quaternion with the given rotation matrix values
  4811. * @param matrix defines the source matrix
  4812. * @param result defines the target quaternion
  4813. */
  4814. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4815. var data = matrix.m;
  4816. var m11 = data[0], m12 = data[4], m13 = data[8];
  4817. var m21 = data[1], m22 = data[5], m23 = data[9];
  4818. var m31 = data[2], m32 = data[6], m33 = data[10];
  4819. var trace = m11 + m22 + m33;
  4820. var s;
  4821. if (trace > 0) {
  4822. s = 0.5 / Math.sqrt(trace + 1.0);
  4823. result.w = 0.25 / s;
  4824. result.x = (m32 - m23) * s;
  4825. result.y = (m13 - m31) * s;
  4826. result.z = (m21 - m12) * s;
  4827. }
  4828. else if (m11 > m22 && m11 > m33) {
  4829. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4830. result.w = (m32 - m23) / s;
  4831. result.x = 0.25 * s;
  4832. result.y = (m12 + m21) / s;
  4833. result.z = (m13 + m31) / s;
  4834. }
  4835. else if (m22 > m33) {
  4836. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4837. result.w = (m13 - m31) / s;
  4838. result.x = (m12 + m21) / s;
  4839. result.y = 0.25 * s;
  4840. result.z = (m23 + m32) / s;
  4841. }
  4842. else {
  4843. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4844. result.w = (m21 - m12) / s;
  4845. result.x = (m13 + m31) / s;
  4846. result.y = (m23 + m32) / s;
  4847. result.z = 0.25 * s;
  4848. }
  4849. };
  4850. /**
  4851. * Creates an empty quaternion
  4852. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4853. */
  4854. Quaternion.Zero = function () {
  4855. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4856. };
  4857. /**
  4858. * Inverse a given quaternion
  4859. * @param q defines the source quaternion
  4860. * @returns a new quaternion as the inverted current quaternion
  4861. */
  4862. Quaternion.Inverse = function (q) {
  4863. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4864. };
  4865. /**
  4866. * Creates an identity quaternion
  4867. * @returns the identity quaternion
  4868. */
  4869. Quaternion.Identity = function () {
  4870. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4871. };
  4872. /**
  4873. * Gets a boolean indicating if the given quaternion is identity
  4874. * @param quaternion defines the quaternion to check
  4875. * @returns true if the quaternion is identity
  4876. */
  4877. Quaternion.IsIdentity = function (quaternion) {
  4878. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4879. };
  4880. /**
  4881. * Creates a quaternion from a rotation around an axis
  4882. * @param axis defines the axis to use
  4883. * @param angle defines the angle to use
  4884. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4885. */
  4886. Quaternion.RotationAxis = function (axis, angle) {
  4887. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4888. };
  4889. /**
  4890. * Creates a rotation around an axis and stores it into the given quaternion
  4891. * @param axis defines the axis to use
  4892. * @param angle defines the angle to use
  4893. * @param result defines the target quaternion
  4894. * @returns the target quaternion
  4895. */
  4896. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4897. var sin = Math.sin(angle / 2);
  4898. axis.normalize();
  4899. result.w = Math.cos(angle / 2);
  4900. result.x = axis.x * sin;
  4901. result.y = axis.y * sin;
  4902. result.z = axis.z * sin;
  4903. return result;
  4904. };
  4905. /**
  4906. * Creates a new quaternion from data stored into an array
  4907. * @param array defines the data source
  4908. * @param offset defines the offset in the source array where the data starts
  4909. * @returns a new quaternion
  4910. */
  4911. Quaternion.FromArray = function (array, offset) {
  4912. if (!offset) {
  4913. offset = 0;
  4914. }
  4915. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4916. };
  4917. /**
  4918. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4919. * @param yaw defines the rotation around Y axis
  4920. * @param pitch defines the rotation around X axis
  4921. * @param roll defines the rotation around Z axis
  4922. * @returns the new quaternion
  4923. */
  4924. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4925. var q = new Quaternion();
  4926. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4927. return q;
  4928. };
  4929. /**
  4930. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4931. * @param yaw defines the rotation around Y axis
  4932. * @param pitch defines the rotation around X axis
  4933. * @param roll defines the rotation around Z axis
  4934. * @param result defines the target quaternion
  4935. */
  4936. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4937. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4938. var halfRoll = roll * 0.5;
  4939. var halfPitch = pitch * 0.5;
  4940. var halfYaw = yaw * 0.5;
  4941. var sinRoll = Math.sin(halfRoll);
  4942. var cosRoll = Math.cos(halfRoll);
  4943. var sinPitch = Math.sin(halfPitch);
  4944. var cosPitch = Math.cos(halfPitch);
  4945. var sinYaw = Math.sin(halfYaw);
  4946. var cosYaw = Math.cos(halfYaw);
  4947. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4948. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4949. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4950. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4951. };
  4952. /**
  4953. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4954. * @param alpha defines the rotation around first axis
  4955. * @param beta defines the rotation around second axis
  4956. * @param gamma defines the rotation around third axis
  4957. * @returns the new quaternion
  4958. */
  4959. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4960. var result = new Quaternion();
  4961. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4962. return result;
  4963. };
  4964. /**
  4965. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4966. * @param alpha defines the rotation around first axis
  4967. * @param beta defines the rotation around second axis
  4968. * @param gamma defines the rotation around third axis
  4969. * @param result defines the target quaternion
  4970. */
  4971. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4972. // Produces a quaternion from Euler angles in the z-x-z orientation
  4973. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4974. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4975. var halfBeta = beta * 0.5;
  4976. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4977. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4978. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4979. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4980. };
  4981. /**
  4982. * 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)
  4983. * @param axis1 defines the first axis
  4984. * @param axis2 defines the second axis
  4985. * @param axis3 defines the third axis
  4986. * @returns the new quaternion
  4987. */
  4988. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4989. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4990. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4991. return quat;
  4992. };
  4993. /**
  4994. * 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
  4995. * @param axis1 defines the first axis
  4996. * @param axis2 defines the second axis
  4997. * @param axis3 defines the third axis
  4998. * @param ref defines the target quaternion
  4999. */
  5000. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5001. var rotMat = MathTmp.Matrix[0];
  5002. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5003. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5004. };
  5005. /**
  5006. * Interpolates between two quaternions
  5007. * @param left defines first quaternion
  5008. * @param right defines second quaternion
  5009. * @param amount defines the gradient to use
  5010. * @returns the new interpolated quaternion
  5011. */
  5012. Quaternion.Slerp = function (left, right, amount) {
  5013. var result = Quaternion.Identity();
  5014. Quaternion.SlerpToRef(left, right, amount, result);
  5015. return result;
  5016. };
  5017. /**
  5018. * Interpolates between two quaternions and stores it into a target quaternion
  5019. * @param left defines first quaternion
  5020. * @param right defines second quaternion
  5021. * @param amount defines the gradient to use
  5022. * @param result defines the target quaternion
  5023. */
  5024. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5025. var num2;
  5026. var num3;
  5027. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5028. var flag = false;
  5029. if (num4 < 0) {
  5030. flag = true;
  5031. num4 = -num4;
  5032. }
  5033. if (num4 > 0.999999) {
  5034. num3 = 1 - amount;
  5035. num2 = flag ? -amount : amount;
  5036. }
  5037. else {
  5038. var num5 = Math.acos(num4);
  5039. var num6 = (1.0 / Math.sin(num5));
  5040. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5041. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5042. }
  5043. result.x = (num3 * left.x) + (num2 * right.x);
  5044. result.y = (num3 * left.y) + (num2 * right.y);
  5045. result.z = (num3 * left.z) + (num2 * right.z);
  5046. result.w = (num3 * left.w) + (num2 * right.w);
  5047. };
  5048. /**
  5049. * Interpolate between two quaternions using Hermite interpolation
  5050. * @param value1 defines first quaternion
  5051. * @param tangent1 defines the incoming tangent
  5052. * @param value2 defines second quaternion
  5053. * @param tangent2 defines the outgoing tangent
  5054. * @param amount defines the target quaternion
  5055. * @returns the new interpolated quaternion
  5056. */
  5057. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5058. var squared = amount * amount;
  5059. var cubed = amount * squared;
  5060. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5061. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5062. var part3 = (cubed - (2.0 * squared)) + amount;
  5063. var part4 = cubed - squared;
  5064. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5065. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5066. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5067. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5068. return new Quaternion(x, y, z, w);
  5069. };
  5070. return Quaternion;
  5071. }());
  5072. BABYLON.Quaternion = Quaternion;
  5073. /**
  5074. * Class used to store matrix data (4x4)
  5075. */
  5076. var Matrix = /** @class */ (function () {
  5077. /**
  5078. * Creates an empty matrix (filled with zeros)
  5079. */
  5080. function Matrix() {
  5081. this._isIdentity = false;
  5082. this._isIdentityDirty = true;
  5083. /**
  5084. * Gets or sets the internal data of the matrix
  5085. */
  5086. this.m = new Float32Array(16);
  5087. this._markAsUpdated();
  5088. }
  5089. /** @hidden */
  5090. Matrix.prototype._markAsUpdated = function () {
  5091. this.updateFlag = Matrix._updateFlagSeed++;
  5092. this._isIdentityDirty = true;
  5093. };
  5094. // Properties
  5095. /**
  5096. * Check if the current matrix is indentity
  5097. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5098. * @returns true is the matrix is the identity matrix
  5099. */
  5100. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5101. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5102. if (this._isIdentityDirty) {
  5103. this._isIdentityDirty = false;
  5104. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5105. this._isIdentity = false;
  5106. }
  5107. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5108. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5109. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5110. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5111. this._isIdentity = false;
  5112. }
  5113. else {
  5114. this._isIdentity = true;
  5115. }
  5116. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5117. this._isIdentity = false;
  5118. }
  5119. }
  5120. return this._isIdentity;
  5121. };
  5122. /**
  5123. * Gets the determinant of the matrix
  5124. * @returns the matrix determinant
  5125. */
  5126. Matrix.prototype.determinant = function () {
  5127. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5128. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5129. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5130. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5131. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5132. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5133. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5134. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5135. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5136. };
  5137. // Methods
  5138. /**
  5139. * Returns the matrix as a Float32Array
  5140. * @returns the matrix underlying array
  5141. */
  5142. Matrix.prototype.toArray = function () {
  5143. return this.m;
  5144. };
  5145. /**
  5146. * Returns the matrix as a Float32Array
  5147. * @returns the matrix underlying array.
  5148. */
  5149. Matrix.prototype.asArray = function () {
  5150. return this.toArray();
  5151. };
  5152. /**
  5153. * Inverts the current matrix in place
  5154. * @returns the current inverted matrix
  5155. */
  5156. Matrix.prototype.invert = function () {
  5157. this.invertToRef(this);
  5158. return this;
  5159. };
  5160. /**
  5161. * Sets all the matrix elements to zero
  5162. * @returns the current matrix
  5163. */
  5164. Matrix.prototype.reset = function () {
  5165. for (var index = 0; index < 16; index++) {
  5166. this.m[index] = 0.0;
  5167. }
  5168. this._markAsUpdated();
  5169. return this;
  5170. };
  5171. /**
  5172. * Adds the current matrix with a second one
  5173. * @param other defines the matrix to add
  5174. * @returns a new matrix as the addition of the current matrix and the given one
  5175. */
  5176. Matrix.prototype.add = function (other) {
  5177. var result = new Matrix();
  5178. this.addToRef(other, result);
  5179. return result;
  5180. };
  5181. /**
  5182. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5183. * @param other defines the matrix to add
  5184. * @param result defines the target matrix
  5185. * @returns the current matrix
  5186. */
  5187. Matrix.prototype.addToRef = function (other, result) {
  5188. for (var index = 0; index < 16; index++) {
  5189. result.m[index] = this.m[index] + other.m[index];
  5190. }
  5191. result._markAsUpdated();
  5192. return this;
  5193. };
  5194. /**
  5195. * Adds in place the given matrix to the current matrix
  5196. * @param other defines the second operand
  5197. * @returns the current updated matrix
  5198. */
  5199. Matrix.prototype.addToSelf = function (other) {
  5200. for (var index = 0; index < 16; index++) {
  5201. this.m[index] += other.m[index];
  5202. }
  5203. this._markAsUpdated();
  5204. return this;
  5205. };
  5206. /**
  5207. * Sets the given matrix to the current inverted Matrix
  5208. * @param other defines the target matrix
  5209. * @returns the unmodified current matrix
  5210. */
  5211. Matrix.prototype.invertToRef = function (other) {
  5212. var l1 = this.m[0];
  5213. var l2 = this.m[1];
  5214. var l3 = this.m[2];
  5215. var l4 = this.m[3];
  5216. var l5 = this.m[4];
  5217. var l6 = this.m[5];
  5218. var l7 = this.m[6];
  5219. var l8 = this.m[7];
  5220. var l9 = this.m[8];
  5221. var l10 = this.m[9];
  5222. var l11 = this.m[10];
  5223. var l12 = this.m[11];
  5224. var l13 = this.m[12];
  5225. var l14 = this.m[13];
  5226. var l15 = this.m[14];
  5227. var l16 = this.m[15];
  5228. var l17 = (l11 * l16) - (l12 * l15);
  5229. var l18 = (l10 * l16) - (l12 * l14);
  5230. var l19 = (l10 * l15) - (l11 * l14);
  5231. var l20 = (l9 * l16) - (l12 * l13);
  5232. var l21 = (l9 * l15) - (l11 * l13);
  5233. var l22 = (l9 * l14) - (l10 * l13);
  5234. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5235. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5236. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5237. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5238. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5239. var l28 = (l7 * l16) - (l8 * l15);
  5240. var l29 = (l6 * l16) - (l8 * l14);
  5241. var l30 = (l6 * l15) - (l7 * l14);
  5242. var l31 = (l5 * l16) - (l8 * l13);
  5243. var l32 = (l5 * l15) - (l7 * l13);
  5244. var l33 = (l5 * l14) - (l6 * l13);
  5245. var l34 = (l7 * l12) - (l8 * l11);
  5246. var l35 = (l6 * l12) - (l8 * l10);
  5247. var l36 = (l6 * l11) - (l7 * l10);
  5248. var l37 = (l5 * l12) - (l8 * l9);
  5249. var l38 = (l5 * l11) - (l7 * l9);
  5250. var l39 = (l5 * l10) - (l6 * l9);
  5251. other.m[0] = l23 * l27;
  5252. other.m[4] = l24 * l27;
  5253. other.m[8] = l25 * l27;
  5254. other.m[12] = l26 * l27;
  5255. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5256. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5257. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5258. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5259. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5260. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5261. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5262. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5263. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5264. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5265. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5266. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5267. other._markAsUpdated();
  5268. return this;
  5269. };
  5270. /**
  5271. * Inserts the translation vector (using 3 floats) in the current matrix
  5272. * @param x defines the 1st component of the translation
  5273. * @param y defines the 2nd component of the translation
  5274. * @param z defines the 3rd component of the translation
  5275. * @returns the current updated matrix
  5276. */
  5277. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5278. this.m[12] = x;
  5279. this.m[13] = y;
  5280. this.m[14] = z;
  5281. this._markAsUpdated();
  5282. return this;
  5283. };
  5284. /**
  5285. * Inserts the translation vector in the current matrix
  5286. * @param vector3 defines the translation to insert
  5287. * @returns the current updated matrix
  5288. */
  5289. Matrix.prototype.setTranslation = function (vector3) {
  5290. this.m[12] = vector3.x;
  5291. this.m[13] = vector3.y;
  5292. this.m[14] = vector3.z;
  5293. this._markAsUpdated();
  5294. return this;
  5295. };
  5296. /**
  5297. * Gets the translation value of the current matrix
  5298. * @returns a new Vector3 as the extracted translation from the matrix
  5299. */
  5300. Matrix.prototype.getTranslation = function () {
  5301. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5302. };
  5303. /**
  5304. * Fill a Vector3 with the extracted translation from the matrix
  5305. * @param result defines the Vector3 where to store the translation
  5306. * @returns the current matrix
  5307. */
  5308. Matrix.prototype.getTranslationToRef = function (result) {
  5309. result.x = this.m[12];
  5310. result.y = this.m[13];
  5311. result.z = this.m[14];
  5312. return this;
  5313. };
  5314. /**
  5315. * Remove rotation and scaling part from the matrix
  5316. * @returns the updated matrix
  5317. */
  5318. Matrix.prototype.removeRotationAndScaling = function () {
  5319. this.setRowFromFloats(0, 1, 0, 0, 0);
  5320. this.setRowFromFloats(1, 0, 1, 0, 0);
  5321. this.setRowFromFloats(2, 0, 0, 1, 0);
  5322. return this;
  5323. };
  5324. /**
  5325. * Multiply two matrices
  5326. * @param other defines the second operand
  5327. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5328. */
  5329. Matrix.prototype.multiply = function (other) {
  5330. var result = new Matrix();
  5331. this.multiplyToRef(other, result);
  5332. return result;
  5333. };
  5334. /**
  5335. * Copy the current matrix from the given one
  5336. * @param other defines the source matrix
  5337. * @returns the current updated matrix
  5338. */
  5339. Matrix.prototype.copyFrom = function (other) {
  5340. for (var index = 0; index < 16; index++) {
  5341. this.m[index] = other.m[index];
  5342. }
  5343. this._markAsUpdated();
  5344. return this;
  5345. };
  5346. /**
  5347. * Populates the given array from the starting index with the current matrix values
  5348. * @param array defines the target array
  5349. * @param offset defines the offset in the target array where to start storing values
  5350. * @returns the current matrix
  5351. */
  5352. Matrix.prototype.copyToArray = function (array, offset) {
  5353. if (offset === void 0) { offset = 0; }
  5354. for (var index = 0; index < 16; index++) {
  5355. array[offset + index] = this.m[index];
  5356. }
  5357. return this;
  5358. };
  5359. /**
  5360. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5361. * @param other defines the second operand
  5362. * @param result defines the matrix where to store the multiplication
  5363. * @returns the current matrix
  5364. */
  5365. Matrix.prototype.multiplyToRef = function (other, result) {
  5366. this.multiplyToArray(other, result.m, 0);
  5367. result._markAsUpdated();
  5368. return this;
  5369. };
  5370. /**
  5371. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5372. * @param other defines the second operand
  5373. * @param result defines the array where to store the multiplication
  5374. * @param offset defines the offset in the target array where to start storing values
  5375. * @returns the current matrix
  5376. */
  5377. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5378. var tm0 = this.m[0];
  5379. var tm1 = this.m[1];
  5380. var tm2 = this.m[2];
  5381. var tm3 = this.m[3];
  5382. var tm4 = this.m[4];
  5383. var tm5 = this.m[5];
  5384. var tm6 = this.m[6];
  5385. var tm7 = this.m[7];
  5386. var tm8 = this.m[8];
  5387. var tm9 = this.m[9];
  5388. var tm10 = this.m[10];
  5389. var tm11 = this.m[11];
  5390. var tm12 = this.m[12];
  5391. var tm13 = this.m[13];
  5392. var tm14 = this.m[14];
  5393. var tm15 = this.m[15];
  5394. var om0 = other.m[0];
  5395. var om1 = other.m[1];
  5396. var om2 = other.m[2];
  5397. var om3 = other.m[3];
  5398. var om4 = other.m[4];
  5399. var om5 = other.m[5];
  5400. var om6 = other.m[6];
  5401. var om7 = other.m[7];
  5402. var om8 = other.m[8];
  5403. var om9 = other.m[9];
  5404. var om10 = other.m[10];
  5405. var om11 = other.m[11];
  5406. var om12 = other.m[12];
  5407. var om13 = other.m[13];
  5408. var om14 = other.m[14];
  5409. var om15 = other.m[15];
  5410. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5411. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5412. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5413. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5414. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5415. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5416. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5417. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5418. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5419. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5420. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5421. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5422. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5423. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5424. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5425. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5426. return this;
  5427. };
  5428. /**
  5429. * Check equality between this matrix and a second one
  5430. * @param value defines the second matrix to compare
  5431. * @returns true is the current matrix and the given one values are strictly equal
  5432. */
  5433. Matrix.prototype.equals = function (value) {
  5434. return value &&
  5435. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5436. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5437. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5438. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5439. };
  5440. /**
  5441. * Clone the current matrix
  5442. * @returns a new matrix from the current matrix
  5443. */
  5444. Matrix.prototype.clone = function () {
  5445. 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]);
  5446. };
  5447. /**
  5448. * Returns the name of the current matrix class
  5449. * @returns the string "Matrix"
  5450. */
  5451. Matrix.prototype.getClassName = function () {
  5452. return "Matrix";
  5453. };
  5454. /**
  5455. * Gets the hash code of the current matrix
  5456. * @returns the hash code
  5457. */
  5458. Matrix.prototype.getHashCode = function () {
  5459. var hash = this.m[0] || 0;
  5460. for (var i = 1; i < 16; i++) {
  5461. hash = (hash * 397) ^ (this.m[i] || 0);
  5462. }
  5463. return hash;
  5464. };
  5465. /**
  5466. * Decomposes the current Matrix into a translation, rotation and scaling components
  5467. * @param scale defines the scale vector3 given as a reference to update
  5468. * @param rotation defines the rotation quaternion given as a reference to update
  5469. * @param translation defines the translation vector3 given as a reference to update
  5470. * @returns true if operation was successful
  5471. */
  5472. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5473. if (translation) {
  5474. translation.x = this.m[12];
  5475. translation.y = this.m[13];
  5476. translation.z = this.m[14];
  5477. }
  5478. scale = scale || MathTmp.Vector3[0];
  5479. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5480. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5481. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5482. if (this.determinant() <= 0) {
  5483. scale.y *= -1;
  5484. }
  5485. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5486. if (rotation) {
  5487. rotation.x = 0;
  5488. rotation.y = 0;
  5489. rotation.z = 0;
  5490. rotation.w = 1;
  5491. }
  5492. return false;
  5493. }
  5494. if (rotation) {
  5495. 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]);
  5496. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5497. }
  5498. return true;
  5499. };
  5500. /**
  5501. * Gets specific row of the matrix
  5502. * @param index defines the number of the row to get
  5503. * @returns the index-th row of the current matrix as a new Vector4
  5504. */
  5505. Matrix.prototype.getRow = function (index) {
  5506. if (index < 0 || index > 3) {
  5507. return null;
  5508. }
  5509. var i = index * 4;
  5510. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5511. };
  5512. /**
  5513. * Sets the index-th row of the current matrix to the vector4 values
  5514. * @param index defines the number of the row to set
  5515. * @param row defines the target vector4
  5516. * @returns the updated current matrix
  5517. */
  5518. Matrix.prototype.setRow = function (index, row) {
  5519. if (index < 0 || index > 3) {
  5520. return this;
  5521. }
  5522. var i = index * 4;
  5523. this.m[i + 0] = row.x;
  5524. this.m[i + 1] = row.y;
  5525. this.m[i + 2] = row.z;
  5526. this.m[i + 3] = row.w;
  5527. this._markAsUpdated();
  5528. return this;
  5529. };
  5530. /**
  5531. * Compute the transpose of the matrix
  5532. * @returns the new transposed matrix
  5533. */
  5534. Matrix.prototype.transpose = function () {
  5535. return Matrix.Transpose(this);
  5536. };
  5537. /**
  5538. * Compute the transpose of the matrix and store it in a given matrix
  5539. * @param result defines the target matrix
  5540. * @returns the current matrix
  5541. */
  5542. Matrix.prototype.transposeToRef = function (result) {
  5543. Matrix.TransposeToRef(this, result);
  5544. return this;
  5545. };
  5546. /**
  5547. * Sets the index-th row of the current matrix with the given 4 x float values
  5548. * @param index defines the row index
  5549. * @param x defines the x component to set
  5550. * @param y defines the y component to set
  5551. * @param z defines the z component to set
  5552. * @param w defines the w component to set
  5553. * @returns the updated current matrix
  5554. */
  5555. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5556. if (index < 0 || index > 3) {
  5557. return this;
  5558. }
  5559. var i = index * 4;
  5560. this.m[i + 0] = x;
  5561. this.m[i + 1] = y;
  5562. this.m[i + 2] = z;
  5563. this.m[i + 3] = w;
  5564. this._markAsUpdated();
  5565. return this;
  5566. };
  5567. /**
  5568. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5569. * @param scale defines the scale factor
  5570. * @returns a new matrix
  5571. */
  5572. Matrix.prototype.scale = function (scale) {
  5573. var result = new Matrix();
  5574. this.scaleToRef(scale, result);
  5575. return result;
  5576. };
  5577. /**
  5578. * Scale the current matrix values by a factor to a given result matrix
  5579. * @param scale defines the scale factor
  5580. * @param result defines the matrix to store the result
  5581. * @returns the current matrix
  5582. */
  5583. Matrix.prototype.scaleToRef = function (scale, result) {
  5584. for (var index = 0; index < 16; index++) {
  5585. result.m[index] = this.m[index] * scale;
  5586. }
  5587. result._markAsUpdated();
  5588. return this;
  5589. };
  5590. /**
  5591. * Scale the current matrix values by a factor and add the result to a given matrix
  5592. * @param scale defines the scale factor
  5593. * @param result defines the Matrix to store the result
  5594. * @returns the current matrix
  5595. */
  5596. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5597. for (var index = 0; index < 16; index++) {
  5598. result.m[index] += this.m[index] * scale;
  5599. }
  5600. result._markAsUpdated();
  5601. return this;
  5602. };
  5603. /**
  5604. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5605. * @param ref matrix to store the result
  5606. */
  5607. Matrix.prototype.toNormalMatrix = function (ref) {
  5608. this.invertToRef(ref);
  5609. ref.transpose();
  5610. var m = ref.m;
  5611. 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);
  5612. };
  5613. /**
  5614. * Gets only rotation part of the current matrix
  5615. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5616. */
  5617. Matrix.prototype.getRotationMatrix = function () {
  5618. var result = Matrix.Identity();
  5619. this.getRotationMatrixToRef(result);
  5620. return result;
  5621. };
  5622. /**
  5623. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5624. * @param result defines the target matrix to store data to
  5625. * @returns the current matrix
  5626. */
  5627. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5628. var m = this.m;
  5629. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5630. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5631. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5632. if (this.determinant() <= 0) {
  5633. sy *= -1;
  5634. }
  5635. if (sx === 0 || sy === 0 || sz === 0) {
  5636. Matrix.IdentityToRef(result);
  5637. }
  5638. else {
  5639. 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);
  5640. }
  5641. return this;
  5642. };
  5643. // Statics
  5644. /**
  5645. * Creates a matrix from an array
  5646. * @param array defines the source array
  5647. * @param offset defines an offset in the source array
  5648. * @returns a new Matrix set from the starting index of the given array
  5649. */
  5650. Matrix.FromArray = function (array, offset) {
  5651. var result = new Matrix();
  5652. if (!offset) {
  5653. offset = 0;
  5654. }
  5655. Matrix.FromArrayToRef(array, offset, result);
  5656. return result;
  5657. };
  5658. /**
  5659. * Copy the content of an array into a given matrix
  5660. * @param array defines the source array
  5661. * @param offset defines an offset in the source array
  5662. * @param result defines the target matrix
  5663. */
  5664. Matrix.FromArrayToRef = function (array, offset, result) {
  5665. for (var index = 0; index < 16; index++) {
  5666. result.m[index] = array[index + offset];
  5667. }
  5668. result._markAsUpdated();
  5669. };
  5670. /**
  5671. * Stores an array into a matrix after having multiplied each component by a given factor
  5672. * @param array defines the source array
  5673. * @param offset defines the offset in the source array
  5674. * @param scale defines the scaling factor
  5675. * @param result defines the target matrix
  5676. */
  5677. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5678. for (var index = 0; index < 16; index++) {
  5679. result.m[index] = array[index + offset] * scale;
  5680. }
  5681. result._markAsUpdated();
  5682. };
  5683. /**
  5684. * Stores a list of values (16) inside a given matrix
  5685. * @param initialM11 defines 1st value of 1st row
  5686. * @param initialM12 defines 2nd value of 1st row
  5687. * @param initialM13 defines 3rd value of 1st row
  5688. * @param initialM14 defines 4th value of 1st row
  5689. * @param initialM21 defines 1st value of 2nd row
  5690. * @param initialM22 defines 2nd value of 2nd row
  5691. * @param initialM23 defines 3rd value of 2nd row
  5692. * @param initialM24 defines 4th value of 2nd row
  5693. * @param initialM31 defines 1st value of 3rd row
  5694. * @param initialM32 defines 2nd value of 3rd row
  5695. * @param initialM33 defines 3rd value of 3rd row
  5696. * @param initialM34 defines 4th value of 3rd row
  5697. * @param initialM41 defines 1st value of 4th row
  5698. * @param initialM42 defines 2nd value of 4th row
  5699. * @param initialM43 defines 3rd value of 4th row
  5700. * @param initialM44 defines 4th value of 4th row
  5701. * @param result defines the target matrix
  5702. */
  5703. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5704. result.m[0] = initialM11;
  5705. result.m[1] = initialM12;
  5706. result.m[2] = initialM13;
  5707. result.m[3] = initialM14;
  5708. result.m[4] = initialM21;
  5709. result.m[5] = initialM22;
  5710. result.m[6] = initialM23;
  5711. result.m[7] = initialM24;
  5712. result.m[8] = initialM31;
  5713. result.m[9] = initialM32;
  5714. result.m[10] = initialM33;
  5715. result.m[11] = initialM34;
  5716. result.m[12] = initialM41;
  5717. result.m[13] = initialM42;
  5718. result.m[14] = initialM43;
  5719. result.m[15] = initialM44;
  5720. result._markAsUpdated();
  5721. };
  5722. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5723. /**
  5724. * Gets an identity matrix that must not be updated
  5725. */
  5726. get: function () {
  5727. return Matrix._identityReadOnly;
  5728. },
  5729. enumerable: true,
  5730. configurable: true
  5731. });
  5732. /**
  5733. * Creates new matrix from a list of values (16)
  5734. * @param initialM11 defines 1st value of 1st row
  5735. * @param initialM12 defines 2nd value of 1st row
  5736. * @param initialM13 defines 3rd value of 1st row
  5737. * @param initialM14 defines 4th value of 1st row
  5738. * @param initialM21 defines 1st value of 2nd row
  5739. * @param initialM22 defines 2nd value of 2nd row
  5740. * @param initialM23 defines 3rd value of 2nd row
  5741. * @param initialM24 defines 4th value of 2nd row
  5742. * @param initialM31 defines 1st value of 3rd row
  5743. * @param initialM32 defines 2nd value of 3rd row
  5744. * @param initialM33 defines 3rd value of 3rd row
  5745. * @param initialM34 defines 4th value of 3rd row
  5746. * @param initialM41 defines 1st value of 4th row
  5747. * @param initialM42 defines 2nd value of 4th row
  5748. * @param initialM43 defines 3rd value of 4th row
  5749. * @param initialM44 defines 4th value of 4th row
  5750. * @returns the new matrix
  5751. */
  5752. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5753. var result = new Matrix();
  5754. result.m[0] = initialM11;
  5755. result.m[1] = initialM12;
  5756. result.m[2] = initialM13;
  5757. result.m[3] = initialM14;
  5758. result.m[4] = initialM21;
  5759. result.m[5] = initialM22;
  5760. result.m[6] = initialM23;
  5761. result.m[7] = initialM24;
  5762. result.m[8] = initialM31;
  5763. result.m[9] = initialM32;
  5764. result.m[10] = initialM33;
  5765. result.m[11] = initialM34;
  5766. result.m[12] = initialM41;
  5767. result.m[13] = initialM42;
  5768. result.m[14] = initialM43;
  5769. result.m[15] = initialM44;
  5770. return result;
  5771. };
  5772. /**
  5773. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5774. * @param scale defines the scale vector3
  5775. * @param rotation defines the rotation quaternion
  5776. * @param translation defines the translation vector3
  5777. * @returns a new matrix
  5778. */
  5779. Matrix.Compose = function (scale, rotation, translation) {
  5780. var result = Matrix.Identity();
  5781. Matrix.ComposeToRef(scale, rotation, translation, result);
  5782. return result;
  5783. };
  5784. /**
  5785. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5786. * @param scale defines the scale vector3
  5787. * @param rotation defines the rotation quaternion
  5788. * @param translation defines the translation vector3
  5789. * @param result defines the target matrix
  5790. */
  5791. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5792. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5793. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5794. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5795. result.setTranslation(translation);
  5796. };
  5797. /**
  5798. * Creates a new identity matrix
  5799. * @returns a new identity matrix
  5800. */
  5801. Matrix.Identity = function () {
  5802. 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);
  5803. };
  5804. /**
  5805. * Creates a new identity matrix and stores the result in a given matrix
  5806. * @param result defines the target matrix
  5807. */
  5808. Matrix.IdentityToRef = function (result) {
  5809. 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);
  5810. };
  5811. /**
  5812. * Creates a new zero matrix
  5813. * @returns a new zero matrix
  5814. */
  5815. Matrix.Zero = function () {
  5816. 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);
  5817. };
  5818. /**
  5819. * Creates a new rotation matrix for "angle" radians around the X axis
  5820. * @param angle defines the angle (in radians) to use
  5821. * @return the new matrix
  5822. */
  5823. Matrix.RotationX = function (angle) {
  5824. var result = new Matrix();
  5825. Matrix.RotationXToRef(angle, result);
  5826. return result;
  5827. };
  5828. /**
  5829. * Creates a new matrix as the invert of a given matrix
  5830. * @param source defines the source matrix
  5831. * @returns the new matrix
  5832. */
  5833. Matrix.Invert = function (source) {
  5834. var result = new Matrix();
  5835. source.invertToRef(result);
  5836. return result;
  5837. };
  5838. /**
  5839. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5840. * @param angle defines the angle (in radians) to use
  5841. * @param result defines the target matrix
  5842. */
  5843. Matrix.RotationXToRef = function (angle, result) {
  5844. var s = Math.sin(angle);
  5845. var c = Math.cos(angle);
  5846. result.m[0] = 1.0;
  5847. result.m[15] = 1.0;
  5848. result.m[5] = c;
  5849. result.m[10] = c;
  5850. result.m[9] = -s;
  5851. result.m[6] = s;
  5852. result.m[1] = 0.0;
  5853. result.m[2] = 0.0;
  5854. result.m[3] = 0.0;
  5855. result.m[4] = 0.0;
  5856. result.m[7] = 0.0;
  5857. result.m[8] = 0.0;
  5858. result.m[11] = 0.0;
  5859. result.m[12] = 0.0;
  5860. result.m[13] = 0.0;
  5861. result.m[14] = 0.0;
  5862. result._markAsUpdated();
  5863. };
  5864. /**
  5865. * Creates a new rotation matrix for "angle" radians around the Y axis
  5866. * @param angle defines the angle (in radians) to use
  5867. * @return the new matrix
  5868. */
  5869. Matrix.RotationY = function (angle) {
  5870. var result = new Matrix();
  5871. Matrix.RotationYToRef(angle, result);
  5872. return result;
  5873. };
  5874. /**
  5875. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5876. * @param angle defines the angle (in radians) to use
  5877. * @param result defines the target matrix
  5878. */
  5879. Matrix.RotationYToRef = function (angle, result) {
  5880. var s = Math.sin(angle);
  5881. var c = Math.cos(angle);
  5882. result.m[5] = 1.0;
  5883. result.m[15] = 1.0;
  5884. result.m[0] = c;
  5885. result.m[2] = -s;
  5886. result.m[8] = s;
  5887. result.m[10] = c;
  5888. result.m[1] = 0.0;
  5889. result.m[3] = 0.0;
  5890. result.m[4] = 0.0;
  5891. result.m[6] = 0.0;
  5892. result.m[7] = 0.0;
  5893. result.m[9] = 0.0;
  5894. result.m[11] = 0.0;
  5895. result.m[12] = 0.0;
  5896. result.m[13] = 0.0;
  5897. result.m[14] = 0.0;
  5898. result._markAsUpdated();
  5899. };
  5900. /**
  5901. * Creates a new rotation matrix for "angle" radians around the Z axis
  5902. * @param angle defines the angle (in radians) to use
  5903. * @return the new matrix
  5904. */
  5905. Matrix.RotationZ = function (angle) {
  5906. var result = new Matrix();
  5907. Matrix.RotationZToRef(angle, result);
  5908. return result;
  5909. };
  5910. /**
  5911. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5912. * @param angle defines the angle (in radians) to use
  5913. * @param result defines the target matrix
  5914. */
  5915. Matrix.RotationZToRef = function (angle, result) {
  5916. var s = Math.sin(angle);
  5917. var c = Math.cos(angle);
  5918. result.m[10] = 1.0;
  5919. result.m[15] = 1.0;
  5920. result.m[0] = c;
  5921. result.m[1] = s;
  5922. result.m[4] = -s;
  5923. result.m[5] = c;
  5924. result.m[2] = 0.0;
  5925. result.m[3] = 0.0;
  5926. result.m[6] = 0.0;
  5927. result.m[7] = 0.0;
  5928. result.m[8] = 0.0;
  5929. result.m[9] = 0.0;
  5930. result.m[11] = 0.0;
  5931. result.m[12] = 0.0;
  5932. result.m[13] = 0.0;
  5933. result.m[14] = 0.0;
  5934. result._markAsUpdated();
  5935. };
  5936. /**
  5937. * Creates a new rotation matrix for "angle" radians around the given axis
  5938. * @param axis defines the axis to use
  5939. * @param angle defines the angle (in radians) to use
  5940. * @return the new matrix
  5941. */
  5942. Matrix.RotationAxis = function (axis, angle) {
  5943. var result = Matrix.Zero();
  5944. Matrix.RotationAxisToRef(axis, angle, result);
  5945. return result;
  5946. };
  5947. /**
  5948. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5949. * @param axis defines the axis to use
  5950. * @param angle defines the angle (in radians) to use
  5951. * @param result defines the target matrix
  5952. */
  5953. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5954. var s = Math.sin(-angle);
  5955. var c = Math.cos(-angle);
  5956. var c1 = 1 - c;
  5957. axis.normalize();
  5958. result.m[0] = (axis.x * axis.x) * c1 + c;
  5959. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5960. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5961. result.m[3] = 0.0;
  5962. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5963. result.m[5] = (axis.y * axis.y) * c1 + c;
  5964. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5965. result.m[7] = 0.0;
  5966. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5967. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5968. result.m[10] = (axis.z * axis.z) * c1 + c;
  5969. result.m[11] = 0.0;
  5970. result.m[15] = 1.0;
  5971. result._markAsUpdated();
  5972. };
  5973. /**
  5974. * Creates a rotation matrix
  5975. * @param yaw defines the yaw angle in radians (Y axis)
  5976. * @param pitch defines the pitch angle in radians (X axis)
  5977. * @param roll defines the roll angle in radians (X axis)
  5978. * @returns the new rotation matrix
  5979. */
  5980. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5981. var result = new Matrix();
  5982. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5983. return result;
  5984. };
  5985. /**
  5986. * Creates a rotation matrix and stores it in a given matrix
  5987. * @param yaw defines the yaw angle in radians (Y axis)
  5988. * @param pitch defines the pitch angle in radians (X axis)
  5989. * @param roll defines the roll angle in radians (X axis)
  5990. * @param result defines the target matrix
  5991. */
  5992. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5993. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5994. this._tempQuaternion.toRotationMatrix(result);
  5995. };
  5996. /**
  5997. * Creates a scaling matrix
  5998. * @param x defines the scale factor on X axis
  5999. * @param y defines the scale factor on Y axis
  6000. * @param z defines the scale factor on Z axis
  6001. * @returns the new matrix
  6002. */
  6003. Matrix.Scaling = function (x, y, z) {
  6004. var result = Matrix.Zero();
  6005. Matrix.ScalingToRef(x, y, z, result);
  6006. return result;
  6007. };
  6008. /**
  6009. * Creates a scaling matrix and stores it in a given matrix
  6010. * @param x defines the scale factor on X axis
  6011. * @param y defines the scale factor on Y axis
  6012. * @param z defines the scale factor on Z axis
  6013. * @param result defines the target matrix
  6014. */
  6015. Matrix.ScalingToRef = function (x, y, z, result) {
  6016. result.m[0] = x;
  6017. result.m[1] = 0.0;
  6018. result.m[2] = 0.0;
  6019. result.m[3] = 0.0;
  6020. result.m[4] = 0.0;
  6021. result.m[5] = y;
  6022. result.m[6] = 0.0;
  6023. result.m[7] = 0.0;
  6024. result.m[8] = 0.0;
  6025. result.m[9] = 0.0;
  6026. result.m[10] = z;
  6027. result.m[11] = 0.0;
  6028. result.m[12] = 0.0;
  6029. result.m[13] = 0.0;
  6030. result.m[14] = 0.0;
  6031. result.m[15] = 1.0;
  6032. result._markAsUpdated();
  6033. };
  6034. /**
  6035. * Creates a translation matrix
  6036. * @param x defines the translation on X axis
  6037. * @param y defines the translation on Y axis
  6038. * @param z defines the translationon Z axis
  6039. * @returns the new matrix
  6040. */
  6041. Matrix.Translation = function (x, y, z) {
  6042. var result = Matrix.Identity();
  6043. Matrix.TranslationToRef(x, y, z, result);
  6044. return result;
  6045. };
  6046. /**
  6047. * Creates a translation matrix and stores it in a given matrix
  6048. * @param x defines the translation on X axis
  6049. * @param y defines the translation on Y axis
  6050. * @param z defines the translationon Z axis
  6051. * @param result defines the target matrix
  6052. */
  6053. Matrix.TranslationToRef = function (x, y, z, result) {
  6054. 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);
  6055. };
  6056. /**
  6057. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6058. * @param startValue defines the start value
  6059. * @param endValue defines the end value
  6060. * @param gradient defines the gradient factor
  6061. * @returns the new matrix
  6062. */
  6063. Matrix.Lerp = function (startValue, endValue, gradient) {
  6064. var result = Matrix.Zero();
  6065. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6066. return result;
  6067. };
  6068. /**
  6069. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6070. * @param startValue defines the start value
  6071. * @param endValue defines the end value
  6072. * @param gradient defines the gradient factor
  6073. * @param result defines the Matrix object where to store data
  6074. */
  6075. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6076. for (var index = 0; index < 16; index++) {
  6077. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6078. }
  6079. result._markAsUpdated();
  6080. };
  6081. /**
  6082. * Builds a new matrix whose values are computed by:
  6083. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6084. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6085. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6086. * @param startValue defines the first matrix
  6087. * @param endValue defines the second matrix
  6088. * @param gradient defines the gradient between the two matrices
  6089. * @returns the new matrix
  6090. */
  6091. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6092. var result = Matrix.Zero();
  6093. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6094. return result;
  6095. };
  6096. /**
  6097. * Update a matrix to values which are computed by:
  6098. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6099. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6100. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6101. * @param startValue defines the first matrix
  6102. * @param endValue defines the second matrix
  6103. * @param gradient defines the gradient between the two matrices
  6104. * @param result defines the target matrix
  6105. */
  6106. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6107. var startScale = MathTmp.Vector3[0];
  6108. var startRotation = MathTmp.Quaternion[0];
  6109. var startTranslation = MathTmp.Vector3[1];
  6110. startValue.decompose(startScale, startRotation, startTranslation);
  6111. var endScale = MathTmp.Vector3[2];
  6112. var endRotation = MathTmp.Quaternion[1];
  6113. var endTranslation = MathTmp.Vector3[3];
  6114. endValue.decompose(endScale, endRotation, endTranslation);
  6115. var resultScale = MathTmp.Vector3[4];
  6116. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6117. var resultRotation = MathTmp.Quaternion[2];
  6118. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6119. var resultTranslation = MathTmp.Vector3[5];
  6120. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6121. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6122. };
  6123. /**
  6124. * 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"
  6125. * This function works in left handed mode
  6126. * @param eye defines the final position of the entity
  6127. * @param target defines where the entity should look at
  6128. * @param up defines the up vector for the entity
  6129. * @returns the new matrix
  6130. */
  6131. Matrix.LookAtLH = function (eye, target, up) {
  6132. var result = Matrix.Zero();
  6133. Matrix.LookAtLHToRef(eye, target, up, result);
  6134. return result;
  6135. };
  6136. /**
  6137. * 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".
  6138. * This function works in left handed mode
  6139. * @param eye defines the final position of the entity
  6140. * @param target defines where the entity should look at
  6141. * @param up defines the up vector for the entity
  6142. * @param result defines the target matrix
  6143. */
  6144. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6145. // Z axis
  6146. target.subtractToRef(eye, this._zAxis);
  6147. this._zAxis.normalize();
  6148. // X axis
  6149. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6150. if (this._xAxis.lengthSquared() === 0) {
  6151. this._xAxis.x = 1.0;
  6152. }
  6153. else {
  6154. this._xAxis.normalize();
  6155. }
  6156. // Y axis
  6157. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6158. this._yAxis.normalize();
  6159. // Eye angles
  6160. var ex = -Vector3.Dot(this._xAxis, eye);
  6161. var ey = -Vector3.Dot(this._yAxis, eye);
  6162. var ez = -Vector3.Dot(this._zAxis, eye);
  6163. 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);
  6164. };
  6165. /**
  6166. * 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"
  6167. * This function works in right handed mode
  6168. * @param eye defines the final position of the entity
  6169. * @param target defines where the entity should look at
  6170. * @param up defines the up vector for the entity
  6171. * @returns the new matrix
  6172. */
  6173. Matrix.LookAtRH = function (eye, target, up) {
  6174. var result = Matrix.Zero();
  6175. Matrix.LookAtRHToRef(eye, target, up, result);
  6176. return result;
  6177. };
  6178. /**
  6179. * 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".
  6180. * This function works in right handed mode
  6181. * @param eye defines the final position of the entity
  6182. * @param target defines where the entity should look at
  6183. * @param up defines the up vector for the entity
  6184. * @param result defines the target matrix
  6185. */
  6186. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6187. // Z axis
  6188. eye.subtractToRef(target, this._zAxis);
  6189. this._zAxis.normalize();
  6190. // X axis
  6191. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6192. if (this._xAxis.lengthSquared() === 0) {
  6193. this._xAxis.x = 1.0;
  6194. }
  6195. else {
  6196. this._xAxis.normalize();
  6197. }
  6198. // Y axis
  6199. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6200. this._yAxis.normalize();
  6201. // Eye angles
  6202. var ex = -Vector3.Dot(this._xAxis, eye);
  6203. var ey = -Vector3.Dot(this._yAxis, eye);
  6204. var ez = -Vector3.Dot(this._zAxis, eye);
  6205. 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);
  6206. };
  6207. /**
  6208. * Create a left-handed orthographic projection matrix
  6209. * @param width defines the viewport width
  6210. * @param height defines the viewport height
  6211. * @param znear defines the near clip plane
  6212. * @param zfar defines the far clip plane
  6213. * @returns a new matrix as a left-handed orthographic projection matrix
  6214. */
  6215. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6216. var matrix = Matrix.Zero();
  6217. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6218. return matrix;
  6219. };
  6220. /**
  6221. * Store a left-handed orthographic projection to a given matrix
  6222. * @param width defines the viewport width
  6223. * @param height defines the viewport height
  6224. * @param znear defines the near clip plane
  6225. * @param zfar defines the far clip plane
  6226. * @param result defines the target matrix
  6227. */
  6228. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6229. var n = znear;
  6230. var f = zfar;
  6231. var a = 2.0 / width;
  6232. var b = 2.0 / height;
  6233. var c = 2.0 / (f - n);
  6234. var d = -(f + n) / (f - n);
  6235. 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);
  6236. };
  6237. /**
  6238. * Create a left-handed orthographic projection matrix
  6239. * @param left defines the viewport left coordinate
  6240. * @param right defines the viewport right coordinate
  6241. * @param bottom defines the viewport bottom coordinate
  6242. * @param top defines the viewport top coordinate
  6243. * @param znear defines the near clip plane
  6244. * @param zfar defines the far clip plane
  6245. * @returns a new matrix as a left-handed orthographic projection matrix
  6246. */
  6247. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6248. var matrix = Matrix.Zero();
  6249. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6250. return matrix;
  6251. };
  6252. /**
  6253. * Stores a left-handed orthographic projection into a given matrix
  6254. * @param left defines the viewport left coordinate
  6255. * @param right defines the viewport right coordinate
  6256. * @param bottom defines the viewport bottom coordinate
  6257. * @param top defines the viewport top coordinate
  6258. * @param znear defines the near clip plane
  6259. * @param zfar defines the far clip plane
  6260. * @param result defines the target matrix
  6261. */
  6262. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6263. var n = znear;
  6264. var f = zfar;
  6265. var a = 2.0 / (right - left);
  6266. var b = 2.0 / (top - bottom);
  6267. var c = 2.0 / (f - n);
  6268. var d = -(f + n) / (f - n);
  6269. var i0 = (left + right) / (left - right);
  6270. var i1 = (top + bottom) / (bottom - top);
  6271. 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);
  6272. };
  6273. /**
  6274. * Creates a right-handed orthographic projection matrix
  6275. * @param left defines the viewport left coordinate
  6276. * @param right defines the viewport right coordinate
  6277. * @param bottom defines the viewport bottom coordinate
  6278. * @param top defines the viewport top coordinate
  6279. * @param znear defines the near clip plane
  6280. * @param zfar defines the far clip plane
  6281. * @returns a new matrix as a right-handed orthographic projection matrix
  6282. */
  6283. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6284. var matrix = Matrix.Zero();
  6285. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6286. return matrix;
  6287. };
  6288. /**
  6289. * Stores a right-handed orthographic projection into a given matrix
  6290. * @param left defines the viewport left coordinate
  6291. * @param right defines the viewport right coordinate
  6292. * @param bottom defines the viewport bottom coordinate
  6293. * @param top defines the viewport top coordinate
  6294. * @param znear defines the near clip plane
  6295. * @param zfar defines the far clip plane
  6296. * @param result defines the target matrix
  6297. */
  6298. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6299. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6300. result.m[10] *= -1.0;
  6301. };
  6302. /**
  6303. * Creates a left-handed perspective projection matrix
  6304. * @param width defines the viewport width
  6305. * @param height defines the viewport height
  6306. * @param znear defines the near clip plane
  6307. * @param zfar defines the far clip plane
  6308. * @returns a new matrix as a left-handed perspective projection matrix
  6309. */
  6310. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6311. var matrix = Matrix.Zero();
  6312. var n = znear;
  6313. var f = zfar;
  6314. var a = 2.0 * n / width;
  6315. var b = 2.0 * n / height;
  6316. var c = (f + n) / (f - n);
  6317. var d = -2.0 * f * n / (f - n);
  6318. 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);
  6319. return matrix;
  6320. };
  6321. /**
  6322. * Creates a left-handed perspective projection matrix
  6323. * @param fov defines the horizontal field of view
  6324. * @param aspect defines the aspect ratio
  6325. * @param znear defines the near clip plane
  6326. * @param zfar defines the far clip plane
  6327. * @returns a new matrix as a left-handed perspective projection matrix
  6328. */
  6329. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6330. var matrix = Matrix.Zero();
  6331. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6332. return matrix;
  6333. };
  6334. /**
  6335. * Stores a left-handed perspective projection into a given matrix
  6336. * @param fov defines the horizontal field of view
  6337. * @param aspect defines the aspect ratio
  6338. * @param znear defines the near clip plane
  6339. * @param zfar defines the far clip plane
  6340. * @param result defines the target matrix
  6341. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6342. */
  6343. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6344. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6345. var n = znear;
  6346. var f = zfar;
  6347. var t = 1.0 / (Math.tan(fov * 0.5));
  6348. var a = isVerticalFovFixed ? (t / aspect) : t;
  6349. var b = isVerticalFovFixed ? t : (t * aspect);
  6350. var c = (f + n) / (f - n);
  6351. var d = -2.0 * f * n / (f - n);
  6352. 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);
  6353. };
  6354. /**
  6355. * Creates a right-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 right-handed perspective projection matrix
  6361. */
  6362. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6363. var matrix = Matrix.Zero();
  6364. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6365. return matrix;
  6366. };
  6367. /**
  6368. * Stores a right-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.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6377. //alternatively this could be expressed as:
  6378. // m = PerspectiveFovLHToRef
  6379. // m[10] *= -1.0;
  6380. // m[11] *= -1.0;
  6381. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6382. var n = znear;
  6383. var f = zfar;
  6384. var t = 1.0 / (Math.tan(fov * 0.5));
  6385. var a = isVerticalFovFixed ? (t / aspect) : t;
  6386. var b = isVerticalFovFixed ? t : (t * aspect);
  6387. var c = -(f + n) / (f - n);
  6388. var d = -2 * f * n / (f - n);
  6389. 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);
  6390. };
  6391. /**
  6392. * Stores a perspective projection for WebVR info a given matrix
  6393. * @param fov defines the field of view
  6394. * @param znear defines the near clip plane
  6395. * @param zfar defines the far clip plane
  6396. * @param result defines the target matrix
  6397. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6398. */
  6399. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6400. if (rightHanded === void 0) { rightHanded = false; }
  6401. var rightHandedFactor = rightHanded ? -1 : 1;
  6402. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6403. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6404. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6405. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6406. var xScale = 2.0 / (leftTan + rightTan);
  6407. var yScale = 2.0 / (upTan + downTan);
  6408. result.m[0] = xScale;
  6409. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6410. result.m[5] = yScale;
  6411. result.m[6] = result.m[7] = 0.0;
  6412. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6413. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6414. result.m[10] = -zfar / (znear - zfar);
  6415. result.m[11] = 1.0 * rightHandedFactor;
  6416. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6417. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6418. result._markAsUpdated();
  6419. };
  6420. /**
  6421. * Computes a complete transformation matrix
  6422. * @param viewport defines the viewport to use
  6423. * @param world defines the world matrix
  6424. * @param view defines the view matrix
  6425. * @param projection defines the projection matrix
  6426. * @param zmin defines the near clip plane
  6427. * @param zmax defines the far clip plane
  6428. * @returns the transformation matrix
  6429. */
  6430. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6431. var cw = viewport.width;
  6432. var ch = viewport.height;
  6433. var cx = viewport.x;
  6434. var cy = viewport.y;
  6435. 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);
  6436. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6437. };
  6438. /**
  6439. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6440. * @param matrix defines the matrix to use
  6441. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6442. */
  6443. Matrix.GetAsMatrix2x2 = function (matrix) {
  6444. return new Float32Array([
  6445. matrix.m[0], matrix.m[1],
  6446. matrix.m[4], matrix.m[5]
  6447. ]);
  6448. };
  6449. /**
  6450. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6451. * @param matrix defines the matrix to use
  6452. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6453. */
  6454. Matrix.GetAsMatrix3x3 = function (matrix) {
  6455. return new Float32Array([
  6456. matrix.m[0], matrix.m[1], matrix.m[2],
  6457. matrix.m[4], matrix.m[5], matrix.m[6],
  6458. matrix.m[8], matrix.m[9], matrix.m[10]
  6459. ]);
  6460. };
  6461. /**
  6462. * Compute the transpose of a given matrix
  6463. * @param matrix defines the matrix to transpose
  6464. * @returns the new matrix
  6465. */
  6466. Matrix.Transpose = function (matrix) {
  6467. var result = new Matrix();
  6468. Matrix.TransposeToRef(matrix, result);
  6469. return result;
  6470. };
  6471. /**
  6472. * Compute the transpose of a matrix and store it in a target matrix
  6473. * @param matrix defines the matrix to transpose
  6474. * @param result defines the target matrix
  6475. */
  6476. Matrix.TransposeToRef = function (matrix, result) {
  6477. result.m[0] = matrix.m[0];
  6478. result.m[1] = matrix.m[4];
  6479. result.m[2] = matrix.m[8];
  6480. result.m[3] = matrix.m[12];
  6481. result.m[4] = matrix.m[1];
  6482. result.m[5] = matrix.m[5];
  6483. result.m[6] = matrix.m[9];
  6484. result.m[7] = matrix.m[13];
  6485. result.m[8] = matrix.m[2];
  6486. result.m[9] = matrix.m[6];
  6487. result.m[10] = matrix.m[10];
  6488. result.m[11] = matrix.m[14];
  6489. result.m[12] = matrix.m[3];
  6490. result.m[13] = matrix.m[7];
  6491. result.m[14] = matrix.m[11];
  6492. result.m[15] = matrix.m[15];
  6493. };
  6494. /**
  6495. * Computes a reflection matrix from a plane
  6496. * @param plane defines the reflection plane
  6497. * @returns a new matrix
  6498. */
  6499. Matrix.Reflection = function (plane) {
  6500. var matrix = new Matrix();
  6501. Matrix.ReflectionToRef(plane, matrix);
  6502. return matrix;
  6503. };
  6504. /**
  6505. * Computes a reflection matrix from a plane
  6506. * @param plane defines the reflection plane
  6507. * @param result defines the target matrix
  6508. */
  6509. Matrix.ReflectionToRef = function (plane, result) {
  6510. plane.normalize();
  6511. var x = plane.normal.x;
  6512. var y = plane.normal.y;
  6513. var z = plane.normal.z;
  6514. var temp = -2 * x;
  6515. var temp2 = -2 * y;
  6516. var temp3 = -2 * z;
  6517. result.m[0] = (temp * x) + 1;
  6518. result.m[1] = temp2 * x;
  6519. result.m[2] = temp3 * x;
  6520. result.m[3] = 0.0;
  6521. result.m[4] = temp * y;
  6522. result.m[5] = (temp2 * y) + 1;
  6523. result.m[6] = temp3 * y;
  6524. result.m[7] = 0.0;
  6525. result.m[8] = temp * z;
  6526. result.m[9] = temp2 * z;
  6527. result.m[10] = (temp3 * z) + 1;
  6528. result.m[11] = 0.0;
  6529. result.m[12] = temp * plane.d;
  6530. result.m[13] = temp2 * plane.d;
  6531. result.m[14] = temp3 * plane.d;
  6532. result.m[15] = 1.0;
  6533. result._markAsUpdated();
  6534. };
  6535. /**
  6536. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6537. * @param xaxis defines the value of the 1st axis
  6538. * @param yaxis defines the value of the 2nd axis
  6539. * @param zaxis defines the value of the 3rd axis
  6540. * @param result defines the target matrix
  6541. */
  6542. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6543. result.m[0] = xaxis.x;
  6544. result.m[1] = xaxis.y;
  6545. result.m[2] = xaxis.z;
  6546. result.m[3] = 0.0;
  6547. result.m[4] = yaxis.x;
  6548. result.m[5] = yaxis.y;
  6549. result.m[6] = yaxis.z;
  6550. result.m[7] = 0.0;
  6551. result.m[8] = zaxis.x;
  6552. result.m[9] = zaxis.y;
  6553. result.m[10] = zaxis.z;
  6554. result.m[11] = 0.0;
  6555. result.m[12] = 0.0;
  6556. result.m[13] = 0.0;
  6557. result.m[14] = 0.0;
  6558. result.m[15] = 1.0;
  6559. result._markAsUpdated();
  6560. };
  6561. /**
  6562. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6563. * @param quat defines the quaternion to use
  6564. * @param result defines the target matrix
  6565. */
  6566. Matrix.FromQuaternionToRef = function (quat, result) {
  6567. var xx = quat.x * quat.x;
  6568. var yy = quat.y * quat.y;
  6569. var zz = quat.z * quat.z;
  6570. var xy = quat.x * quat.y;
  6571. var zw = quat.z * quat.w;
  6572. var zx = quat.z * quat.x;
  6573. var yw = quat.y * quat.w;
  6574. var yz = quat.y * quat.z;
  6575. var xw = quat.x * quat.w;
  6576. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6577. result.m[1] = 2.0 * (xy + zw);
  6578. result.m[2] = 2.0 * (zx - yw);
  6579. result.m[3] = 0.0;
  6580. result.m[4] = 2.0 * (xy - zw);
  6581. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6582. result.m[6] = 2.0 * (yz + xw);
  6583. result.m[7] = 0.0;
  6584. result.m[8] = 2.0 * (zx + yw);
  6585. result.m[9] = 2.0 * (yz - xw);
  6586. result.m[10] = 1.0 - (2.0 * (yy + xx));
  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. Matrix._tempQuaternion = new Quaternion();
  6595. Matrix._xAxis = Vector3.Zero();
  6596. Matrix._yAxis = Vector3.Zero();
  6597. Matrix._zAxis = Vector3.Zero();
  6598. Matrix._updateFlagSeed = 0;
  6599. Matrix._identityReadOnly = Matrix.Identity();
  6600. return Matrix;
  6601. }());
  6602. BABYLON.Matrix = Matrix;
  6603. var Plane = /** @class */ (function () {
  6604. /**
  6605. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6606. */
  6607. function Plane(a, b, c, d) {
  6608. this.normal = new Vector3(a, b, c);
  6609. this.d = d;
  6610. }
  6611. /**
  6612. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6613. */
  6614. Plane.prototype.asArray = function () {
  6615. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6616. };
  6617. // Methods
  6618. /**
  6619. * Returns a new plane copied from the current Plane.
  6620. */
  6621. Plane.prototype.clone = function () {
  6622. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6623. };
  6624. /**
  6625. * Returns the string "Plane".
  6626. */
  6627. Plane.prototype.getClassName = function () {
  6628. return "Plane";
  6629. };
  6630. /**
  6631. * Returns the Plane hash code.
  6632. */
  6633. Plane.prototype.getHashCode = function () {
  6634. var hash = this.normal.getHashCode();
  6635. hash = (hash * 397) ^ (this.d || 0);
  6636. return hash;
  6637. };
  6638. /**
  6639. * Normalize the current Plane in place.
  6640. * Returns the updated Plane.
  6641. */
  6642. Plane.prototype.normalize = function () {
  6643. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6644. var magnitude = 0.0;
  6645. if (norm !== 0) {
  6646. magnitude = 1.0 / norm;
  6647. }
  6648. this.normal.x *= magnitude;
  6649. this.normal.y *= magnitude;
  6650. this.normal.z *= magnitude;
  6651. this.d *= magnitude;
  6652. return this;
  6653. };
  6654. /**
  6655. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6656. */
  6657. Plane.prototype.transform = function (transformation) {
  6658. var transposedMatrix = Matrix.Transpose(transformation);
  6659. var x = this.normal.x;
  6660. var y = this.normal.y;
  6661. var z = this.normal.z;
  6662. var d = this.d;
  6663. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6664. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6665. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6666. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6667. return new Plane(normalX, normalY, normalZ, finalD);
  6668. };
  6669. /**
  6670. * Returns the dot product (float) of the point coordinates and the plane normal.
  6671. */
  6672. Plane.prototype.dotCoordinate = function (point) {
  6673. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6674. };
  6675. /**
  6676. * Updates the current Plane from the plane defined by the three given points.
  6677. * Returns the updated Plane.
  6678. */
  6679. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6680. var x1 = point2.x - point1.x;
  6681. var y1 = point2.y - point1.y;
  6682. var z1 = point2.z - point1.z;
  6683. var x2 = point3.x - point1.x;
  6684. var y2 = point3.y - point1.y;
  6685. var z2 = point3.z - point1.z;
  6686. var yz = (y1 * z2) - (z1 * y2);
  6687. var xz = (z1 * x2) - (x1 * z2);
  6688. var xy = (x1 * y2) - (y1 * x2);
  6689. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6690. var invPyth;
  6691. if (pyth !== 0) {
  6692. invPyth = 1.0 / pyth;
  6693. }
  6694. else {
  6695. invPyth = 0.0;
  6696. }
  6697. this.normal.x = yz * invPyth;
  6698. this.normal.y = xz * invPyth;
  6699. this.normal.z = xy * invPyth;
  6700. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6701. return this;
  6702. };
  6703. /**
  6704. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6705. */
  6706. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6707. var dot = Vector3.Dot(this.normal, direction);
  6708. return (dot <= epsilon);
  6709. };
  6710. /**
  6711. * Returns the signed distance (float) from the given point to the Plane.
  6712. */
  6713. Plane.prototype.signedDistanceTo = function (point) {
  6714. return Vector3.Dot(point, this.normal) + this.d;
  6715. };
  6716. // Statics
  6717. /**
  6718. * Returns a new Plane from the given array.
  6719. */
  6720. Plane.FromArray = function (array) {
  6721. return new Plane(array[0], array[1], array[2], array[3]);
  6722. };
  6723. /**
  6724. * Returns a new Plane defined by the three given points.
  6725. */
  6726. Plane.FromPoints = function (point1, point2, point3) {
  6727. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6728. result.copyFromPoints(point1, point2, point3);
  6729. return result;
  6730. };
  6731. /**
  6732. * Returns a new Plane the normal vector to this plane at the given origin point.
  6733. * Note : the vector "normal" is updated because normalized.
  6734. */
  6735. Plane.FromPositionAndNormal = function (origin, normal) {
  6736. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6737. normal.normalize();
  6738. result.normal = normal;
  6739. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6740. return result;
  6741. };
  6742. /**
  6743. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6744. */
  6745. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6746. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6747. return Vector3.Dot(point, normal) + d;
  6748. };
  6749. return Plane;
  6750. }());
  6751. BABYLON.Plane = Plane;
  6752. var Viewport = /** @class */ (function () {
  6753. /**
  6754. * Creates a Viewport object located at (x, y) and sized (width, height).
  6755. */
  6756. function Viewport(x, y, width, height) {
  6757. this.x = x;
  6758. this.y = y;
  6759. this.width = width;
  6760. this.height = height;
  6761. }
  6762. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6763. if (renderWidthOrEngine.getRenderWidth) {
  6764. var engine = renderWidthOrEngine;
  6765. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6766. }
  6767. var renderWidth = renderWidthOrEngine;
  6768. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6769. };
  6770. /**
  6771. * Returns a new Viewport copied from the current one.
  6772. */
  6773. Viewport.prototype.clone = function () {
  6774. return new Viewport(this.x, this.y, this.width, this.height);
  6775. };
  6776. return Viewport;
  6777. }());
  6778. BABYLON.Viewport = Viewport;
  6779. var Frustum = /** @class */ (function () {
  6780. function Frustum() {
  6781. }
  6782. /**
  6783. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6784. */
  6785. Frustum.GetPlanes = function (transform) {
  6786. var frustumPlanes = [];
  6787. for (var index = 0; index < 6; index++) {
  6788. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6789. }
  6790. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6791. return frustumPlanes;
  6792. };
  6793. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6794. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6795. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6796. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6797. frustumPlane.d = transform.m[15] + transform.m[14];
  6798. frustumPlane.normalize();
  6799. };
  6800. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6801. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6802. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6803. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6804. frustumPlane.d = transform.m[15] - transform.m[14];
  6805. frustumPlane.normalize();
  6806. };
  6807. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6808. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6809. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6810. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6811. frustumPlane.d = transform.m[15] + transform.m[12];
  6812. frustumPlane.normalize();
  6813. };
  6814. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6815. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6816. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6817. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6818. frustumPlane.d = transform.m[15] - transform.m[12];
  6819. frustumPlane.normalize();
  6820. };
  6821. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6822. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6823. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6824. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6825. frustumPlane.d = transform.m[15] - transform.m[13];
  6826. frustumPlane.normalize();
  6827. };
  6828. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6829. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6830. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6831. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6832. frustumPlane.d = transform.m[15] + transform.m[13];
  6833. frustumPlane.normalize();
  6834. };
  6835. /**
  6836. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6837. */
  6838. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6839. // Near
  6840. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6841. // Far
  6842. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6843. // Left
  6844. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6845. // Right
  6846. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6847. // Top
  6848. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6849. // Bottom
  6850. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6851. };
  6852. return Frustum;
  6853. }());
  6854. BABYLON.Frustum = Frustum;
  6855. /** Defines supported spaces */
  6856. var Space;
  6857. (function (Space) {
  6858. /** Local (object) space */
  6859. Space[Space["LOCAL"] = 0] = "LOCAL";
  6860. /** World space */
  6861. Space[Space["WORLD"] = 1] = "WORLD";
  6862. /** Bone space */
  6863. Space[Space["BONE"] = 2] = "BONE";
  6864. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6865. /** Defines the 3 main axes */
  6866. var Axis = /** @class */ (function () {
  6867. function Axis() {
  6868. }
  6869. /** X axis */
  6870. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6871. /** Y axis */
  6872. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6873. /** Z axis */
  6874. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6875. return Axis;
  6876. }());
  6877. BABYLON.Axis = Axis;
  6878. ;
  6879. var BezierCurve = /** @class */ (function () {
  6880. function BezierCurve() {
  6881. }
  6882. /**
  6883. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6884. */
  6885. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6886. // Extract X (which is equal to time here)
  6887. var f0 = 1 - 3 * x2 + 3 * x1;
  6888. var f1 = 3 * x2 - 6 * x1;
  6889. var f2 = 3 * x1;
  6890. var refinedT = t;
  6891. for (var i = 0; i < 5; i++) {
  6892. var refinedT2 = refinedT * refinedT;
  6893. var refinedT3 = refinedT2 * refinedT;
  6894. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6895. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6896. refinedT -= (x - t) * slope;
  6897. refinedT = Math.min(1, Math.max(0, refinedT));
  6898. }
  6899. // Resolve cubic bezier for the given x
  6900. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6901. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6902. Math.pow(refinedT, 3);
  6903. };
  6904. return BezierCurve;
  6905. }());
  6906. BABYLON.BezierCurve = BezierCurve;
  6907. /**
  6908. * Defines potential orientation for back face culling
  6909. */
  6910. var Orientation;
  6911. (function (Orientation) {
  6912. /**
  6913. * Clockwise
  6914. */
  6915. Orientation[Orientation["CW"] = 0] = "CW";
  6916. /** Counter clockwise */
  6917. Orientation[Orientation["CCW"] = 1] = "CCW";
  6918. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6919. /**
  6920. * Defines angle representation
  6921. */
  6922. var Angle = /** @class */ (function () {
  6923. /**
  6924. * Creates an Angle object of "radians" radians (float).
  6925. */
  6926. function Angle(radians) {
  6927. this._radians = radians;
  6928. if (this._radians < 0.0)
  6929. this._radians += (2.0 * Math.PI);
  6930. }
  6931. /**
  6932. * Get value in degrees
  6933. * @returns the Angle value in degrees (float)
  6934. */
  6935. Angle.prototype.degrees = function () {
  6936. return this._radians * 180.0 / Math.PI;
  6937. };
  6938. /**
  6939. * Get value in radians
  6940. * @returns the Angle value in radians (float)
  6941. */
  6942. Angle.prototype.radians = function () {
  6943. return this._radians;
  6944. };
  6945. /**
  6946. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6947. * @param a defines first vector
  6948. * @param b defines second vector
  6949. * @returns a new Angle
  6950. */
  6951. Angle.BetweenTwoPoints = function (a, b) {
  6952. var delta = b.subtract(a);
  6953. var theta = Math.atan2(delta.y, delta.x);
  6954. return new Angle(theta);
  6955. };
  6956. /**
  6957. * Gets a new Angle object from the given float in radians
  6958. * @param radians defines the angle value in radians
  6959. * @returns a new Angle
  6960. */
  6961. Angle.FromRadians = function (radians) {
  6962. return new Angle(radians);
  6963. };
  6964. /**
  6965. * Gets a new Angle object from the given float in degrees
  6966. * @param degrees defines the angle value in degrees
  6967. * @returns a new Angle
  6968. */
  6969. Angle.FromDegrees = function (degrees) {
  6970. return new Angle(degrees * Math.PI / 180.0);
  6971. };
  6972. return Angle;
  6973. }());
  6974. BABYLON.Angle = Angle;
  6975. var Arc2 = /** @class */ (function () {
  6976. /**
  6977. * Creates an Arc object from the three given points : start, middle and end.
  6978. */
  6979. function Arc2(startPoint, midPoint, endPoint) {
  6980. this.startPoint = startPoint;
  6981. this.midPoint = midPoint;
  6982. this.endPoint = endPoint;
  6983. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6984. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6985. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6986. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6987. 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);
  6988. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6989. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6990. var a1 = this.startAngle.degrees();
  6991. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6992. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6993. // angles correction
  6994. if (a2 - a1 > +180.0)
  6995. a2 -= 360.0;
  6996. if (a2 - a1 < -180.0)
  6997. a2 += 360.0;
  6998. if (a3 - a2 > +180.0)
  6999. a3 -= 360.0;
  7000. if (a3 - a2 < -180.0)
  7001. a3 += 360.0;
  7002. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7003. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7004. }
  7005. return Arc2;
  7006. }());
  7007. BABYLON.Arc2 = Arc2;
  7008. var Path2 = /** @class */ (function () {
  7009. /**
  7010. * Creates a Path2 object from the starting 2D coordinates x and y.
  7011. */
  7012. function Path2(x, y) {
  7013. this._points = new Array();
  7014. this._length = 0.0;
  7015. this.closed = false;
  7016. this._points.push(new Vector2(x, y));
  7017. }
  7018. /**
  7019. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7020. * Returns the updated Path2.
  7021. */
  7022. Path2.prototype.addLineTo = function (x, y) {
  7023. if (this.closed) {
  7024. return this;
  7025. }
  7026. var newPoint = new Vector2(x, y);
  7027. var previousPoint = this._points[this._points.length - 1];
  7028. this._points.push(newPoint);
  7029. this._length += newPoint.subtract(previousPoint).length();
  7030. return this;
  7031. };
  7032. /**
  7033. * 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.
  7034. * Returns the updated Path2.
  7035. */
  7036. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7037. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7038. if (this.closed) {
  7039. return this;
  7040. }
  7041. var startPoint = this._points[this._points.length - 1];
  7042. var midPoint = new Vector2(midX, midY);
  7043. var endPoint = new Vector2(endX, endY);
  7044. var arc = new Arc2(startPoint, midPoint, endPoint);
  7045. var increment = arc.angle.radians() / numberOfSegments;
  7046. if (arc.orientation === Orientation.CW)
  7047. increment *= -1;
  7048. var currentAngle = arc.startAngle.radians() + increment;
  7049. for (var i = 0; i < numberOfSegments; i++) {
  7050. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7051. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7052. this.addLineTo(x, y);
  7053. currentAngle += increment;
  7054. }
  7055. return this;
  7056. };
  7057. /**
  7058. * Closes the Path2.
  7059. * Returns the Path2.
  7060. */
  7061. Path2.prototype.close = function () {
  7062. this.closed = true;
  7063. return this;
  7064. };
  7065. /**
  7066. * Returns the Path2 total length (float).
  7067. */
  7068. Path2.prototype.length = function () {
  7069. var result = this._length;
  7070. if (!this.closed) {
  7071. var lastPoint = this._points[this._points.length - 1];
  7072. var firstPoint = this._points[0];
  7073. result += (firstPoint.subtract(lastPoint).length());
  7074. }
  7075. return result;
  7076. };
  7077. /**
  7078. * Returns the Path2 internal array of points.
  7079. */
  7080. Path2.prototype.getPoints = function () {
  7081. return this._points;
  7082. };
  7083. /**
  7084. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7085. */
  7086. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7087. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7088. return Vector2.Zero();
  7089. }
  7090. var lengthPosition = normalizedLengthPosition * this.length();
  7091. var previousOffset = 0;
  7092. for (var i = 0; i < this._points.length; i++) {
  7093. var j = (i + 1) % this._points.length;
  7094. var a = this._points[i];
  7095. var b = this._points[j];
  7096. var bToA = b.subtract(a);
  7097. var nextOffset = (bToA.length() + previousOffset);
  7098. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7099. var dir = bToA.normalize();
  7100. var localOffset = lengthPosition - previousOffset;
  7101. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7102. }
  7103. previousOffset = nextOffset;
  7104. }
  7105. return Vector2.Zero();
  7106. };
  7107. /**
  7108. * Returns a new Path2 starting at the coordinates (x, y).
  7109. */
  7110. Path2.StartingAt = function (x, y) {
  7111. return new Path2(x, y);
  7112. };
  7113. return Path2;
  7114. }());
  7115. BABYLON.Path2 = Path2;
  7116. var Path3D = /** @class */ (function () {
  7117. /**
  7118. * new Path3D(path, normal, raw)
  7119. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7120. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7121. * path : an array of Vector3, the curve axis of the Path3D
  7122. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7123. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7124. */
  7125. function Path3D(path, firstNormal, raw) {
  7126. if (firstNormal === void 0) { firstNormal = null; }
  7127. this.path = path;
  7128. this._curve = new Array();
  7129. this._distances = new Array();
  7130. this._tangents = new Array();
  7131. this._normals = new Array();
  7132. this._binormals = new Array();
  7133. for (var p = 0; p < path.length; p++) {
  7134. this._curve[p] = path[p].clone(); // hard copy
  7135. }
  7136. this._raw = raw || false;
  7137. this._compute(firstNormal);
  7138. }
  7139. /**
  7140. * Returns the Path3D array of successive Vector3 designing its curve.
  7141. */
  7142. Path3D.prototype.getCurve = function () {
  7143. return this._curve;
  7144. };
  7145. /**
  7146. * Returns an array populated with tangent vectors on each Path3D curve point.
  7147. */
  7148. Path3D.prototype.getTangents = function () {
  7149. return this._tangents;
  7150. };
  7151. /**
  7152. * Returns an array populated with normal vectors on each Path3D curve point.
  7153. */
  7154. Path3D.prototype.getNormals = function () {
  7155. return this._normals;
  7156. };
  7157. /**
  7158. * Returns an array populated with binormal vectors on each Path3D curve point.
  7159. */
  7160. Path3D.prototype.getBinormals = function () {
  7161. return this._binormals;
  7162. };
  7163. /**
  7164. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7165. */
  7166. Path3D.prototype.getDistances = function () {
  7167. return this._distances;
  7168. };
  7169. /**
  7170. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7171. * Returns the same object updated.
  7172. */
  7173. Path3D.prototype.update = function (path, firstNormal) {
  7174. if (firstNormal === void 0) { firstNormal = null; }
  7175. for (var p = 0; p < path.length; p++) {
  7176. this._curve[p].x = path[p].x;
  7177. this._curve[p].y = path[p].y;
  7178. this._curve[p].z = path[p].z;
  7179. }
  7180. this._compute(firstNormal);
  7181. return this;
  7182. };
  7183. // private function compute() : computes tangents, normals and binormals
  7184. Path3D.prototype._compute = function (firstNormal) {
  7185. var l = this._curve.length;
  7186. // first and last tangents
  7187. this._tangents[0] = this._getFirstNonNullVector(0);
  7188. if (!this._raw) {
  7189. this._tangents[0].normalize();
  7190. }
  7191. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7192. if (!this._raw) {
  7193. this._tangents[l - 1].normalize();
  7194. }
  7195. // normals and binormals at first point : arbitrary vector with _normalVector()
  7196. var tg0 = this._tangents[0];
  7197. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7198. this._normals[0] = pp0;
  7199. if (!this._raw) {
  7200. this._normals[0].normalize();
  7201. }
  7202. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7203. if (!this._raw) {
  7204. this._binormals[0].normalize();
  7205. }
  7206. this._distances[0] = 0.0;
  7207. // normals and binormals : next points
  7208. var prev; // previous vector (segment)
  7209. var cur; // current vector (segment)
  7210. var curTang; // current tangent
  7211. // previous normal
  7212. var prevBinor; // previous binormal
  7213. for (var i = 1; i < l; i++) {
  7214. // tangents
  7215. prev = this._getLastNonNullVector(i);
  7216. if (i < l - 1) {
  7217. cur = this._getFirstNonNullVector(i);
  7218. this._tangents[i] = prev.add(cur);
  7219. this._tangents[i].normalize();
  7220. }
  7221. this._distances[i] = this._distances[i - 1] + prev.length();
  7222. // normals and binormals
  7223. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7224. curTang = this._tangents[i];
  7225. prevBinor = this._binormals[i - 1];
  7226. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7227. if (!this._raw) {
  7228. this._normals[i].normalize();
  7229. }
  7230. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7231. if (!this._raw) {
  7232. this._binormals[i].normalize();
  7233. }
  7234. }
  7235. };
  7236. // private function getFirstNonNullVector(index)
  7237. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7238. Path3D.prototype._getFirstNonNullVector = function (index) {
  7239. var i = 1;
  7240. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7241. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7242. i++;
  7243. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7244. }
  7245. return nNVector;
  7246. };
  7247. // private function getLastNonNullVector(index)
  7248. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7249. Path3D.prototype._getLastNonNullVector = function (index) {
  7250. var i = 1;
  7251. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7252. while (nLVector.length() === 0 && index > i + 1) {
  7253. i++;
  7254. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7255. }
  7256. return nLVector;
  7257. };
  7258. // private function normalVector(v0, vt, va) :
  7259. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7260. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7261. Path3D.prototype._normalVector = function (v0, vt, va) {
  7262. var normal0;
  7263. var tgl = vt.length();
  7264. if (tgl === 0.0) {
  7265. tgl = 1.0;
  7266. }
  7267. if (va === undefined || va === null) {
  7268. var point;
  7269. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7270. point = new Vector3(0.0, -1.0, 0.0);
  7271. }
  7272. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7273. point = new Vector3(1.0, 0.0, 0.0);
  7274. }
  7275. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7276. point = new Vector3(0.0, 0.0, 1.0);
  7277. }
  7278. else {
  7279. point = Vector3.Zero();
  7280. }
  7281. normal0 = Vector3.Cross(vt, point);
  7282. }
  7283. else {
  7284. normal0 = Vector3.Cross(vt, va);
  7285. Vector3.CrossToRef(normal0, vt, normal0);
  7286. }
  7287. normal0.normalize();
  7288. return normal0;
  7289. };
  7290. return Path3D;
  7291. }());
  7292. BABYLON.Path3D = Path3D;
  7293. var Curve3 = /** @class */ (function () {
  7294. /**
  7295. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7296. * A Curve3 is designed from a series of successive Vector3.
  7297. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7298. */
  7299. function Curve3(points) {
  7300. this._length = 0.0;
  7301. this._points = points;
  7302. this._length = this._computeLength(points);
  7303. }
  7304. /**
  7305. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7306. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7307. * @param v1 (Vector3) the control point
  7308. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7309. * @param nbPoints (integer) the wanted number of points in the curve
  7310. */
  7311. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7312. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7313. var bez = new Array();
  7314. var equation = function (t, val0, val1, val2) {
  7315. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7316. return res;
  7317. };
  7318. for (var i = 0; i <= nbPoints; i++) {
  7319. 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)));
  7320. }
  7321. return new Curve3(bez);
  7322. };
  7323. /**
  7324. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7325. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7326. * @param v1 (Vector3) the first control point
  7327. * @param v2 (Vector3) the second control point
  7328. * @param v3 (Vector3) the end point of the Cubic Bezier
  7329. * @param nbPoints (integer) the wanted number of points in the curve
  7330. */
  7331. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7332. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7333. var bez = new Array();
  7334. var equation = function (t, val0, val1, val2, val3) {
  7335. 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;
  7336. return res;
  7337. };
  7338. for (var i = 0; i <= nbPoints; i++) {
  7339. 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)));
  7340. }
  7341. return new Curve3(bez);
  7342. };
  7343. /**
  7344. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7345. * @param p1 (Vector3) the origin point of the Hermite Spline
  7346. * @param t1 (Vector3) the tangent vector at the origin point
  7347. * @param p2 (Vector3) the end point of the Hermite Spline
  7348. * @param t2 (Vector3) the tangent vector at the end point
  7349. * @param nbPoints (integer) the wanted number of points in the curve
  7350. */
  7351. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7352. var hermite = new Array();
  7353. var step = 1.0 / nbPoints;
  7354. for (var i = 0; i <= nbPoints; i++) {
  7355. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7356. }
  7357. return new Curve3(hermite);
  7358. };
  7359. /**
  7360. * Returns a Curve3 object along a CatmullRom Spline curve :
  7361. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  7362. * @param nbPoints (integer) the wanted number of points between each curve control points.
  7363. */
  7364. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  7365. var totalPoints = new Array();
  7366. totalPoints.push(points[0].clone());
  7367. Array.prototype.push.apply(totalPoints, points);
  7368. totalPoints.push(points[points.length - 1].clone());
  7369. var catmullRom = new Array();
  7370. var step = 1.0 / nbPoints;
  7371. var amount = 0.0;
  7372. for (var i = 0; i < totalPoints.length - 3; i++) {
  7373. amount = 0;
  7374. for (var c = 0; c < nbPoints; c++) {
  7375. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7376. amount += step;
  7377. }
  7378. }
  7379. i--;
  7380. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7381. return new Curve3(catmullRom);
  7382. };
  7383. /**
  7384. * Returns the Curve3 stored array of successive Vector3
  7385. */
  7386. Curve3.prototype.getPoints = function () {
  7387. return this._points;
  7388. };
  7389. /**
  7390. * Returns the computed length (float) of the curve.
  7391. */
  7392. Curve3.prototype.length = function () {
  7393. return this._length;
  7394. };
  7395. /**
  7396. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7397. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7398. * curveA and curveB keep unchanged.
  7399. */
  7400. Curve3.prototype.continue = function (curve) {
  7401. var lastPoint = this._points[this._points.length - 1];
  7402. var continuedPoints = this._points.slice();
  7403. var curvePoints = curve.getPoints();
  7404. for (var i = 1; i < curvePoints.length; i++) {
  7405. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7406. }
  7407. var continuedCurve = new Curve3(continuedPoints);
  7408. return continuedCurve;
  7409. };
  7410. Curve3.prototype._computeLength = function (path) {
  7411. var l = 0;
  7412. for (var i = 1; i < path.length; i++) {
  7413. l += (path[i].subtract(path[i - 1])).length();
  7414. }
  7415. return l;
  7416. };
  7417. return Curve3;
  7418. }());
  7419. BABYLON.Curve3 = Curve3;
  7420. // Vertex formats
  7421. var PositionNormalVertex = /** @class */ (function () {
  7422. function PositionNormalVertex(position, normal) {
  7423. if (position === void 0) { position = Vector3.Zero(); }
  7424. if (normal === void 0) { normal = Vector3.Up(); }
  7425. this.position = position;
  7426. this.normal = normal;
  7427. }
  7428. PositionNormalVertex.prototype.clone = function () {
  7429. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7430. };
  7431. return PositionNormalVertex;
  7432. }());
  7433. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7434. var PositionNormalTextureVertex = /** @class */ (function () {
  7435. function PositionNormalTextureVertex(position, normal, uv) {
  7436. if (position === void 0) { position = Vector3.Zero(); }
  7437. if (normal === void 0) { normal = Vector3.Up(); }
  7438. if (uv === void 0) { uv = Vector2.Zero(); }
  7439. this.position = position;
  7440. this.normal = normal;
  7441. this.uv = uv;
  7442. }
  7443. PositionNormalTextureVertex.prototype.clone = function () {
  7444. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7445. };
  7446. return PositionNormalTextureVertex;
  7447. }());
  7448. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7449. // Temporary pre-allocated objects for engine internal use
  7450. // usage in any internal function :
  7451. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7452. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7453. var Tmp = /** @class */ (function () {
  7454. function Tmp() {
  7455. }
  7456. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7457. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7458. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7459. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7460. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7461. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7462. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7463. Matrix.Zero(), Matrix.Zero(),
  7464. Matrix.Zero(), Matrix.Zero(),
  7465. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7466. return Tmp;
  7467. }());
  7468. BABYLON.Tmp = Tmp;
  7469. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7470. var MathTmp = /** @class */ (function () {
  7471. function MathTmp() {
  7472. }
  7473. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7474. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7475. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7476. return MathTmp;
  7477. }());
  7478. })(BABYLON || (BABYLON = {}));
  7479. //# sourceMappingURL=babylon.math.js.map
  7480. var BABYLON;
  7481. (function (BABYLON) {
  7482. var Scalar = /** @class */ (function () {
  7483. function Scalar() {
  7484. }
  7485. /**
  7486. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7487. */
  7488. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7489. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7490. var num = a - b;
  7491. return -epsilon <= num && num <= epsilon;
  7492. };
  7493. /**
  7494. * Returns a string : the upper case translation of the number i to hexadecimal.
  7495. */
  7496. Scalar.ToHex = function (i) {
  7497. var str = i.toString(16);
  7498. if (i <= 15) {
  7499. return ("0" + str).toUpperCase();
  7500. }
  7501. return str.toUpperCase();
  7502. };
  7503. /**
  7504. * Returns -1 if value is negative and +1 is value is positive.
  7505. * Returns the value itself if it's equal to zero.
  7506. */
  7507. Scalar.Sign = function (value) {
  7508. value = +value; // convert to a number
  7509. if (value === 0 || isNaN(value))
  7510. return value;
  7511. return value > 0 ? 1 : -1;
  7512. };
  7513. /**
  7514. * Returns the value itself if it's between min and max.
  7515. * Returns min if the value is lower than min.
  7516. * Returns max if the value is greater than max.
  7517. */
  7518. Scalar.Clamp = function (value, min, max) {
  7519. if (min === void 0) { min = 0; }
  7520. if (max === void 0) { max = 1; }
  7521. return Math.min(max, Math.max(min, value));
  7522. };
  7523. /**
  7524. * Returns the log2 of value.
  7525. */
  7526. Scalar.Log2 = function (value) {
  7527. return Math.log(value) * Math.LOG2E;
  7528. };
  7529. /**
  7530. * Loops the value, so that it is never larger than length and never smaller than 0.
  7531. *
  7532. * This is similar to the modulo operator but it works with floating point numbers.
  7533. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7534. * With t = 5 and length = 2.5, the result would be 0.0.
  7535. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7536. */
  7537. Scalar.Repeat = function (value, length) {
  7538. return value - Math.floor(value / length) * length;
  7539. };
  7540. /**
  7541. * Normalize the value between 0.0 and 1.0 using min and max values
  7542. */
  7543. Scalar.Normalize = function (value, min, max) {
  7544. return (value - min) / (max - min);
  7545. };
  7546. /**
  7547. * Denormalize the value from 0.0 and 1.0 using min and max values
  7548. */
  7549. Scalar.Denormalize = function (normalized, min, max) {
  7550. return (normalized * (max - min) + min);
  7551. };
  7552. /**
  7553. * Calculates the shortest difference between two given angles given in degrees.
  7554. */
  7555. Scalar.DeltaAngle = function (current, target) {
  7556. var num = Scalar.Repeat(target - current, 360.0);
  7557. if (num > 180.0) {
  7558. num -= 360.0;
  7559. }
  7560. return num;
  7561. };
  7562. /**
  7563. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7564. *
  7565. * The returned value will move back and forth between 0 and length
  7566. */
  7567. Scalar.PingPong = function (tx, length) {
  7568. var t = Scalar.Repeat(tx, length * 2.0);
  7569. return length - Math.abs(t - length);
  7570. };
  7571. /**
  7572. * Interpolates between min and max with smoothing at the limits.
  7573. *
  7574. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7575. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7576. */
  7577. Scalar.SmoothStep = function (from, to, tx) {
  7578. var t = Scalar.Clamp(tx);
  7579. t = -2.0 * t * t * t + 3.0 * t * t;
  7580. return to * t + from * (1.0 - t);
  7581. };
  7582. /**
  7583. * Moves a value current towards target.
  7584. *
  7585. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7586. * Negative values of maxDelta pushes the value away from target.
  7587. */
  7588. Scalar.MoveTowards = function (current, target, maxDelta) {
  7589. var result = 0;
  7590. if (Math.abs(target - current) <= maxDelta) {
  7591. result = target;
  7592. }
  7593. else {
  7594. result = current + Scalar.Sign(target - current) * maxDelta;
  7595. }
  7596. return result;
  7597. };
  7598. /**
  7599. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7600. *
  7601. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7602. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7603. */
  7604. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7605. var num = Scalar.DeltaAngle(current, target);
  7606. var result = 0;
  7607. if (-maxDelta < num && num < maxDelta) {
  7608. result = target;
  7609. }
  7610. else {
  7611. target = current + num;
  7612. result = Scalar.MoveTowards(current, target, maxDelta);
  7613. }
  7614. return result;
  7615. };
  7616. /**
  7617. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7618. */
  7619. Scalar.Lerp = function (start, end, amount) {
  7620. return start + ((end - start) * amount);
  7621. };
  7622. /**
  7623. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7624. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7625. */
  7626. Scalar.LerpAngle = function (start, end, amount) {
  7627. var num = Scalar.Repeat(end - start, 360.0);
  7628. if (num > 180.0) {
  7629. num -= 360.0;
  7630. }
  7631. return start + num * Scalar.Clamp(amount);
  7632. };
  7633. /**
  7634. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7635. */
  7636. Scalar.InverseLerp = function (a, b, value) {
  7637. var result = 0;
  7638. if (a != b) {
  7639. result = Scalar.Clamp((value - a) / (b - a));
  7640. }
  7641. else {
  7642. result = 0.0;
  7643. }
  7644. return result;
  7645. };
  7646. /**
  7647. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7648. */
  7649. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7650. var squared = amount * amount;
  7651. var cubed = amount * squared;
  7652. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7653. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7654. var part3 = (cubed - (2.0 * squared)) + amount;
  7655. var part4 = cubed - squared;
  7656. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7657. };
  7658. /**
  7659. * Returns a random float number between and min and max values
  7660. */
  7661. Scalar.RandomRange = function (min, max) {
  7662. if (min === max)
  7663. return min;
  7664. return ((Math.random() * (max - min)) + min);
  7665. };
  7666. /**
  7667. * This function returns percentage of a number in a given range.
  7668. *
  7669. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7670. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7671. */
  7672. Scalar.RangeToPercent = function (number, min, max) {
  7673. return ((number - min) / (max - min));
  7674. };
  7675. /**
  7676. * This function returns number that corresponds to the percentage in a given range.
  7677. *
  7678. * PercentToRange(0.34,0,100) will return 34.
  7679. */
  7680. Scalar.PercentToRange = function (percent, min, max) {
  7681. return ((max - min) * percent + min);
  7682. };
  7683. /**
  7684. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7685. * @param angle The angle to normalize in radian.
  7686. * @return The converted angle.
  7687. */
  7688. Scalar.NormalizeRadians = function (angle) {
  7689. // More precise but slower version kept for reference.
  7690. // angle = angle % Tools.TwoPi;
  7691. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7692. //if (angle > Math.PI) {
  7693. // angle -= Tools.TwoPi;
  7694. //}
  7695. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7696. return angle;
  7697. };
  7698. /**
  7699. * Two pi constants convenient for computation.
  7700. */
  7701. Scalar.TwoPi = Math.PI * 2;
  7702. return Scalar;
  7703. }());
  7704. BABYLON.Scalar = Scalar;
  7705. })(BABYLON || (BABYLON = {}));
  7706. //# sourceMappingURL=babylon.math.scalar.js.map
  7707. //# sourceMappingURL=babylon.mixins.js.map
  7708. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7709. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7710. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7711. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7712. //# sourceMappingURL=babylon.webgl2.js.map
  7713. var BABYLON;
  7714. (function (BABYLON) {
  7715. var __decoratorInitialStore = {};
  7716. var __mergedStore = {};
  7717. var _copySource = function (creationFunction, source, instanciate) {
  7718. var destination = creationFunction();
  7719. // Tags
  7720. if (BABYLON.Tags) {
  7721. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7722. }
  7723. var classStore = getMergedStore(destination);
  7724. // Properties
  7725. for (var property in classStore) {
  7726. var propertyDescriptor = classStore[property];
  7727. var sourceProperty = source[property];
  7728. var propertyType = propertyDescriptor.type;
  7729. if (sourceProperty !== undefined && sourceProperty !== null) {
  7730. switch (propertyType) {
  7731. case 0: // Value
  7732. case 6: // Mesh reference
  7733. case 11: // Camera reference
  7734. destination[property] = sourceProperty;
  7735. break;
  7736. case 1: // Texture
  7737. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7738. break;
  7739. case 2: // Color3
  7740. case 3: // FresnelParameters
  7741. case 4: // Vector2
  7742. case 5: // Vector3
  7743. case 7: // Color Curves
  7744. case 10: // Quaternion
  7745. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7746. break;
  7747. }
  7748. }
  7749. }
  7750. return destination;
  7751. };
  7752. function getDirectStore(target) {
  7753. var classKey = target.getClassName();
  7754. if (!__decoratorInitialStore[classKey]) {
  7755. __decoratorInitialStore[classKey] = {};
  7756. }
  7757. return __decoratorInitialStore[classKey];
  7758. }
  7759. /**
  7760. * Return the list of properties flagged as serializable
  7761. * @param target: host object
  7762. */
  7763. function getMergedStore(target) {
  7764. var classKey = target.getClassName();
  7765. if (__mergedStore[classKey]) {
  7766. return __mergedStore[classKey];
  7767. }
  7768. __mergedStore[classKey] = {};
  7769. var store = __mergedStore[classKey];
  7770. var currentTarget = target;
  7771. var currentKey = classKey;
  7772. while (currentKey) {
  7773. var initialStore = __decoratorInitialStore[currentKey];
  7774. for (var property in initialStore) {
  7775. store[property] = initialStore[property];
  7776. }
  7777. var parent_1 = void 0;
  7778. var done = false;
  7779. do {
  7780. parent_1 = Object.getPrototypeOf(currentTarget);
  7781. if (!parent_1.getClassName) {
  7782. done = true;
  7783. break;
  7784. }
  7785. if (parent_1.getClassName() !== currentKey) {
  7786. break;
  7787. }
  7788. currentTarget = parent_1;
  7789. } while (parent_1);
  7790. if (done) {
  7791. break;
  7792. }
  7793. currentKey = parent_1.getClassName();
  7794. currentTarget = parent_1;
  7795. }
  7796. return store;
  7797. }
  7798. function generateSerializableMember(type, sourceName) {
  7799. return function (target, propertyKey) {
  7800. var classStore = getDirectStore(target);
  7801. if (!classStore[propertyKey]) {
  7802. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7803. }
  7804. };
  7805. }
  7806. function generateExpandMember(setCallback, targetKey) {
  7807. if (targetKey === void 0) { targetKey = null; }
  7808. return function (target, propertyKey) {
  7809. var key = targetKey || ("_" + propertyKey);
  7810. Object.defineProperty(target, propertyKey, {
  7811. get: function () {
  7812. return this[key];
  7813. },
  7814. set: function (value) {
  7815. if (this[key] === value) {
  7816. return;
  7817. }
  7818. this[key] = value;
  7819. target[setCallback].apply(this);
  7820. },
  7821. enumerable: true,
  7822. configurable: true
  7823. });
  7824. };
  7825. }
  7826. function expandToProperty(callback, targetKey) {
  7827. if (targetKey === void 0) { targetKey = null; }
  7828. return generateExpandMember(callback, targetKey);
  7829. }
  7830. BABYLON.expandToProperty = expandToProperty;
  7831. function serialize(sourceName) {
  7832. return generateSerializableMember(0, sourceName); // value member
  7833. }
  7834. BABYLON.serialize = serialize;
  7835. function serializeAsTexture(sourceName) {
  7836. return generateSerializableMember(1, sourceName); // texture member
  7837. }
  7838. BABYLON.serializeAsTexture = serializeAsTexture;
  7839. function serializeAsColor3(sourceName) {
  7840. return generateSerializableMember(2, sourceName); // color3 member
  7841. }
  7842. BABYLON.serializeAsColor3 = serializeAsColor3;
  7843. function serializeAsFresnelParameters(sourceName) {
  7844. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7845. }
  7846. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7847. function serializeAsVector2(sourceName) {
  7848. return generateSerializableMember(4, sourceName); // vector2 member
  7849. }
  7850. BABYLON.serializeAsVector2 = serializeAsVector2;
  7851. function serializeAsVector3(sourceName) {
  7852. return generateSerializableMember(5, sourceName); // vector3 member
  7853. }
  7854. BABYLON.serializeAsVector3 = serializeAsVector3;
  7855. function serializeAsMeshReference(sourceName) {
  7856. return generateSerializableMember(6, sourceName); // mesh reference member
  7857. }
  7858. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7859. function serializeAsColorCurves(sourceName) {
  7860. return generateSerializableMember(7, sourceName); // color curves
  7861. }
  7862. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7863. function serializeAsColor4(sourceName) {
  7864. return generateSerializableMember(8, sourceName); // color 4
  7865. }
  7866. BABYLON.serializeAsColor4 = serializeAsColor4;
  7867. function serializeAsImageProcessingConfiguration(sourceName) {
  7868. return generateSerializableMember(9, sourceName); // image processing
  7869. }
  7870. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7871. function serializeAsQuaternion(sourceName) {
  7872. return generateSerializableMember(10, sourceName); // quaternion member
  7873. }
  7874. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7875. /**
  7876. * Decorator used to define property that can be serialized as reference to a camera
  7877. * @param sourceName defines the name of the property to decorate
  7878. */
  7879. function serializeAsCameraReference(sourceName) {
  7880. return generateSerializableMember(11, sourceName); // camera reference member
  7881. }
  7882. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7883. var SerializationHelper = /** @class */ (function () {
  7884. function SerializationHelper() {
  7885. }
  7886. SerializationHelper.Serialize = function (entity, serializationObject) {
  7887. if (!serializationObject) {
  7888. serializationObject = {};
  7889. }
  7890. // Tags
  7891. if (BABYLON.Tags) {
  7892. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7893. }
  7894. var serializedProperties = getMergedStore(entity);
  7895. // Properties
  7896. for (var property in serializedProperties) {
  7897. var propertyDescriptor = serializedProperties[property];
  7898. var targetPropertyName = propertyDescriptor.sourceName || property;
  7899. var propertyType = propertyDescriptor.type;
  7900. var sourceProperty = entity[property];
  7901. if (sourceProperty !== undefined && sourceProperty !== null) {
  7902. switch (propertyType) {
  7903. case 0: // Value
  7904. serializationObject[targetPropertyName] = sourceProperty;
  7905. break;
  7906. case 1: // Texture
  7907. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7908. break;
  7909. case 2: // Color3
  7910. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7911. break;
  7912. case 3: // FresnelParameters
  7913. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7914. break;
  7915. case 4: // Vector2
  7916. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7917. break;
  7918. case 5: // Vector3
  7919. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7920. break;
  7921. case 6: // Mesh reference
  7922. serializationObject[targetPropertyName] = sourceProperty.id;
  7923. break;
  7924. case 7: // Color Curves
  7925. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7926. break;
  7927. case 8: // Color 4
  7928. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7929. break;
  7930. case 9: // Image Processing
  7931. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7932. break;
  7933. case 10: // Quaternion
  7934. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7935. break;
  7936. case 11: // Camera reference
  7937. serializationObject[targetPropertyName] = sourceProperty.id;
  7938. break;
  7939. }
  7940. }
  7941. }
  7942. return serializationObject;
  7943. };
  7944. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7945. if (rootUrl === void 0) { rootUrl = null; }
  7946. var destination = creationFunction();
  7947. if (!rootUrl) {
  7948. rootUrl = "";
  7949. }
  7950. // Tags
  7951. if (BABYLON.Tags) {
  7952. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7953. }
  7954. var classStore = getMergedStore(destination);
  7955. // Properties
  7956. for (var property in classStore) {
  7957. var propertyDescriptor = classStore[property];
  7958. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7959. var propertyType = propertyDescriptor.type;
  7960. if (sourceProperty !== undefined && sourceProperty !== null) {
  7961. var dest = destination;
  7962. switch (propertyType) {
  7963. case 0: // Value
  7964. dest[property] = sourceProperty;
  7965. break;
  7966. case 1: // Texture
  7967. if (scene) {
  7968. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7969. }
  7970. break;
  7971. case 2: // Color3
  7972. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7973. break;
  7974. case 3: // FresnelParameters
  7975. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7976. break;
  7977. case 4: // Vector2
  7978. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7979. break;
  7980. case 5: // Vector3
  7981. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7982. break;
  7983. case 6: // Mesh reference
  7984. if (scene) {
  7985. dest[property] = scene.getLastMeshByID(sourceProperty);
  7986. }
  7987. break;
  7988. case 7: // Color Curves
  7989. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7990. break;
  7991. case 8: // Color 4
  7992. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7993. break;
  7994. case 9: // Image Processing
  7995. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7996. break;
  7997. case 10: // Quaternion
  7998. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7999. break;
  8000. case 11: // Camera reference
  8001. if (scene) {
  8002. dest[property] = scene.getCameraByID(sourceProperty);
  8003. }
  8004. break;
  8005. }
  8006. }
  8007. }
  8008. return destination;
  8009. };
  8010. SerializationHelper.Clone = function (creationFunction, source) {
  8011. return _copySource(creationFunction, source, false);
  8012. };
  8013. SerializationHelper.Instanciate = function (creationFunction, source) {
  8014. return _copySource(creationFunction, source, true);
  8015. };
  8016. return SerializationHelper;
  8017. }());
  8018. BABYLON.SerializationHelper = SerializationHelper;
  8019. })(BABYLON || (BABYLON = {}));
  8020. //# sourceMappingURL=babylon.decorators.js.map
  8021. var BABYLON;
  8022. (function (BABYLON) {
  8023. /**
  8024. * Wrapper class for promise with external resolve and reject.
  8025. */
  8026. var Deferred = /** @class */ (function () {
  8027. /**
  8028. * Constructor for this deferred object.
  8029. */
  8030. function Deferred() {
  8031. var _this = this;
  8032. this.promise = new Promise(function (resolve, reject) {
  8033. _this._resolve = resolve;
  8034. _this._reject = reject;
  8035. });
  8036. }
  8037. Object.defineProperty(Deferred.prototype, "resolve", {
  8038. /**
  8039. * The resolve method of the promise associated with this deferred object.
  8040. */
  8041. get: function () {
  8042. return this._resolve;
  8043. },
  8044. enumerable: true,
  8045. configurable: true
  8046. });
  8047. Object.defineProperty(Deferred.prototype, "reject", {
  8048. /**
  8049. * The reject method of the promise associated with this deferred object.
  8050. */
  8051. get: function () {
  8052. return this._reject;
  8053. },
  8054. enumerable: true,
  8055. configurable: true
  8056. });
  8057. return Deferred;
  8058. }());
  8059. BABYLON.Deferred = Deferred;
  8060. })(BABYLON || (BABYLON = {}));
  8061. //# sourceMappingURL=babylon.deferred.js.map
  8062. var BABYLON;
  8063. (function (BABYLON) {
  8064. /**
  8065. * A class serves as a medium between the observable and its observers
  8066. */
  8067. var EventState = /** @class */ (function () {
  8068. /**
  8069. * Create a new EventState
  8070. * @param mask defines the mask associated with this state
  8071. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8072. * @param target defines the original target of the state
  8073. * @param currentTarget defines the current target of the state
  8074. */
  8075. function EventState(mask, skipNextObservers, target, currentTarget) {
  8076. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8077. this.initalize(mask, skipNextObservers, target, currentTarget);
  8078. }
  8079. /**
  8080. * Initialize the current event state
  8081. * @param mask defines the mask associated with this state
  8082. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8083. * @param target defines the original target of the state
  8084. * @param currentTarget defines the current target of the state
  8085. * @returns the current event state
  8086. */
  8087. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8088. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8089. this.mask = mask;
  8090. this.skipNextObservers = skipNextObservers;
  8091. this.target = target;
  8092. this.currentTarget = currentTarget;
  8093. return this;
  8094. };
  8095. return EventState;
  8096. }());
  8097. BABYLON.EventState = EventState;
  8098. /**
  8099. * Represent an Observer registered to a given Observable object.
  8100. */
  8101. var Observer = /** @class */ (function () {
  8102. /**
  8103. * Creates a new observer
  8104. * @param callback defines the callback to call when the observer is notified
  8105. * @param mask defines the mask of the observer (used to filter notifications)
  8106. * @param scope defines the current scope used to restore the JS context
  8107. */
  8108. function Observer(
  8109. /**
  8110. * Defines the callback to call when the observer is notified
  8111. */
  8112. callback,
  8113. /**
  8114. * Defines the mask of the observer (used to filter notifications)
  8115. */
  8116. mask,
  8117. /**
  8118. * Defines the current scope used to restore the JS context
  8119. */
  8120. scope) {
  8121. if (scope === void 0) { scope = null; }
  8122. this.callback = callback;
  8123. this.mask = mask;
  8124. this.scope = scope;
  8125. /** @hidden */
  8126. this._willBeUnregistered = false;
  8127. /**
  8128. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8129. */
  8130. this.unregisterOnNextCall = false;
  8131. }
  8132. return Observer;
  8133. }());
  8134. BABYLON.Observer = Observer;
  8135. /**
  8136. * Represent a list of observers registered to multiple Observables object.
  8137. */
  8138. var MultiObserver = /** @class */ (function () {
  8139. function MultiObserver() {
  8140. }
  8141. /**
  8142. * Release associated resources
  8143. */
  8144. MultiObserver.prototype.dispose = function () {
  8145. if (this._observers && this._observables) {
  8146. for (var index = 0; index < this._observers.length; index++) {
  8147. this._observables[index].remove(this._observers[index]);
  8148. }
  8149. }
  8150. this._observers = null;
  8151. this._observables = null;
  8152. };
  8153. /**
  8154. * Raise a callback when one of the observable will notify
  8155. * @param observables defines a list of observables to watch
  8156. * @param callback defines the callback to call on notification
  8157. * @param mask defines the mask used to filter notifications
  8158. * @param scope defines the current scope used to restore the JS context
  8159. * @returns the new MultiObserver
  8160. */
  8161. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8162. if (mask === void 0) { mask = -1; }
  8163. if (scope === void 0) { scope = null; }
  8164. var result = new MultiObserver();
  8165. result._observers = new Array();
  8166. result._observables = observables;
  8167. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8168. var observable = observables_1[_i];
  8169. var observer = observable.add(callback, mask, false, scope);
  8170. if (observer) {
  8171. result._observers.push(observer);
  8172. }
  8173. }
  8174. return result;
  8175. };
  8176. return MultiObserver;
  8177. }());
  8178. BABYLON.MultiObserver = MultiObserver;
  8179. /**
  8180. * The Observable class is a simple implementation of the Observable pattern.
  8181. *
  8182. * 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.
  8183. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8184. * 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).
  8185. * 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.
  8186. */
  8187. var Observable = /** @class */ (function () {
  8188. /**
  8189. * Creates a new observable
  8190. * @param onObserverAdded defines a callback to call when a new observer is added
  8191. */
  8192. function Observable(onObserverAdded) {
  8193. this._observers = new Array();
  8194. this._eventState = new EventState(0);
  8195. if (onObserverAdded) {
  8196. this._onObserverAdded = onObserverAdded;
  8197. }
  8198. }
  8199. /**
  8200. * Create a new Observer with the specified callback
  8201. * @param callback the callback that will be executed for that Observer
  8202. * @param mask the mask used to filter observers
  8203. * @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.
  8204. * @param scope optional scope for the callback to be called from
  8205. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8206. * @returns the new observer created for the callback
  8207. */
  8208. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8209. if (mask === void 0) { mask = -1; }
  8210. if (insertFirst === void 0) { insertFirst = false; }
  8211. if (scope === void 0) { scope = null; }
  8212. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8213. if (!callback) {
  8214. return null;
  8215. }
  8216. var observer = new Observer(callback, mask, scope);
  8217. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8218. if (insertFirst) {
  8219. this._observers.unshift(observer);
  8220. }
  8221. else {
  8222. this._observers.push(observer);
  8223. }
  8224. if (this._onObserverAdded) {
  8225. this._onObserverAdded(observer);
  8226. }
  8227. return observer;
  8228. };
  8229. /**
  8230. * Remove an Observer from the Observable object
  8231. * @param observer the instance of the Observer to remove
  8232. * @returns false if it doesn't belong to this Observable
  8233. */
  8234. Observable.prototype.remove = function (observer) {
  8235. if (!observer) {
  8236. return false;
  8237. }
  8238. var index = this._observers.indexOf(observer);
  8239. if (index !== -1) {
  8240. this._observers.splice(index, 1);
  8241. return true;
  8242. }
  8243. return false;
  8244. };
  8245. /**
  8246. * Remove a callback from the Observable object
  8247. * @param callback the callback to remove
  8248. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8249. * @returns false if it doesn't belong to this Observable
  8250. */
  8251. Observable.prototype.removeCallback = function (callback, scope) {
  8252. for (var index = 0; index < this._observers.length; index++) {
  8253. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8254. this._observers.splice(index, 1);
  8255. return true;
  8256. }
  8257. }
  8258. return false;
  8259. };
  8260. Observable.prototype._deferUnregister = function (observer) {
  8261. var _this = this;
  8262. observer.unregisterOnNextCall = false;
  8263. observer._willBeUnregistered = true;
  8264. BABYLON.Tools.SetImmediate(function () {
  8265. _this.remove(observer);
  8266. });
  8267. };
  8268. /**
  8269. * Notify all Observers by calling their respective callback with the given data
  8270. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8271. * @param eventData defines the data to send to all observers
  8272. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8273. * @param target defines the original target of the state
  8274. * @param currentTarget defines the current target of the state
  8275. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8276. */
  8277. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8278. if (mask === void 0) { mask = -1; }
  8279. if (!this._observers.length) {
  8280. return true;
  8281. }
  8282. var state = this._eventState;
  8283. state.mask = mask;
  8284. state.target = target;
  8285. state.currentTarget = currentTarget;
  8286. state.skipNextObservers = false;
  8287. state.lastReturnValue = eventData;
  8288. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8289. var obs = _a[_i];
  8290. if (obs._willBeUnregistered) {
  8291. continue;
  8292. }
  8293. if (obs.mask & mask) {
  8294. if (obs.scope) {
  8295. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8296. }
  8297. else {
  8298. state.lastReturnValue = obs.callback(eventData, state);
  8299. }
  8300. if (obs.unregisterOnNextCall) {
  8301. this._deferUnregister(obs);
  8302. }
  8303. }
  8304. if (state.skipNextObservers) {
  8305. return false;
  8306. }
  8307. }
  8308. return true;
  8309. };
  8310. /**
  8311. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8312. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8313. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8314. * and it is crucial that all callbacks will be executed.
  8315. * The order of the callbacks is kept, callbacks are not executed parallel.
  8316. *
  8317. * @param eventData The data to be sent to each callback
  8318. * @param mask is used to filter observers defaults to -1
  8319. * @param target defines the callback target (see EventState)
  8320. * @param currentTarget defines he current object in the bubbling phase
  8321. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8322. */
  8323. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8324. var _this = this;
  8325. if (mask === void 0) { mask = -1; }
  8326. // create an empty promise
  8327. var p = Promise.resolve(eventData);
  8328. // no observers? return this promise.
  8329. if (!this._observers.length) {
  8330. return p;
  8331. }
  8332. var state = this._eventState;
  8333. state.mask = mask;
  8334. state.target = target;
  8335. state.currentTarget = currentTarget;
  8336. state.skipNextObservers = false;
  8337. // execute one callback after another (not using Promise.all, the order is important)
  8338. this._observers.forEach(function (obs) {
  8339. if (state.skipNextObservers) {
  8340. return;
  8341. }
  8342. if (obs._willBeUnregistered) {
  8343. return;
  8344. }
  8345. if (obs.mask & mask) {
  8346. if (obs.scope) {
  8347. p = p.then(function (lastReturnedValue) {
  8348. state.lastReturnValue = lastReturnedValue;
  8349. return obs.callback.apply(obs.scope, [eventData, state]);
  8350. });
  8351. }
  8352. else {
  8353. p = p.then(function (lastReturnedValue) {
  8354. state.lastReturnValue = lastReturnedValue;
  8355. return obs.callback(eventData, state);
  8356. });
  8357. }
  8358. if (obs.unregisterOnNextCall) {
  8359. _this._deferUnregister(obs);
  8360. }
  8361. }
  8362. });
  8363. // return the eventData
  8364. return p.then(function () { return eventData; });
  8365. };
  8366. /**
  8367. * Notify a specific observer
  8368. * @param observer defines the observer to notify
  8369. * @param eventData defines the data to be sent to each callback
  8370. * @param mask is used to filter observers defaults to -1
  8371. */
  8372. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8373. if (mask === void 0) { mask = -1; }
  8374. var state = this._eventState;
  8375. state.mask = mask;
  8376. state.skipNextObservers = false;
  8377. observer.callback(eventData, state);
  8378. };
  8379. /**
  8380. * Gets a boolean indicating if the observable has at least one observer
  8381. * @returns true is the Observable has at least one Observer registered
  8382. */
  8383. Observable.prototype.hasObservers = function () {
  8384. return this._observers.length > 0;
  8385. };
  8386. /**
  8387. * Clear the list of observers
  8388. */
  8389. Observable.prototype.clear = function () {
  8390. this._observers = new Array();
  8391. this._onObserverAdded = null;
  8392. };
  8393. /**
  8394. * Clone the current observable
  8395. * @returns a new observable
  8396. */
  8397. Observable.prototype.clone = function () {
  8398. var result = new Observable();
  8399. result._observers = this._observers.slice(0);
  8400. return result;
  8401. };
  8402. /**
  8403. * Does this observable handles observer registered with a given mask
  8404. * @param mask defines the mask to be tested
  8405. * @return whether or not one observer registered with the given mask is handeled
  8406. **/
  8407. Observable.prototype.hasSpecificMask = function (mask) {
  8408. if (mask === void 0) { mask = -1; }
  8409. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8410. var obs = _a[_i];
  8411. if (obs.mask & mask || obs.mask === mask) {
  8412. return true;
  8413. }
  8414. }
  8415. return false;
  8416. };
  8417. return Observable;
  8418. }());
  8419. BABYLON.Observable = Observable;
  8420. })(BABYLON || (BABYLON = {}));
  8421. //# sourceMappingURL=babylon.observable.js.map
  8422. var BABYLON;
  8423. (function (BABYLON) {
  8424. var SmartArray = /** @class */ (function () {
  8425. function SmartArray(capacity) {
  8426. this.length = 0;
  8427. this.data = new Array(capacity);
  8428. this._id = SmartArray._GlobalId++;
  8429. }
  8430. SmartArray.prototype.push = function (value) {
  8431. this.data[this.length++] = value;
  8432. if (this.length > this.data.length) {
  8433. this.data.length *= 2;
  8434. }
  8435. };
  8436. SmartArray.prototype.forEach = function (func) {
  8437. for (var index = 0; index < this.length; index++) {
  8438. func(this.data[index]);
  8439. }
  8440. };
  8441. SmartArray.prototype.sort = function (compareFn) {
  8442. this.data.sort(compareFn);
  8443. };
  8444. SmartArray.prototype.reset = function () {
  8445. this.length = 0;
  8446. };
  8447. SmartArray.prototype.dispose = function () {
  8448. this.reset();
  8449. if (this.data) {
  8450. this.data.length = 0;
  8451. this.data = [];
  8452. }
  8453. };
  8454. SmartArray.prototype.concat = function (array) {
  8455. if (array.length === 0) {
  8456. return;
  8457. }
  8458. if (this.length + array.length > this.data.length) {
  8459. this.data.length = (this.length + array.length) * 2;
  8460. }
  8461. for (var index = 0; index < array.length; index++) {
  8462. this.data[this.length++] = (array.data || array)[index];
  8463. }
  8464. };
  8465. SmartArray.prototype.indexOf = function (value) {
  8466. var position = this.data.indexOf(value);
  8467. if (position >= this.length) {
  8468. return -1;
  8469. }
  8470. return position;
  8471. };
  8472. SmartArray.prototype.contains = function (value) {
  8473. return this.data.indexOf(value) !== -1;
  8474. };
  8475. // Statics
  8476. SmartArray._GlobalId = 0;
  8477. return SmartArray;
  8478. }());
  8479. BABYLON.SmartArray = SmartArray;
  8480. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8481. __extends(SmartArrayNoDuplicate, _super);
  8482. function SmartArrayNoDuplicate() {
  8483. var _this = _super !== null && _super.apply(this, arguments) || this;
  8484. _this._duplicateId = 0;
  8485. return _this;
  8486. }
  8487. SmartArrayNoDuplicate.prototype.push = function (value) {
  8488. _super.prototype.push.call(this, value);
  8489. if (!value.__smartArrayFlags) {
  8490. value.__smartArrayFlags = {};
  8491. }
  8492. value.__smartArrayFlags[this._id] = this._duplicateId;
  8493. };
  8494. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8495. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8496. return false;
  8497. }
  8498. this.push(value);
  8499. return true;
  8500. };
  8501. SmartArrayNoDuplicate.prototype.reset = function () {
  8502. _super.prototype.reset.call(this);
  8503. this._duplicateId++;
  8504. };
  8505. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8506. if (array.length === 0) {
  8507. return;
  8508. }
  8509. if (this.length + array.length > this.data.length) {
  8510. this.data.length = (this.length + array.length) * 2;
  8511. }
  8512. for (var index = 0; index < array.length; index++) {
  8513. var item = (array.data || array)[index];
  8514. this.pushNoDuplicate(item);
  8515. }
  8516. };
  8517. return SmartArrayNoDuplicate;
  8518. }(SmartArray));
  8519. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8520. })(BABYLON || (BABYLON = {}));
  8521. //# sourceMappingURL=babylon.smartArray.js.map
  8522. var BABYLON;
  8523. (function (BABYLON) {
  8524. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8525. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8526. var LoadFileError = /** @class */ (function (_super) {
  8527. __extends(LoadFileError, _super);
  8528. function LoadFileError(message, request) {
  8529. var _this = _super.call(this, message) || this;
  8530. _this.request = request;
  8531. _this.name = "LoadFileError";
  8532. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8533. return _this;
  8534. }
  8535. // Polyfill for Object.setPrototypeOf if necessary.
  8536. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8537. return LoadFileError;
  8538. }(Error));
  8539. BABYLON.LoadFileError = LoadFileError;
  8540. var RetryStrategy = /** @class */ (function () {
  8541. function RetryStrategy() {
  8542. }
  8543. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8544. if (maxRetries === void 0) { maxRetries = 3; }
  8545. if (baseInterval === void 0) { baseInterval = 500; }
  8546. return function (url, request, retryIndex) {
  8547. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8548. return -1;
  8549. }
  8550. return Math.pow(2, retryIndex) * baseInterval;
  8551. };
  8552. };
  8553. return RetryStrategy;
  8554. }());
  8555. BABYLON.RetryStrategy = RetryStrategy;
  8556. // Screenshots
  8557. var screenshotCanvas;
  8558. var cloneValue = function (source, destinationObject) {
  8559. if (!source)
  8560. return null;
  8561. if (source instanceof BABYLON.Mesh) {
  8562. return null;
  8563. }
  8564. if (source instanceof BABYLON.SubMesh) {
  8565. return source.clone(destinationObject);
  8566. }
  8567. else if (source.clone) {
  8568. return source.clone();
  8569. }
  8570. return null;
  8571. };
  8572. var Tools = /** @class */ (function () {
  8573. function Tools() {
  8574. }
  8575. /**
  8576. * Interpolates between a and b via alpha
  8577. * @param a The lower value (returned when alpha = 0)
  8578. * @param b The upper value (returned when alpha = 1)
  8579. * @param alpha The interpolation-factor
  8580. * @return The mixed value
  8581. */
  8582. Tools.Mix = function (a, b, alpha) {
  8583. return a * (1 - alpha) + b * alpha;
  8584. };
  8585. Tools.Instantiate = function (className) {
  8586. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8587. return Tools.RegisteredExternalClasses[className];
  8588. }
  8589. var arr = className.split(".");
  8590. var fn = (window || this);
  8591. for (var i = 0, len = arr.length; i < len; i++) {
  8592. fn = fn[arr[i]];
  8593. }
  8594. if (typeof fn !== "function") {
  8595. return null;
  8596. }
  8597. return fn;
  8598. };
  8599. /**
  8600. * Provides a slice function that will work even on IE
  8601. * @param data defines the array to slice
  8602. * @param start defines the start of the data (optional)
  8603. * @param end defines the end of the data (optional)
  8604. * @returns the new sliced array
  8605. */
  8606. Tools.Slice = function (data, start, end) {
  8607. if (data.slice) {
  8608. return data.slice(start, end);
  8609. }
  8610. return Array.prototype.slice.call(data, start, end);
  8611. };
  8612. Tools.SetImmediate = function (action) {
  8613. if (window.setImmediate) {
  8614. window.setImmediate(action);
  8615. }
  8616. else {
  8617. setTimeout(action, 1);
  8618. }
  8619. };
  8620. Tools.IsExponentOfTwo = function (value) {
  8621. var count = 1;
  8622. do {
  8623. count *= 2;
  8624. } while (count < value);
  8625. return count === value;
  8626. };
  8627. /**
  8628. * Returns the nearest 32-bit single precision float representation of a Number
  8629. * @param value A Number. If the parameter is of a different type, it will get converted
  8630. * to a number or to NaN if it cannot be converted
  8631. * @returns number
  8632. */
  8633. Tools.FloatRound = function (value) {
  8634. if (Math.fround) {
  8635. return Math.fround(value);
  8636. }
  8637. return (Tools._tmpFloatArray[0] = value);
  8638. };
  8639. /**
  8640. * Find the next highest power of two.
  8641. * @param x Number to start search from.
  8642. * @return Next highest power of two.
  8643. */
  8644. Tools.CeilingPOT = function (x) {
  8645. x--;
  8646. x |= x >> 1;
  8647. x |= x >> 2;
  8648. x |= x >> 4;
  8649. x |= x >> 8;
  8650. x |= x >> 16;
  8651. x++;
  8652. return x;
  8653. };
  8654. /**
  8655. * Find the next lowest power of two.
  8656. * @param x Number to start search from.
  8657. * @return Next lowest power of two.
  8658. */
  8659. Tools.FloorPOT = function (x) {
  8660. x = x | (x >> 1);
  8661. x = x | (x >> 2);
  8662. x = x | (x >> 4);
  8663. x = x | (x >> 8);
  8664. x = x | (x >> 16);
  8665. return x - (x >> 1);
  8666. };
  8667. /**
  8668. * Find the nearest power of two.
  8669. * @param x Number to start search from.
  8670. * @return Next nearest power of two.
  8671. */
  8672. Tools.NearestPOT = function (x) {
  8673. var c = Tools.CeilingPOT(x);
  8674. var f = Tools.FloorPOT(x);
  8675. return (c - x) > (x - f) ? f : c;
  8676. };
  8677. Tools.GetExponentOfTwo = function (value, max, mode) {
  8678. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8679. var pot;
  8680. switch (mode) {
  8681. case BABYLON.Engine.SCALEMODE_FLOOR:
  8682. pot = Tools.FloorPOT(value);
  8683. break;
  8684. case BABYLON.Engine.SCALEMODE_NEAREST:
  8685. pot = Tools.NearestPOT(value);
  8686. break;
  8687. case BABYLON.Engine.SCALEMODE_CEILING:
  8688. default:
  8689. pot = Tools.CeilingPOT(value);
  8690. break;
  8691. }
  8692. return Math.min(pot, max);
  8693. };
  8694. Tools.GetFilename = function (path) {
  8695. var index = path.lastIndexOf("/");
  8696. if (index < 0)
  8697. return path;
  8698. return path.substring(index + 1);
  8699. };
  8700. /**
  8701. * Extracts the "folder" part of a path (everything before the filename).
  8702. * @param uri The URI to extract the info from
  8703. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8704. * @returns The "folder" part of the path
  8705. */
  8706. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8707. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8708. var index = uri.lastIndexOf("/");
  8709. if (index < 0) {
  8710. if (returnUnchangedIfNoSlash) {
  8711. return uri;
  8712. }
  8713. return "";
  8714. }
  8715. return uri.substring(0, index + 1);
  8716. };
  8717. Tools.GetDOMTextContent = function (element) {
  8718. var result = "";
  8719. var child = element.firstChild;
  8720. while (child) {
  8721. if (child.nodeType === 3) {
  8722. result += child.textContent;
  8723. }
  8724. child = child.nextSibling;
  8725. }
  8726. return result;
  8727. };
  8728. Tools.ToDegrees = function (angle) {
  8729. return angle * 180 / Math.PI;
  8730. };
  8731. Tools.ToRadians = function (angle) {
  8732. return angle * Math.PI / 180;
  8733. };
  8734. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8735. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8736. var output = "";
  8737. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8738. var i = 0;
  8739. var bytes = new Uint8Array(buffer);
  8740. while (i < bytes.length) {
  8741. chr1 = bytes[i++];
  8742. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8743. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8744. enc1 = chr1 >> 2;
  8745. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8746. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8747. enc4 = chr3 & 63;
  8748. if (isNaN(chr2)) {
  8749. enc3 = enc4 = 64;
  8750. }
  8751. else if (isNaN(chr3)) {
  8752. enc4 = 64;
  8753. }
  8754. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8755. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8756. }
  8757. return "data:image/png;base64," + output;
  8758. };
  8759. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8760. if (bias === void 0) { bias = null; }
  8761. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8762. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8763. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8764. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8765. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8766. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8767. }
  8768. if (bias) {
  8769. minimum.x -= minimum.x * bias.x + bias.y;
  8770. minimum.y -= minimum.y * bias.x + bias.y;
  8771. minimum.z -= minimum.z * bias.x + bias.y;
  8772. maximum.x += maximum.x * bias.x + bias.y;
  8773. maximum.y += maximum.y * bias.x + bias.y;
  8774. maximum.z += maximum.z * bias.x + bias.y;
  8775. }
  8776. return {
  8777. minimum: minimum,
  8778. maximum: maximum
  8779. };
  8780. };
  8781. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8782. if (bias === void 0) { bias = null; }
  8783. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8784. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8785. if (!stride) {
  8786. stride = 3;
  8787. }
  8788. for (var index = start; index < start + count; index++) {
  8789. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8790. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8791. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8792. }
  8793. if (bias) {
  8794. minimum.x -= minimum.x * bias.x + bias.y;
  8795. minimum.y -= minimum.y * bias.x + bias.y;
  8796. minimum.z -= minimum.z * bias.x + bias.y;
  8797. maximum.x += maximum.x * bias.x + bias.y;
  8798. maximum.y += maximum.y * bias.x + bias.y;
  8799. maximum.z += maximum.z * bias.x + bias.y;
  8800. }
  8801. return {
  8802. minimum: minimum,
  8803. maximum: maximum
  8804. };
  8805. };
  8806. Tools.Vector2ArrayFeeder = function (array) {
  8807. return function (index) {
  8808. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8809. var length = isFloatArray ? array.length / 2 : array.length;
  8810. if (index >= length) {
  8811. return null;
  8812. }
  8813. if (isFloatArray) {
  8814. var fa = array;
  8815. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8816. }
  8817. var a = array;
  8818. return a[index];
  8819. };
  8820. };
  8821. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8822. if (bias === void 0) { bias = null; }
  8823. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8824. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8825. var i = 0;
  8826. var cur = feeder(i++);
  8827. while (cur) {
  8828. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8829. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8830. cur = feeder(i++);
  8831. }
  8832. if (bias) {
  8833. minimum.x -= minimum.x * bias.x + bias.y;
  8834. minimum.y -= minimum.y * bias.x + bias.y;
  8835. maximum.x += maximum.x * bias.x + bias.y;
  8836. maximum.y += maximum.y * bias.x + bias.y;
  8837. }
  8838. return {
  8839. minimum: minimum,
  8840. maximum: maximum
  8841. };
  8842. };
  8843. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8844. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8845. return null;
  8846. return Array.isArray(obj) ? obj : [obj];
  8847. };
  8848. // Misc.
  8849. Tools.GetPointerPrefix = function () {
  8850. var eventPrefix = "pointer";
  8851. // Check if pointer events are supported
  8852. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8853. eventPrefix = "mouse";
  8854. }
  8855. return eventPrefix;
  8856. };
  8857. /**
  8858. * @param func - the function to be called
  8859. * @param requester - the object that will request the next frame. Falls back to window.
  8860. */
  8861. Tools.QueueNewFrame = function (func, requester) {
  8862. if (!Tools.IsWindowObjectExist()) {
  8863. return setTimeout(func, 16);
  8864. }
  8865. if (!requester) {
  8866. requester = window;
  8867. }
  8868. if (requester.requestAnimationFrame) {
  8869. return requester.requestAnimationFrame(func);
  8870. }
  8871. else if (requester.msRequestAnimationFrame) {
  8872. return requester.msRequestAnimationFrame(func);
  8873. }
  8874. else if (requester.webkitRequestAnimationFrame) {
  8875. return requester.webkitRequestAnimationFrame(func);
  8876. }
  8877. else if (requester.mozRequestAnimationFrame) {
  8878. return requester.mozRequestAnimationFrame(func);
  8879. }
  8880. else if (requester.oRequestAnimationFrame) {
  8881. return requester.oRequestAnimationFrame(func);
  8882. }
  8883. else {
  8884. return window.setTimeout(func, 16);
  8885. }
  8886. };
  8887. Tools.RequestFullscreen = function (element) {
  8888. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8889. if (!requestFunction)
  8890. return;
  8891. requestFunction.call(element);
  8892. };
  8893. Tools.ExitFullscreen = function () {
  8894. if (document.exitFullscreen) {
  8895. document.exitFullscreen();
  8896. }
  8897. else if (document.mozCancelFullScreen) {
  8898. document.mozCancelFullScreen();
  8899. }
  8900. else if (document.webkitCancelFullScreen) {
  8901. document.webkitCancelFullScreen();
  8902. }
  8903. else if (document.msCancelFullScreen) {
  8904. document.msCancelFullScreen();
  8905. }
  8906. };
  8907. Tools.SetCorsBehavior = function (url, element) {
  8908. if (url && url.indexOf("data:") === 0) {
  8909. return;
  8910. }
  8911. if (Tools.CorsBehavior) {
  8912. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8913. element.crossOrigin = Tools.CorsBehavior;
  8914. }
  8915. else {
  8916. var result = Tools.CorsBehavior(url);
  8917. if (result) {
  8918. element.crossOrigin = result;
  8919. }
  8920. }
  8921. }
  8922. };
  8923. // External files
  8924. Tools.CleanUrl = function (url) {
  8925. url = url.replace(/#/mg, "%23");
  8926. return url;
  8927. };
  8928. Tools.LoadImage = function (url, onLoad, onError, database) {
  8929. if (url instanceof ArrayBuffer) {
  8930. url = Tools.EncodeArrayBufferTobase64(url);
  8931. }
  8932. url = Tools.CleanUrl(url);
  8933. url = Tools.PreprocessUrl(url);
  8934. var img = new Image();
  8935. Tools.SetCorsBehavior(url, img);
  8936. var loadHandler = function () {
  8937. img.removeEventListener("load", loadHandler);
  8938. img.removeEventListener("error", errorHandler);
  8939. onLoad(img);
  8940. };
  8941. var errorHandler = function (err) {
  8942. img.removeEventListener("load", loadHandler);
  8943. img.removeEventListener("error", errorHandler);
  8944. Tools.Error("Error while trying to load image: " + url);
  8945. if (onError) {
  8946. onError("Error while trying to load image: " + url, err);
  8947. }
  8948. };
  8949. img.addEventListener("load", loadHandler);
  8950. img.addEventListener("error", errorHandler);
  8951. var noIndexedDB = function () {
  8952. img.src = url;
  8953. };
  8954. var loadFromIndexedDB = function () {
  8955. if (database) {
  8956. database.loadImageFromDB(url, img);
  8957. }
  8958. };
  8959. //ANY database to do!
  8960. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8961. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8962. }
  8963. else {
  8964. if (url.indexOf("file:") !== -1) {
  8965. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8966. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8967. try {
  8968. var blobURL;
  8969. try {
  8970. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8971. }
  8972. catch (ex) {
  8973. // Chrome doesn't support oneTimeOnly parameter
  8974. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8975. }
  8976. img.src = blobURL;
  8977. }
  8978. catch (e) {
  8979. img.src = "";
  8980. }
  8981. return img;
  8982. }
  8983. }
  8984. noIndexedDB();
  8985. }
  8986. return img;
  8987. };
  8988. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8989. url = Tools.CleanUrl(url);
  8990. url = Tools.PreprocessUrl(url);
  8991. // If file and file input are set
  8992. if (url.indexOf("file:") !== -1) {
  8993. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8994. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8995. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8996. }
  8997. }
  8998. var loadUrl = Tools.BaseUrl + url;
  8999. var aborted = false;
  9000. var fileRequest = {
  9001. onCompleteObservable: new BABYLON.Observable(),
  9002. abort: function () { return aborted = true; },
  9003. };
  9004. var requestFile = function () {
  9005. var request = new XMLHttpRequest();
  9006. var retryHandle = null;
  9007. fileRequest.abort = function () {
  9008. aborted = true;
  9009. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9010. request.abort();
  9011. }
  9012. if (retryHandle !== null) {
  9013. clearTimeout(retryHandle);
  9014. retryHandle = null;
  9015. }
  9016. };
  9017. var retryLoop = function (retryIndex) {
  9018. request.open('GET', loadUrl, true);
  9019. if (useArrayBuffer) {
  9020. request.responseType = "arraybuffer";
  9021. }
  9022. if (onProgress) {
  9023. request.addEventListener("progress", onProgress);
  9024. }
  9025. var onLoadEnd = function () {
  9026. request.removeEventListener("loadend", onLoadEnd);
  9027. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9028. fileRequest.onCompleteObservable.clear();
  9029. };
  9030. request.addEventListener("loadend", onLoadEnd);
  9031. var onReadyStateChange = function () {
  9032. if (aborted) {
  9033. return;
  9034. }
  9035. // In case of undefined state in some browsers.
  9036. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9037. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9038. request.removeEventListener("readystatechange", onReadyStateChange);
  9039. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9040. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9041. return;
  9042. }
  9043. var retryStrategy = Tools.DefaultRetryStrategy;
  9044. if (retryStrategy) {
  9045. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9046. if (waitTime !== -1) {
  9047. // Prevent the request from completing for retry.
  9048. request.removeEventListener("loadend", onLoadEnd);
  9049. request = new XMLHttpRequest();
  9050. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9051. return;
  9052. }
  9053. }
  9054. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9055. if (onError) {
  9056. onError(request, e);
  9057. }
  9058. else {
  9059. throw e;
  9060. }
  9061. }
  9062. };
  9063. request.addEventListener("readystatechange", onReadyStateChange);
  9064. request.send();
  9065. };
  9066. retryLoop(0);
  9067. };
  9068. // Caching all files
  9069. if (database && database.enableSceneOffline) {
  9070. var noIndexedDB_1 = function () {
  9071. if (!aborted) {
  9072. requestFile();
  9073. }
  9074. };
  9075. var loadFromIndexedDB = function () {
  9076. // TODO: database needs to support aborting and should return a IFileRequest
  9077. if (aborted) {
  9078. return;
  9079. }
  9080. if (database) {
  9081. database.loadFileFromDB(url, function (data) {
  9082. if (!aborted) {
  9083. onSuccess(data);
  9084. }
  9085. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9086. }, onProgress ? function (event) {
  9087. if (!aborted) {
  9088. onProgress(event);
  9089. }
  9090. } : undefined, noIndexedDB_1, useArrayBuffer);
  9091. }
  9092. };
  9093. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9094. }
  9095. else {
  9096. requestFile();
  9097. }
  9098. return fileRequest;
  9099. };
  9100. /**
  9101. * Load a script (identified by an url). When the url returns, the
  9102. * content of this file is added into a new script element, attached to the DOM (body element)
  9103. */
  9104. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9105. var head = document.getElementsByTagName('head')[0];
  9106. var script = document.createElement('script');
  9107. script.type = 'text/javascript';
  9108. script.src = scriptUrl;
  9109. script.onload = function () {
  9110. if (onSuccess) {
  9111. onSuccess();
  9112. }
  9113. };
  9114. script.onerror = function (e) {
  9115. if (onError) {
  9116. onError("Unable to load script '" + scriptUrl + "'", e);
  9117. }
  9118. };
  9119. head.appendChild(script);
  9120. };
  9121. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9122. var reader = new FileReader();
  9123. var request = {
  9124. onCompleteObservable: new BABYLON.Observable(),
  9125. abort: function () { return reader.abort(); },
  9126. };
  9127. reader.onloadend = function (e) {
  9128. request.onCompleteObservable.notifyObservers(request);
  9129. };
  9130. reader.onload = function (e) {
  9131. //target doesn't have result from ts 1.3
  9132. callback(e.target['result']);
  9133. };
  9134. reader.onprogress = progressCallback;
  9135. reader.readAsDataURL(fileToLoad);
  9136. return request;
  9137. };
  9138. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9139. var reader = new FileReader();
  9140. var request = {
  9141. onCompleteObservable: new BABYLON.Observable(),
  9142. abort: function () { return reader.abort(); },
  9143. };
  9144. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9145. reader.onerror = function (e) {
  9146. Tools.Log("Error while reading file: " + fileToLoad.name);
  9147. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9148. };
  9149. reader.onload = function (e) {
  9150. //target doesn't have result from ts 1.3
  9151. callback(e.target['result']);
  9152. };
  9153. if (progressCallBack) {
  9154. reader.onprogress = progressCallBack;
  9155. }
  9156. if (!useArrayBuffer) {
  9157. // Asynchronous read
  9158. reader.readAsText(fileToLoad);
  9159. }
  9160. else {
  9161. reader.readAsArrayBuffer(fileToLoad);
  9162. }
  9163. return request;
  9164. };
  9165. //returns a downloadable url to a file content.
  9166. Tools.FileAsURL = function (content) {
  9167. var fileBlob = new Blob([content]);
  9168. var url = window.URL || window.webkitURL;
  9169. var link = url.createObjectURL(fileBlob);
  9170. return link;
  9171. };
  9172. // Misc.
  9173. Tools.Format = function (value, decimals) {
  9174. if (decimals === void 0) { decimals = 2; }
  9175. return value.toFixed(decimals);
  9176. };
  9177. Tools.CheckExtends = function (v, min, max) {
  9178. if (v.x < min.x)
  9179. min.x = v.x;
  9180. if (v.y < min.y)
  9181. min.y = v.y;
  9182. if (v.z < min.z)
  9183. min.z = v.z;
  9184. if (v.x > max.x)
  9185. max.x = v.x;
  9186. if (v.y > max.y)
  9187. max.y = v.y;
  9188. if (v.z > max.z)
  9189. max.z = v.z;
  9190. };
  9191. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9192. for (var prop in source) {
  9193. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9194. continue;
  9195. }
  9196. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9197. continue;
  9198. }
  9199. var sourceValue = source[prop];
  9200. var typeOfSourceValue = typeof sourceValue;
  9201. if (typeOfSourceValue === "function") {
  9202. continue;
  9203. }
  9204. try {
  9205. if (typeOfSourceValue === "object") {
  9206. if (sourceValue instanceof Array) {
  9207. destination[prop] = [];
  9208. if (sourceValue.length > 0) {
  9209. if (typeof sourceValue[0] == "object") {
  9210. for (var index = 0; index < sourceValue.length; index++) {
  9211. var clonedValue = cloneValue(sourceValue[index], destination);
  9212. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9213. destination[prop].push(clonedValue);
  9214. }
  9215. }
  9216. }
  9217. else {
  9218. destination[prop] = sourceValue.slice(0);
  9219. }
  9220. }
  9221. }
  9222. else {
  9223. destination[prop] = cloneValue(sourceValue, destination);
  9224. }
  9225. }
  9226. else {
  9227. destination[prop] = sourceValue;
  9228. }
  9229. }
  9230. catch (e) {
  9231. // Just ignore error (it could be because of a read-only property)
  9232. }
  9233. }
  9234. };
  9235. Tools.IsEmpty = function (obj) {
  9236. for (var i in obj) {
  9237. if (obj.hasOwnProperty(i)) {
  9238. return false;
  9239. }
  9240. }
  9241. return true;
  9242. };
  9243. Tools.RegisterTopRootEvents = function (events) {
  9244. for (var index = 0; index < events.length; index++) {
  9245. var event = events[index];
  9246. window.addEventListener(event.name, event.handler, false);
  9247. try {
  9248. if (window.parent) {
  9249. window.parent.addEventListener(event.name, event.handler, false);
  9250. }
  9251. }
  9252. catch (e) {
  9253. // Silently fails...
  9254. }
  9255. }
  9256. };
  9257. Tools.UnregisterTopRootEvents = function (events) {
  9258. for (var index = 0; index < events.length; index++) {
  9259. var event = events[index];
  9260. window.removeEventListener(event.name, event.handler);
  9261. try {
  9262. if (window.parent) {
  9263. window.parent.removeEventListener(event.name, event.handler);
  9264. }
  9265. }
  9266. catch (e) {
  9267. // Silently fails...
  9268. }
  9269. }
  9270. };
  9271. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9272. if (mimeType === void 0) { mimeType = "image/png"; }
  9273. // Read the contents of the framebuffer
  9274. var numberOfChannelsByLine = width * 4;
  9275. var halfHeight = height / 2;
  9276. //Reading datas from WebGL
  9277. var data = engine.readPixels(0, 0, width, height);
  9278. //To flip image on Y axis.
  9279. for (var i = 0; i < halfHeight; i++) {
  9280. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9281. var currentCell = j + i * numberOfChannelsByLine;
  9282. var targetLine = height - i - 1;
  9283. var targetCell = j + targetLine * numberOfChannelsByLine;
  9284. var temp = data[currentCell];
  9285. data[currentCell] = data[targetCell];
  9286. data[targetCell] = temp;
  9287. }
  9288. }
  9289. // Create a 2D canvas to store the result
  9290. if (!screenshotCanvas) {
  9291. screenshotCanvas = document.createElement('canvas');
  9292. }
  9293. screenshotCanvas.width = width;
  9294. screenshotCanvas.height = height;
  9295. var context = screenshotCanvas.getContext('2d');
  9296. if (context) {
  9297. // Copy the pixels to a 2D canvas
  9298. var imageData = context.createImageData(width, height);
  9299. var castData = (imageData.data);
  9300. castData.set(data);
  9301. context.putImageData(imageData, 0, 0);
  9302. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9303. }
  9304. };
  9305. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9306. if (mimeType === void 0) { mimeType = "image/png"; }
  9307. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9308. if (successCallback) {
  9309. successCallback(base64Image);
  9310. }
  9311. else {
  9312. // We need HTMLCanvasElement.toBlob for HD screenshots
  9313. if (!screenshotCanvas.toBlob) {
  9314. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9315. screenshotCanvas.toBlob = function (callback, type, quality) {
  9316. var _this = this;
  9317. setTimeout(function () {
  9318. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9319. for (var i = 0; i < len; i++) {
  9320. arr[i] = binStr.charCodeAt(i);
  9321. }
  9322. callback(new Blob([arr], { type: type || 'image/png' }));
  9323. });
  9324. };
  9325. }
  9326. screenshotCanvas.toBlob(function (blob) {
  9327. var url = URL.createObjectURL(blob);
  9328. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9329. if (("download" in document.createElement("a"))) {
  9330. var a = window.document.createElement("a");
  9331. a.href = url;
  9332. if (fileName) {
  9333. a.setAttribute("download", fileName);
  9334. }
  9335. else {
  9336. var date = new Date();
  9337. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9338. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9339. }
  9340. window.document.body.appendChild(a);
  9341. a.addEventListener("click", function () {
  9342. if (a.parentElement) {
  9343. a.parentElement.removeChild(a);
  9344. }
  9345. });
  9346. a.click();
  9347. }
  9348. else {
  9349. var newWindow = window.open("");
  9350. if (!newWindow)
  9351. return;
  9352. var img = newWindow.document.createElement("img");
  9353. img.onload = function () {
  9354. // no longer need to read the blob so it's revoked
  9355. URL.revokeObjectURL(url);
  9356. };
  9357. img.src = url;
  9358. newWindow.document.body.appendChild(img);
  9359. }
  9360. });
  9361. }
  9362. };
  9363. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9364. if (mimeType === void 0) { mimeType = "image/png"; }
  9365. var width;
  9366. var height;
  9367. // If a precision value is specified
  9368. if (size.precision) {
  9369. width = Math.round(engine.getRenderWidth() * size.precision);
  9370. height = Math.round(width / engine.getAspectRatio(camera));
  9371. }
  9372. else if (size.width && size.height) {
  9373. width = size.width;
  9374. height = size.height;
  9375. }
  9376. //If passing only width, computing height to keep display canvas ratio.
  9377. else if (size.width && !size.height) {
  9378. width = size.width;
  9379. height = Math.round(width / engine.getAspectRatio(camera));
  9380. }
  9381. //If passing only height, computing width to keep display canvas ratio.
  9382. else if (size.height && !size.width) {
  9383. height = size.height;
  9384. width = Math.round(height * engine.getAspectRatio(camera));
  9385. }
  9386. //Assuming here that "size" parameter is a number
  9387. else if (!isNaN(size)) {
  9388. height = size;
  9389. width = size;
  9390. }
  9391. else {
  9392. Tools.Error("Invalid 'size' parameter !");
  9393. return;
  9394. }
  9395. if (!screenshotCanvas) {
  9396. screenshotCanvas = document.createElement('canvas');
  9397. }
  9398. screenshotCanvas.width = width;
  9399. screenshotCanvas.height = height;
  9400. var renderContext = screenshotCanvas.getContext("2d");
  9401. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9402. var newWidth = width;
  9403. var newHeight = newWidth / ratio;
  9404. if (newHeight > height) {
  9405. newHeight = height;
  9406. newWidth = newHeight * ratio;
  9407. }
  9408. var offsetX = Math.max(0, width - newWidth) / 2;
  9409. var offsetY = Math.max(0, height - newHeight) / 2;
  9410. var renderingCanvas = engine.getRenderingCanvas();
  9411. if (renderContext && renderingCanvas) {
  9412. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9413. }
  9414. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9415. };
  9416. /**
  9417. * Generates an image screenshot from the specified camera.
  9418. *
  9419. * @param engine The engine to use for rendering
  9420. * @param camera The camera to use for rendering
  9421. * @param size This parameter can be set to a single number or to an object with the
  9422. * following (optional) properties: precision, width, height. If a single number is passed,
  9423. * it will be used for both width and height. If an object is passed, the screenshot size
  9424. * will be derived from the parameters. The precision property is a multiplier allowing
  9425. * rendering at a higher or lower resolution.
  9426. * @param successCallback The callback receives a single parameter which contains the
  9427. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9428. * src parameter of an <img> to display it.
  9429. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9430. * Check your browser for supported MIME types.
  9431. * @param samples Texture samples (default: 1)
  9432. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9433. * @param fileName A name for for the downloaded file.
  9434. * @constructor
  9435. */
  9436. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9437. if (mimeType === void 0) { mimeType = "image/png"; }
  9438. if (samples === void 0) { samples = 1; }
  9439. if (antialiasing === void 0) { antialiasing = false; }
  9440. var width;
  9441. var height;
  9442. //If a precision value is specified
  9443. if (size.precision) {
  9444. width = Math.round(engine.getRenderWidth() * size.precision);
  9445. height = Math.round(width / engine.getAspectRatio(camera));
  9446. size = { width: width, height: height };
  9447. }
  9448. else if (size.width && size.height) {
  9449. width = size.width;
  9450. height = size.height;
  9451. }
  9452. //If passing only width, computing height to keep display canvas ratio.
  9453. else if (size.width && !size.height) {
  9454. width = size.width;
  9455. height = Math.round(width / engine.getAspectRatio(camera));
  9456. size = { width: width, height: height };
  9457. }
  9458. //If passing only height, computing width to keep display canvas ratio.
  9459. else if (size.height && !size.width) {
  9460. height = size.height;
  9461. width = Math.round(height * engine.getAspectRatio(camera));
  9462. size = { width: width, height: height };
  9463. }
  9464. //Assuming here that "size" parameter is a number
  9465. else if (!isNaN(size)) {
  9466. height = size;
  9467. width = size;
  9468. }
  9469. else {
  9470. Tools.Error("Invalid 'size' parameter !");
  9471. return;
  9472. }
  9473. var scene = camera.getScene();
  9474. var previousCamera = null;
  9475. if (scene.activeCamera !== camera) {
  9476. previousCamera = scene.activeCamera;
  9477. scene.activeCamera = camera;
  9478. }
  9479. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9480. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9481. texture.renderList = null;
  9482. texture.samples = samples;
  9483. if (antialiasing) {
  9484. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9485. }
  9486. texture.onAfterRenderObservable.add(function () {
  9487. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9488. });
  9489. scene.incrementRenderId();
  9490. scene.resetCachedMaterial();
  9491. texture.render(true);
  9492. texture.dispose();
  9493. if (previousCamera) {
  9494. scene.activeCamera = previousCamera;
  9495. }
  9496. camera.getProjectionMatrix(true); // Force cache refresh;
  9497. };
  9498. // XHR response validator for local file scenario
  9499. Tools.ValidateXHRData = function (xhr, dataType) {
  9500. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9501. if (dataType === void 0) { dataType = 7; }
  9502. try {
  9503. if (dataType & 1) {
  9504. if (xhr.responseText && xhr.responseText.length > 0) {
  9505. return true;
  9506. }
  9507. else if (dataType === 1) {
  9508. return false;
  9509. }
  9510. }
  9511. if (dataType & 2) {
  9512. // Check header width and height since there is no "TGA" magic number
  9513. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9514. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9515. return true;
  9516. }
  9517. else if (dataType === 2) {
  9518. return false;
  9519. }
  9520. }
  9521. if (dataType & 4) {
  9522. // Check for the "DDS" magic number
  9523. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9524. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9525. return true;
  9526. }
  9527. else {
  9528. return false;
  9529. }
  9530. }
  9531. }
  9532. catch (e) {
  9533. // Global protection
  9534. }
  9535. return false;
  9536. };
  9537. /**
  9538. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9539. * Be aware Math.random() could cause collisions, but:
  9540. * "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"
  9541. */
  9542. Tools.RandomId = function () {
  9543. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9544. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9545. return v.toString(16);
  9546. });
  9547. };
  9548. /**
  9549. * Test if the given uri is a base64 string.
  9550. * @param uri The uri to test
  9551. * @return True if the uri is a base64 string or false otherwise.
  9552. */
  9553. Tools.IsBase64 = function (uri) {
  9554. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9555. };
  9556. /**
  9557. * Decode the given base64 uri.
  9558. * @param uri The uri to decode
  9559. * @return The decoded base64 data.
  9560. */
  9561. Tools.DecodeBase64 = function (uri) {
  9562. var decodedString = atob(uri.split(",")[1]);
  9563. var bufferLength = decodedString.length;
  9564. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9565. for (var i = 0; i < bufferLength; i++) {
  9566. bufferView[i] = decodedString.charCodeAt(i);
  9567. }
  9568. return bufferView.buffer;
  9569. };
  9570. Object.defineProperty(Tools, "NoneLogLevel", {
  9571. get: function () {
  9572. return Tools._NoneLogLevel;
  9573. },
  9574. enumerable: true,
  9575. configurable: true
  9576. });
  9577. Object.defineProperty(Tools, "MessageLogLevel", {
  9578. get: function () {
  9579. return Tools._MessageLogLevel;
  9580. },
  9581. enumerable: true,
  9582. configurable: true
  9583. });
  9584. Object.defineProperty(Tools, "WarningLogLevel", {
  9585. get: function () {
  9586. return Tools._WarningLogLevel;
  9587. },
  9588. enumerable: true,
  9589. configurable: true
  9590. });
  9591. Object.defineProperty(Tools, "ErrorLogLevel", {
  9592. get: function () {
  9593. return Tools._ErrorLogLevel;
  9594. },
  9595. enumerable: true,
  9596. configurable: true
  9597. });
  9598. Object.defineProperty(Tools, "AllLogLevel", {
  9599. get: function () {
  9600. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9601. },
  9602. enumerable: true,
  9603. configurable: true
  9604. });
  9605. Tools._AddLogEntry = function (entry) {
  9606. Tools._LogCache = entry + Tools._LogCache;
  9607. if (Tools.OnNewCacheEntry) {
  9608. Tools.OnNewCacheEntry(entry);
  9609. }
  9610. };
  9611. Tools._FormatMessage = function (message) {
  9612. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9613. var date = new Date();
  9614. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9615. };
  9616. Tools._LogDisabled = function (message) {
  9617. // nothing to do
  9618. };
  9619. Tools._LogEnabled = function (message) {
  9620. var formattedMessage = Tools._FormatMessage(message);
  9621. console.log("BJS - " + formattedMessage);
  9622. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9623. Tools._AddLogEntry(entry);
  9624. };
  9625. Tools._WarnDisabled = function (message) {
  9626. // nothing to do
  9627. };
  9628. Tools._WarnEnabled = function (message) {
  9629. var formattedMessage = Tools._FormatMessage(message);
  9630. console.warn("BJS - " + formattedMessage);
  9631. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9632. Tools._AddLogEntry(entry);
  9633. };
  9634. Tools._ErrorDisabled = function (message) {
  9635. // nothing to do
  9636. };
  9637. Tools._ErrorEnabled = function (message) {
  9638. Tools.errorsCount++;
  9639. var formattedMessage = Tools._FormatMessage(message);
  9640. console.error("BJS - " + formattedMessage);
  9641. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9642. Tools._AddLogEntry(entry);
  9643. };
  9644. Object.defineProperty(Tools, "LogCache", {
  9645. get: function () {
  9646. return Tools._LogCache;
  9647. },
  9648. enumerable: true,
  9649. configurable: true
  9650. });
  9651. Tools.ClearLogCache = function () {
  9652. Tools._LogCache = "";
  9653. Tools.errorsCount = 0;
  9654. };
  9655. Object.defineProperty(Tools, "LogLevels", {
  9656. set: function (level) {
  9657. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9658. Tools.Log = Tools._LogEnabled;
  9659. }
  9660. else {
  9661. Tools.Log = Tools._LogDisabled;
  9662. }
  9663. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9664. Tools.Warn = Tools._WarnEnabled;
  9665. }
  9666. else {
  9667. Tools.Warn = Tools._WarnDisabled;
  9668. }
  9669. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9670. Tools.Error = Tools._ErrorEnabled;
  9671. }
  9672. else {
  9673. Tools.Error = Tools._ErrorDisabled;
  9674. }
  9675. },
  9676. enumerable: true,
  9677. configurable: true
  9678. });
  9679. Tools.IsWindowObjectExist = function () {
  9680. return (typeof window) !== "undefined";
  9681. };
  9682. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9683. get: function () {
  9684. return Tools._PerformanceNoneLogLevel;
  9685. },
  9686. enumerable: true,
  9687. configurable: true
  9688. });
  9689. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9690. get: function () {
  9691. return Tools._PerformanceUserMarkLogLevel;
  9692. },
  9693. enumerable: true,
  9694. configurable: true
  9695. });
  9696. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9697. get: function () {
  9698. return Tools._PerformanceConsoleLogLevel;
  9699. },
  9700. enumerable: true,
  9701. configurable: true
  9702. });
  9703. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9704. set: function (level) {
  9705. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9706. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9707. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9708. return;
  9709. }
  9710. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9711. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9712. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9713. return;
  9714. }
  9715. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9716. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9717. },
  9718. enumerable: true,
  9719. configurable: true
  9720. });
  9721. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9722. };
  9723. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9724. };
  9725. Tools._StartUserMark = function (counterName, condition) {
  9726. if (condition === void 0) { condition = true; }
  9727. if (!Tools._performance) {
  9728. if (!Tools.IsWindowObjectExist()) {
  9729. return;
  9730. }
  9731. Tools._performance = window.performance;
  9732. }
  9733. if (!condition || !Tools._performance.mark) {
  9734. return;
  9735. }
  9736. Tools._performance.mark(counterName + "-Begin");
  9737. };
  9738. Tools._EndUserMark = function (counterName, condition) {
  9739. if (condition === void 0) { condition = true; }
  9740. if (!condition || !Tools._performance.mark) {
  9741. return;
  9742. }
  9743. Tools._performance.mark(counterName + "-End");
  9744. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9745. };
  9746. Tools._StartPerformanceConsole = function (counterName, condition) {
  9747. if (condition === void 0) { condition = true; }
  9748. if (!condition) {
  9749. return;
  9750. }
  9751. Tools._StartUserMark(counterName, condition);
  9752. if (console.time) {
  9753. console.time(counterName);
  9754. }
  9755. };
  9756. Tools._EndPerformanceConsole = function (counterName, condition) {
  9757. if (condition === void 0) { condition = true; }
  9758. if (!condition) {
  9759. return;
  9760. }
  9761. Tools._EndUserMark(counterName, condition);
  9762. if (console.time) {
  9763. console.timeEnd(counterName);
  9764. }
  9765. };
  9766. Object.defineProperty(Tools, "Now", {
  9767. get: function () {
  9768. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9769. return window.performance.now();
  9770. }
  9771. return Date.now();
  9772. },
  9773. enumerable: true,
  9774. configurable: true
  9775. });
  9776. /**
  9777. * This method will return the name of the class used to create the instance of the given object.
  9778. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9779. * @param object the object to get the class name from
  9780. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9781. */
  9782. Tools.GetClassName = function (object, isType) {
  9783. if (isType === void 0) { isType = false; }
  9784. var name = null;
  9785. if (!isType && object.getClassName) {
  9786. name = object.getClassName();
  9787. }
  9788. else {
  9789. if (object instanceof Object) {
  9790. var classObj = isType ? object : Object.getPrototypeOf(object);
  9791. name = classObj.constructor["__bjsclassName__"];
  9792. }
  9793. if (!name) {
  9794. name = typeof object;
  9795. }
  9796. }
  9797. return name;
  9798. };
  9799. Tools.First = function (array, predicate) {
  9800. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9801. var el = array_1[_i];
  9802. if (predicate(el)) {
  9803. return el;
  9804. }
  9805. }
  9806. return null;
  9807. };
  9808. /**
  9809. * This method will return the name of the full name of the class, including its owning module (if any).
  9810. * 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).
  9811. * @param object the object to get the class name from
  9812. * @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.
  9813. */
  9814. Tools.getFullClassName = function (object, isType) {
  9815. if (isType === void 0) { isType = false; }
  9816. var className = null;
  9817. var moduleName = null;
  9818. if (!isType && object.getClassName) {
  9819. className = object.getClassName();
  9820. }
  9821. else {
  9822. if (object instanceof Object) {
  9823. var classObj = isType ? object : Object.getPrototypeOf(object);
  9824. className = classObj.constructor["__bjsclassName__"];
  9825. moduleName = classObj.constructor["__bjsmoduleName__"];
  9826. }
  9827. if (!className) {
  9828. className = typeof object;
  9829. }
  9830. }
  9831. if (!className) {
  9832. return null;
  9833. }
  9834. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9835. };
  9836. /**
  9837. * 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.
  9838. * @param array
  9839. */
  9840. Tools.arrayOrStringFeeder = function (array) {
  9841. return function (index) {
  9842. if (index >= array.length) {
  9843. return null;
  9844. }
  9845. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9846. if (val && val.getHashCode) {
  9847. val = val.getHashCode();
  9848. }
  9849. if (typeof val === "string") {
  9850. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9851. }
  9852. return val;
  9853. };
  9854. };
  9855. /**
  9856. * Compute the hashCode of a stream of number
  9857. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9858. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9859. * @return the hash code computed
  9860. */
  9861. Tools.hashCodeFromStream = function (feeder) {
  9862. // Based from here: http://stackoverflow.com/a/7616484/802124
  9863. var hash = 0;
  9864. var index = 0;
  9865. var chr = feeder(index++);
  9866. while (chr != null) {
  9867. hash = ((hash << 5) - hash) + chr;
  9868. hash |= 0; // Convert to 32bit integer
  9869. chr = feeder(index++);
  9870. }
  9871. return hash;
  9872. };
  9873. /**
  9874. * Returns a promise that resolves after the given amount of time.
  9875. * @param delay Number of milliseconds to delay
  9876. * @returns Promise that resolves after the given amount of time
  9877. */
  9878. Tools.DelayAsync = function (delay) {
  9879. return new Promise(function (resolve) {
  9880. setTimeout(function () {
  9881. resolve();
  9882. }, delay);
  9883. });
  9884. };
  9885. Tools.BaseUrl = "";
  9886. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9887. /**
  9888. * Default behaviour for cors in the application.
  9889. * It can be a string if the expected behavior is identical in the entire app.
  9890. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9891. */
  9892. Tools.CorsBehavior = "anonymous";
  9893. Tools.UseFallbackTexture = true;
  9894. /**
  9895. * Use this object to register external classes like custom textures or material
  9896. * to allow the laoders to instantiate them
  9897. */
  9898. Tools.RegisteredExternalClasses = {};
  9899. // Used in case of a texture loading problem
  9900. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  9901. Tools._tmpFloatArray = new Float32Array(1);
  9902. Tools.PreprocessUrl = function (url) {
  9903. return url;
  9904. };
  9905. // Logs
  9906. Tools._NoneLogLevel = 0;
  9907. Tools._MessageLogLevel = 1;
  9908. Tools._WarningLogLevel = 2;
  9909. Tools._ErrorLogLevel = 4;
  9910. Tools._LogCache = "";
  9911. Tools.errorsCount = 0;
  9912. Tools.Log = Tools._LogEnabled;
  9913. Tools.Warn = Tools._WarnEnabled;
  9914. Tools.Error = Tools._ErrorEnabled;
  9915. // Performances
  9916. Tools._PerformanceNoneLogLevel = 0;
  9917. Tools._PerformanceUserMarkLogLevel = 1;
  9918. Tools._PerformanceConsoleLogLevel = 2;
  9919. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9920. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9921. return Tools;
  9922. }());
  9923. BABYLON.Tools = Tools;
  9924. /**
  9925. * This class is used to track a performance counter which is number based.
  9926. * The user has access to many properties which give statistics of different nature
  9927. *
  9928. * The implementer can track two kinds of Performance Counter: time and count
  9929. * 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.
  9930. * 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.
  9931. */
  9932. var PerfCounter = /** @class */ (function () {
  9933. function PerfCounter() {
  9934. this._startMonitoringTime = 0;
  9935. this._min = 0;
  9936. this._max = 0;
  9937. this._average = 0;
  9938. this._lastSecAverage = 0;
  9939. this._current = 0;
  9940. this._totalValueCount = 0;
  9941. this._totalAccumulated = 0;
  9942. this._lastSecAccumulated = 0;
  9943. this._lastSecTime = 0;
  9944. this._lastSecValueCount = 0;
  9945. }
  9946. Object.defineProperty(PerfCounter.prototype, "min", {
  9947. /**
  9948. * Returns the smallest value ever
  9949. */
  9950. get: function () {
  9951. return this._min;
  9952. },
  9953. enumerable: true,
  9954. configurable: true
  9955. });
  9956. Object.defineProperty(PerfCounter.prototype, "max", {
  9957. /**
  9958. * Returns the biggest value ever
  9959. */
  9960. get: function () {
  9961. return this._max;
  9962. },
  9963. enumerable: true,
  9964. configurable: true
  9965. });
  9966. Object.defineProperty(PerfCounter.prototype, "average", {
  9967. /**
  9968. * Returns the average value since the performance counter is running
  9969. */
  9970. get: function () {
  9971. return this._average;
  9972. },
  9973. enumerable: true,
  9974. configurable: true
  9975. });
  9976. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9977. /**
  9978. * Returns the average value of the last second the counter was monitored
  9979. */
  9980. get: function () {
  9981. return this._lastSecAverage;
  9982. },
  9983. enumerable: true,
  9984. configurable: true
  9985. });
  9986. Object.defineProperty(PerfCounter.prototype, "current", {
  9987. /**
  9988. * Returns the current value
  9989. */
  9990. get: function () {
  9991. return this._current;
  9992. },
  9993. enumerable: true,
  9994. configurable: true
  9995. });
  9996. Object.defineProperty(PerfCounter.prototype, "total", {
  9997. get: function () {
  9998. return this._totalAccumulated;
  9999. },
  10000. enumerable: true,
  10001. configurable: true
  10002. });
  10003. Object.defineProperty(PerfCounter.prototype, "count", {
  10004. get: function () {
  10005. return this._totalValueCount;
  10006. },
  10007. enumerable: true,
  10008. configurable: true
  10009. });
  10010. /**
  10011. * Call this method to start monitoring a new frame.
  10012. * 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.
  10013. */
  10014. PerfCounter.prototype.fetchNewFrame = function () {
  10015. this._totalValueCount++;
  10016. this._current = 0;
  10017. this._lastSecValueCount++;
  10018. };
  10019. /**
  10020. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10021. * @param newCount the count value to add to the monitored count
  10022. * @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.
  10023. */
  10024. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10025. if (!PerfCounter.Enabled) {
  10026. return;
  10027. }
  10028. this._current += newCount;
  10029. if (fetchResult) {
  10030. this._fetchResult();
  10031. }
  10032. };
  10033. /**
  10034. * Start monitoring this performance counter
  10035. */
  10036. PerfCounter.prototype.beginMonitoring = function () {
  10037. if (!PerfCounter.Enabled) {
  10038. return;
  10039. }
  10040. this._startMonitoringTime = Tools.Now;
  10041. };
  10042. /**
  10043. * Compute the time lapsed since the previous beginMonitoring() call.
  10044. * @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
  10045. */
  10046. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10047. if (newFrame === void 0) { newFrame = true; }
  10048. if (!PerfCounter.Enabled) {
  10049. return;
  10050. }
  10051. if (newFrame) {
  10052. this.fetchNewFrame();
  10053. }
  10054. var currentTime = Tools.Now;
  10055. this._current = currentTime - this._startMonitoringTime;
  10056. if (newFrame) {
  10057. this._fetchResult();
  10058. }
  10059. };
  10060. PerfCounter.prototype._fetchResult = function () {
  10061. this._totalAccumulated += this._current;
  10062. this._lastSecAccumulated += this._current;
  10063. // Min/Max update
  10064. this._min = Math.min(this._min, this._current);
  10065. this._max = Math.max(this._max, this._current);
  10066. this._average = this._totalAccumulated / this._totalValueCount;
  10067. // Reset last sec?
  10068. var now = Tools.Now;
  10069. if ((now - this._lastSecTime) > 1000) {
  10070. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10071. this._lastSecTime = now;
  10072. this._lastSecAccumulated = 0;
  10073. this._lastSecValueCount = 0;
  10074. }
  10075. };
  10076. PerfCounter.Enabled = true;
  10077. return PerfCounter;
  10078. }());
  10079. BABYLON.PerfCounter = PerfCounter;
  10080. /**
  10081. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10082. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10083. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10084. * @param name The name of the class, case should be preserved
  10085. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10086. */
  10087. function className(name, module) {
  10088. return function (target) {
  10089. target["__bjsclassName__"] = name;
  10090. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10091. };
  10092. }
  10093. BABYLON.className = className;
  10094. /**
  10095. * An implementation of a loop for asynchronous functions.
  10096. */
  10097. var AsyncLoop = /** @class */ (function () {
  10098. /**
  10099. * Constroctor.
  10100. * @param iterations the number of iterations.
  10101. * @param _fn the function to run each iteration
  10102. * @param _successCallback the callback that will be called upon succesful execution
  10103. * @param offset starting offset.
  10104. */
  10105. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10106. if (offset === void 0) { offset = 0; }
  10107. this.iterations = iterations;
  10108. this._fn = _fn;
  10109. this._successCallback = _successCallback;
  10110. this.index = offset - 1;
  10111. this._done = false;
  10112. }
  10113. /**
  10114. * Execute the next iteration. Must be called after the last iteration was finished.
  10115. */
  10116. AsyncLoop.prototype.executeNext = function () {
  10117. if (!this._done) {
  10118. if (this.index + 1 < this.iterations) {
  10119. ++this.index;
  10120. this._fn(this);
  10121. }
  10122. else {
  10123. this.breakLoop();
  10124. }
  10125. }
  10126. };
  10127. /**
  10128. * Break the loop and run the success callback.
  10129. */
  10130. AsyncLoop.prototype.breakLoop = function () {
  10131. this._done = true;
  10132. this._successCallback();
  10133. };
  10134. /**
  10135. * Helper function
  10136. */
  10137. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10138. if (offset === void 0) { offset = 0; }
  10139. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10140. loop.executeNext();
  10141. return loop;
  10142. };
  10143. /**
  10144. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10145. * @param iterations total number of iterations
  10146. * @param syncedIterations number of synchronous iterations in each async iteration.
  10147. * @param fn the function to call each iteration.
  10148. * @param callback a success call back that will be called when iterating stops.
  10149. * @param breakFunction a break condition (optional)
  10150. * @param timeout timeout settings for the setTimeout function. default - 0.
  10151. * @constructor
  10152. */
  10153. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10154. if (timeout === void 0) { timeout = 0; }
  10155. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10156. if (breakFunction && breakFunction())
  10157. loop.breakLoop();
  10158. else {
  10159. setTimeout(function () {
  10160. for (var i = 0; i < syncedIterations; ++i) {
  10161. var iteration = (loop.index * syncedIterations) + i;
  10162. if (iteration >= iterations)
  10163. break;
  10164. fn(iteration);
  10165. if (breakFunction && breakFunction()) {
  10166. loop.breakLoop();
  10167. break;
  10168. }
  10169. }
  10170. loop.executeNext();
  10171. }, timeout);
  10172. }
  10173. }, callback);
  10174. };
  10175. return AsyncLoop;
  10176. }());
  10177. BABYLON.AsyncLoop = AsyncLoop;
  10178. })(BABYLON || (BABYLON = {}));
  10179. //# sourceMappingURL=babylon.tools.js.map
  10180. var BABYLON;
  10181. (function (BABYLON) {
  10182. var PromiseStates;
  10183. (function (PromiseStates) {
  10184. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10185. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10186. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10187. })(PromiseStates || (PromiseStates = {}));
  10188. var FulFillmentAgregator = /** @class */ (function () {
  10189. function FulFillmentAgregator() {
  10190. this.count = 0;
  10191. this.target = 0;
  10192. this.results = [];
  10193. }
  10194. return FulFillmentAgregator;
  10195. }());
  10196. var InternalPromise = /** @class */ (function () {
  10197. function InternalPromise(resolver) {
  10198. var _this = this;
  10199. this._state = PromiseStates.Pending;
  10200. this._children = new Array();
  10201. this._rejectWasConsumed = false;
  10202. if (!resolver) {
  10203. return;
  10204. }
  10205. try {
  10206. resolver(function (value) {
  10207. _this._resolve(value);
  10208. }, function (reason) {
  10209. _this._reject(reason);
  10210. });
  10211. }
  10212. catch (e) {
  10213. this._reject(e);
  10214. }
  10215. }
  10216. Object.defineProperty(InternalPromise.prototype, "_result", {
  10217. get: function () {
  10218. return this._resultValue;
  10219. },
  10220. set: function (value) {
  10221. this._resultValue = value;
  10222. if (this._parent && this._parent._result === undefined) {
  10223. this._parent._result = value;
  10224. }
  10225. },
  10226. enumerable: true,
  10227. configurable: true
  10228. });
  10229. InternalPromise.prototype.catch = function (onRejected) {
  10230. return this.then(undefined, onRejected);
  10231. };
  10232. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10233. var _this = this;
  10234. var newPromise = new InternalPromise();
  10235. newPromise._onFulfilled = onFulfilled;
  10236. newPromise._onRejected = onRejected;
  10237. // Composition
  10238. this._children.push(newPromise);
  10239. newPromise._parent = this;
  10240. if (this._state !== PromiseStates.Pending) {
  10241. BABYLON.Tools.SetImmediate(function () {
  10242. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10243. var returnedValue = newPromise._resolve(_this._result);
  10244. if (returnedValue !== undefined && returnedValue !== null) {
  10245. if (returnedValue._state !== undefined) {
  10246. var returnedPromise = returnedValue;
  10247. newPromise._children.push(returnedPromise);
  10248. returnedPromise._parent = newPromise;
  10249. newPromise = returnedPromise;
  10250. }
  10251. else {
  10252. newPromise._result = returnedValue;
  10253. }
  10254. }
  10255. }
  10256. else {
  10257. newPromise._reject(_this._reason);
  10258. }
  10259. });
  10260. }
  10261. return newPromise;
  10262. };
  10263. InternalPromise.prototype._moveChildren = function (children) {
  10264. var _this = this;
  10265. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10266. this._children.forEach(function (child) {
  10267. child._parent = _this;
  10268. });
  10269. if (this._state === PromiseStates.Fulfilled) {
  10270. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10271. var child = _b[_i];
  10272. child._resolve(this._result);
  10273. }
  10274. }
  10275. else if (this._state === PromiseStates.Rejected) {
  10276. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10277. var child = _d[_c];
  10278. child._reject(this._reason);
  10279. }
  10280. }
  10281. var _a;
  10282. };
  10283. InternalPromise.prototype._resolve = function (value) {
  10284. try {
  10285. this._state = PromiseStates.Fulfilled;
  10286. var returnedValue = null;
  10287. if (this._onFulfilled) {
  10288. returnedValue = this._onFulfilled(value);
  10289. }
  10290. if (returnedValue !== undefined && returnedValue !== null) {
  10291. if (returnedValue._state !== undefined) {
  10292. // Transmit children
  10293. var returnedPromise = returnedValue;
  10294. returnedPromise._parent = this;
  10295. returnedPromise._moveChildren(this._children);
  10296. value = returnedPromise._result;
  10297. }
  10298. else {
  10299. value = returnedValue;
  10300. }
  10301. }
  10302. this._result = value;
  10303. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10304. var child = _a[_i];
  10305. child._resolve(value);
  10306. }
  10307. this._children.length = 0;
  10308. delete this._onFulfilled;
  10309. delete this._onRejected;
  10310. }
  10311. catch (e) {
  10312. this._reject(e, true);
  10313. }
  10314. };
  10315. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10316. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10317. this._state = PromiseStates.Rejected;
  10318. this._reason = reason;
  10319. if (this._onRejected && !onLocalThrow) {
  10320. try {
  10321. this._onRejected(reason);
  10322. this._rejectWasConsumed = true;
  10323. }
  10324. catch (e) {
  10325. reason = e;
  10326. }
  10327. }
  10328. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10329. var child = _a[_i];
  10330. if (this._rejectWasConsumed) {
  10331. child._resolve(null);
  10332. }
  10333. else {
  10334. child._reject(reason);
  10335. }
  10336. }
  10337. this._children.length = 0;
  10338. delete this._onFulfilled;
  10339. delete this._onRejected;
  10340. };
  10341. InternalPromise.resolve = function (value) {
  10342. var newPromise = new InternalPromise();
  10343. newPromise._resolve(value);
  10344. return newPromise;
  10345. };
  10346. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10347. promise.then(function (value) {
  10348. agregator.results[index] = value;
  10349. agregator.count++;
  10350. if (agregator.count === agregator.target) {
  10351. agregator.rootPromise._resolve(agregator.results);
  10352. }
  10353. return null;
  10354. }, function (reason) {
  10355. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10356. agregator.rootPromise._reject(reason);
  10357. }
  10358. });
  10359. };
  10360. InternalPromise.all = function (promises) {
  10361. var newPromise = new InternalPromise();
  10362. var agregator = new FulFillmentAgregator();
  10363. agregator.target = promises.length;
  10364. agregator.rootPromise = newPromise;
  10365. if (promises.length) {
  10366. for (var index = 0; index < promises.length; index++) {
  10367. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10368. }
  10369. }
  10370. else {
  10371. newPromise._resolve([]);
  10372. }
  10373. return newPromise;
  10374. };
  10375. InternalPromise.race = function (promises) {
  10376. var newPromise = new InternalPromise();
  10377. if (promises.length) {
  10378. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10379. var promise = promises_1[_i];
  10380. promise.then(function (value) {
  10381. if (newPromise) {
  10382. newPromise._resolve(value);
  10383. newPromise = null;
  10384. }
  10385. return null;
  10386. }, function (reason) {
  10387. if (newPromise) {
  10388. newPromise._reject(reason);
  10389. newPromise = null;
  10390. }
  10391. });
  10392. }
  10393. }
  10394. return newPromise;
  10395. };
  10396. return InternalPromise;
  10397. }());
  10398. /**
  10399. * Helper class that provides a small promise polyfill
  10400. */
  10401. var PromisePolyfill = /** @class */ (function () {
  10402. function PromisePolyfill() {
  10403. }
  10404. /**
  10405. * Static function used to check if the polyfill is required
  10406. * If this is the case then the function will inject the polyfill to window.Promise
  10407. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10408. */
  10409. PromisePolyfill.Apply = function (force) {
  10410. if (force === void 0) { force = false; }
  10411. if (force || typeof Promise === 'undefined') {
  10412. var root = window;
  10413. root.Promise = InternalPromise;
  10414. }
  10415. };
  10416. return PromisePolyfill;
  10417. }());
  10418. BABYLON.PromisePolyfill = PromisePolyfill;
  10419. })(BABYLON || (BABYLON = {}));
  10420. //# sourceMappingURL=babylon.promise.js.map
  10421. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10422. var BABYLON;
  10423. (function (BABYLON) {
  10424. /**
  10425. * Helper class to push actions to a pool of workers.
  10426. */
  10427. var WorkerPool = /** @class */ (function () {
  10428. /**
  10429. * Constructor
  10430. * @param workers Array of workers to use for actions
  10431. */
  10432. function WorkerPool(workers) {
  10433. this._pendingActions = new Array();
  10434. this._workerInfos = workers.map(function (worker) { return ({
  10435. worker: worker,
  10436. active: false
  10437. }); });
  10438. }
  10439. /**
  10440. * Terminates all workers and clears any pending actions.
  10441. */
  10442. WorkerPool.prototype.dispose = function () {
  10443. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10444. var workerInfo = _a[_i];
  10445. workerInfo.worker.terminate();
  10446. }
  10447. delete this._workerInfos;
  10448. delete this._pendingActions;
  10449. };
  10450. /**
  10451. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10452. * pended until a worker has completed its action.
  10453. * @param action The action to perform. Call onComplete when the action is complete.
  10454. */
  10455. WorkerPool.prototype.push = function (action) {
  10456. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10457. var workerInfo = _a[_i];
  10458. if (!workerInfo.active) {
  10459. this._execute(workerInfo, action);
  10460. return;
  10461. }
  10462. }
  10463. this._pendingActions.push(action);
  10464. };
  10465. WorkerPool.prototype._execute = function (workerInfo, action) {
  10466. var _this = this;
  10467. workerInfo.active = true;
  10468. action(workerInfo.worker, function () {
  10469. workerInfo.active = false;
  10470. var nextAction = _this._pendingActions.shift();
  10471. if (nextAction) {
  10472. _this._execute(workerInfo, nextAction);
  10473. }
  10474. });
  10475. };
  10476. return WorkerPool;
  10477. }());
  10478. BABYLON.WorkerPool = WorkerPool;
  10479. })(BABYLON || (BABYLON = {}));
  10480. //# sourceMappingURL=babylon.workerPool.js.map
  10481. var BABYLON;
  10482. (function (BABYLON) {
  10483. /**
  10484. * @hidden
  10485. **/
  10486. var _AlphaState = /** @class */ (function () {
  10487. /**
  10488. * Initializes the state.
  10489. */
  10490. function _AlphaState() {
  10491. this._isAlphaBlendDirty = false;
  10492. this._isBlendFunctionParametersDirty = false;
  10493. this._isBlendEquationParametersDirty = false;
  10494. this._isBlendConstantsDirty = false;
  10495. this._alphaBlend = false;
  10496. this._blendFunctionParameters = new Array(4);
  10497. this._blendEquationParameters = new Array(2);
  10498. this._blendConstants = new Array(4);
  10499. this.reset();
  10500. }
  10501. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10502. get: function () {
  10503. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10504. },
  10505. enumerable: true,
  10506. configurable: true
  10507. });
  10508. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10509. get: function () {
  10510. return this._alphaBlend;
  10511. },
  10512. set: function (value) {
  10513. if (this._alphaBlend === value) {
  10514. return;
  10515. }
  10516. this._alphaBlend = value;
  10517. this._isAlphaBlendDirty = true;
  10518. },
  10519. enumerable: true,
  10520. configurable: true
  10521. });
  10522. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10523. if (this._blendConstants[0] === r &&
  10524. this._blendConstants[1] === g &&
  10525. this._blendConstants[2] === b &&
  10526. this._blendConstants[3] === a) {
  10527. return;
  10528. }
  10529. this._blendConstants[0] = r;
  10530. this._blendConstants[1] = g;
  10531. this._blendConstants[2] = b;
  10532. this._blendConstants[3] = a;
  10533. this._isBlendConstantsDirty = true;
  10534. };
  10535. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10536. if (this._blendFunctionParameters[0] === value0 &&
  10537. this._blendFunctionParameters[1] === value1 &&
  10538. this._blendFunctionParameters[2] === value2 &&
  10539. this._blendFunctionParameters[3] === value3) {
  10540. return;
  10541. }
  10542. this._blendFunctionParameters[0] = value0;
  10543. this._blendFunctionParameters[1] = value1;
  10544. this._blendFunctionParameters[2] = value2;
  10545. this._blendFunctionParameters[3] = value3;
  10546. this._isBlendFunctionParametersDirty = true;
  10547. };
  10548. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10549. if (this._blendEquationParameters[0] === rgb &&
  10550. this._blendEquationParameters[1] === alpha) {
  10551. return;
  10552. }
  10553. this._blendEquationParameters[0] = rgb;
  10554. this._blendEquationParameters[1] = alpha;
  10555. this._isBlendEquationParametersDirty = true;
  10556. };
  10557. _AlphaState.prototype.reset = function () {
  10558. this._alphaBlend = false;
  10559. this._blendFunctionParameters[0] = null;
  10560. this._blendFunctionParameters[1] = null;
  10561. this._blendFunctionParameters[2] = null;
  10562. this._blendFunctionParameters[3] = null;
  10563. this._blendEquationParameters[0] = null;
  10564. this._blendEquationParameters[1] = null;
  10565. this._blendConstants[0] = null;
  10566. this._blendConstants[1] = null;
  10567. this._blendConstants[2] = null;
  10568. this._blendConstants[3] = null;
  10569. this._isAlphaBlendDirty = true;
  10570. this._isBlendFunctionParametersDirty = false;
  10571. this._isBlendEquationParametersDirty = false;
  10572. this._isBlendConstantsDirty = false;
  10573. };
  10574. _AlphaState.prototype.apply = function (gl) {
  10575. if (!this.isDirty) {
  10576. return;
  10577. }
  10578. // Alpha blend
  10579. if (this._isAlphaBlendDirty) {
  10580. if (this._alphaBlend) {
  10581. gl.enable(gl.BLEND);
  10582. }
  10583. else {
  10584. gl.disable(gl.BLEND);
  10585. }
  10586. this._isAlphaBlendDirty = false;
  10587. }
  10588. // Alpha function
  10589. if (this._isBlendFunctionParametersDirty) {
  10590. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10591. this._isBlendFunctionParametersDirty = false;
  10592. }
  10593. // Alpha equation
  10594. if (this._isBlendEquationParametersDirty) {
  10595. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10596. this._isBlendEquationParametersDirty = false;
  10597. }
  10598. // Constants
  10599. if (this._isBlendConstantsDirty) {
  10600. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10601. this._isBlendConstantsDirty = false;
  10602. }
  10603. };
  10604. return _AlphaState;
  10605. }());
  10606. BABYLON._AlphaState = _AlphaState;
  10607. })(BABYLON || (BABYLON = {}));
  10608. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10609. var BABYLON;
  10610. (function (BABYLON) {
  10611. /**
  10612. * @hidden
  10613. **/
  10614. var _DepthCullingState = /** @class */ (function () {
  10615. /**
  10616. * Initializes the state.
  10617. */
  10618. function _DepthCullingState() {
  10619. this._isDepthTestDirty = false;
  10620. this._isDepthMaskDirty = false;
  10621. this._isDepthFuncDirty = false;
  10622. this._isCullFaceDirty = false;
  10623. this._isCullDirty = false;
  10624. this._isZOffsetDirty = false;
  10625. this._isFrontFaceDirty = false;
  10626. this.reset();
  10627. }
  10628. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10629. get: function () {
  10630. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10631. },
  10632. enumerable: true,
  10633. configurable: true
  10634. });
  10635. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10636. get: function () {
  10637. return this._zOffset;
  10638. },
  10639. set: function (value) {
  10640. if (this._zOffset === value) {
  10641. return;
  10642. }
  10643. this._zOffset = value;
  10644. this._isZOffsetDirty = true;
  10645. },
  10646. enumerable: true,
  10647. configurable: true
  10648. });
  10649. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10650. get: function () {
  10651. return this._cullFace;
  10652. },
  10653. set: function (value) {
  10654. if (this._cullFace === value) {
  10655. return;
  10656. }
  10657. this._cullFace = value;
  10658. this._isCullFaceDirty = true;
  10659. },
  10660. enumerable: true,
  10661. configurable: true
  10662. });
  10663. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10664. get: function () {
  10665. return this._cull;
  10666. },
  10667. set: function (value) {
  10668. if (this._cull === value) {
  10669. return;
  10670. }
  10671. this._cull = value;
  10672. this._isCullDirty = true;
  10673. },
  10674. enumerable: true,
  10675. configurable: true
  10676. });
  10677. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10678. get: function () {
  10679. return this._depthFunc;
  10680. },
  10681. set: function (value) {
  10682. if (this._depthFunc === value) {
  10683. return;
  10684. }
  10685. this._depthFunc = value;
  10686. this._isDepthFuncDirty = true;
  10687. },
  10688. enumerable: true,
  10689. configurable: true
  10690. });
  10691. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10692. get: function () {
  10693. return this._depthMask;
  10694. },
  10695. set: function (value) {
  10696. if (this._depthMask === value) {
  10697. return;
  10698. }
  10699. this._depthMask = value;
  10700. this._isDepthMaskDirty = true;
  10701. },
  10702. enumerable: true,
  10703. configurable: true
  10704. });
  10705. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10706. get: function () {
  10707. return this._depthTest;
  10708. },
  10709. set: function (value) {
  10710. if (this._depthTest === value) {
  10711. return;
  10712. }
  10713. this._depthTest = value;
  10714. this._isDepthTestDirty = true;
  10715. },
  10716. enumerable: true,
  10717. configurable: true
  10718. });
  10719. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10720. get: function () {
  10721. return this._frontFace;
  10722. },
  10723. set: function (value) {
  10724. if (this._frontFace === value) {
  10725. return;
  10726. }
  10727. this._frontFace = value;
  10728. this._isFrontFaceDirty = true;
  10729. },
  10730. enumerable: true,
  10731. configurable: true
  10732. });
  10733. _DepthCullingState.prototype.reset = function () {
  10734. this._depthMask = true;
  10735. this._depthTest = true;
  10736. this._depthFunc = null;
  10737. this._cullFace = null;
  10738. this._cull = null;
  10739. this._zOffset = 0;
  10740. this._frontFace = null;
  10741. this._isDepthTestDirty = true;
  10742. this._isDepthMaskDirty = true;
  10743. this._isDepthFuncDirty = false;
  10744. this._isCullFaceDirty = false;
  10745. this._isCullDirty = false;
  10746. this._isZOffsetDirty = false;
  10747. this._isFrontFaceDirty = false;
  10748. };
  10749. _DepthCullingState.prototype.apply = function (gl) {
  10750. if (!this.isDirty) {
  10751. return;
  10752. }
  10753. // Cull
  10754. if (this._isCullDirty) {
  10755. if (this.cull) {
  10756. gl.enable(gl.CULL_FACE);
  10757. }
  10758. else {
  10759. gl.disable(gl.CULL_FACE);
  10760. }
  10761. this._isCullDirty = false;
  10762. }
  10763. // Cull face
  10764. if (this._isCullFaceDirty) {
  10765. gl.cullFace(this.cullFace);
  10766. this._isCullFaceDirty = false;
  10767. }
  10768. // Depth mask
  10769. if (this._isDepthMaskDirty) {
  10770. gl.depthMask(this.depthMask);
  10771. this._isDepthMaskDirty = false;
  10772. }
  10773. // Depth test
  10774. if (this._isDepthTestDirty) {
  10775. if (this.depthTest) {
  10776. gl.enable(gl.DEPTH_TEST);
  10777. }
  10778. else {
  10779. gl.disable(gl.DEPTH_TEST);
  10780. }
  10781. this._isDepthTestDirty = false;
  10782. }
  10783. // Depth func
  10784. if (this._isDepthFuncDirty) {
  10785. gl.depthFunc(this.depthFunc);
  10786. this._isDepthFuncDirty = false;
  10787. }
  10788. // zOffset
  10789. if (this._isZOffsetDirty) {
  10790. if (this.zOffset) {
  10791. gl.enable(gl.POLYGON_OFFSET_FILL);
  10792. gl.polygonOffset(this.zOffset, 0);
  10793. }
  10794. else {
  10795. gl.disable(gl.POLYGON_OFFSET_FILL);
  10796. }
  10797. this._isZOffsetDirty = false;
  10798. }
  10799. // Front face
  10800. if (this._isFrontFaceDirty) {
  10801. gl.frontFace(this.frontFace);
  10802. this._isFrontFaceDirty = false;
  10803. }
  10804. };
  10805. return _DepthCullingState;
  10806. }());
  10807. BABYLON._DepthCullingState = _DepthCullingState;
  10808. })(BABYLON || (BABYLON = {}));
  10809. //# sourceMappingURL=babylon.depthCullingState.js.map
  10810. var BABYLON;
  10811. (function (BABYLON) {
  10812. /**
  10813. * @hidden
  10814. **/
  10815. var _StencilState = /** @class */ (function () {
  10816. function _StencilState() {
  10817. this._isStencilTestDirty = false;
  10818. this._isStencilMaskDirty = false;
  10819. this._isStencilFuncDirty = false;
  10820. this._isStencilOpDirty = false;
  10821. this.reset();
  10822. }
  10823. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10824. get: function () {
  10825. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10826. },
  10827. enumerable: true,
  10828. configurable: true
  10829. });
  10830. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10831. get: function () {
  10832. return this._stencilFunc;
  10833. },
  10834. set: function (value) {
  10835. if (this._stencilFunc === value) {
  10836. return;
  10837. }
  10838. this._stencilFunc = value;
  10839. this._isStencilFuncDirty = true;
  10840. },
  10841. enumerable: true,
  10842. configurable: true
  10843. });
  10844. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10845. get: function () {
  10846. return this._stencilFuncRef;
  10847. },
  10848. set: function (value) {
  10849. if (this._stencilFuncRef === value) {
  10850. return;
  10851. }
  10852. this._stencilFuncRef = value;
  10853. this._isStencilFuncDirty = true;
  10854. },
  10855. enumerable: true,
  10856. configurable: true
  10857. });
  10858. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10859. get: function () {
  10860. return this._stencilFuncMask;
  10861. },
  10862. set: function (value) {
  10863. if (this._stencilFuncMask === value) {
  10864. return;
  10865. }
  10866. this._stencilFuncMask = value;
  10867. this._isStencilFuncDirty = true;
  10868. },
  10869. enumerable: true,
  10870. configurable: true
  10871. });
  10872. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10873. get: function () {
  10874. return this._stencilOpStencilFail;
  10875. },
  10876. set: function (value) {
  10877. if (this._stencilOpStencilFail === value) {
  10878. return;
  10879. }
  10880. this._stencilOpStencilFail = value;
  10881. this._isStencilOpDirty = true;
  10882. },
  10883. enumerable: true,
  10884. configurable: true
  10885. });
  10886. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10887. get: function () {
  10888. return this._stencilOpDepthFail;
  10889. },
  10890. set: function (value) {
  10891. if (this._stencilOpDepthFail === value) {
  10892. return;
  10893. }
  10894. this._stencilOpDepthFail = value;
  10895. this._isStencilOpDirty = true;
  10896. },
  10897. enumerable: true,
  10898. configurable: true
  10899. });
  10900. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10901. get: function () {
  10902. return this._stencilOpStencilDepthPass;
  10903. },
  10904. set: function (value) {
  10905. if (this._stencilOpStencilDepthPass === value) {
  10906. return;
  10907. }
  10908. this._stencilOpStencilDepthPass = value;
  10909. this._isStencilOpDirty = true;
  10910. },
  10911. enumerable: true,
  10912. configurable: true
  10913. });
  10914. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10915. get: function () {
  10916. return this._stencilMask;
  10917. },
  10918. set: function (value) {
  10919. if (this._stencilMask === value) {
  10920. return;
  10921. }
  10922. this._stencilMask = value;
  10923. this._isStencilMaskDirty = true;
  10924. },
  10925. enumerable: true,
  10926. configurable: true
  10927. });
  10928. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10929. get: function () {
  10930. return this._stencilTest;
  10931. },
  10932. set: function (value) {
  10933. if (this._stencilTest === value) {
  10934. return;
  10935. }
  10936. this._stencilTest = value;
  10937. this._isStencilTestDirty = true;
  10938. },
  10939. enumerable: true,
  10940. configurable: true
  10941. });
  10942. _StencilState.prototype.reset = function () {
  10943. this._stencilTest = false;
  10944. this._stencilMask = 0xFF;
  10945. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10946. this._stencilFuncRef = 1;
  10947. this._stencilFuncMask = 0xFF;
  10948. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10949. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10950. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10951. this._isStencilTestDirty = true;
  10952. this._isStencilMaskDirty = true;
  10953. this._isStencilFuncDirty = true;
  10954. this._isStencilOpDirty = true;
  10955. };
  10956. _StencilState.prototype.apply = function (gl) {
  10957. if (!this.isDirty) {
  10958. return;
  10959. }
  10960. // Stencil test
  10961. if (this._isStencilTestDirty) {
  10962. if (this.stencilTest) {
  10963. gl.enable(gl.STENCIL_TEST);
  10964. }
  10965. else {
  10966. gl.disable(gl.STENCIL_TEST);
  10967. }
  10968. this._isStencilTestDirty = false;
  10969. }
  10970. // Stencil mask
  10971. if (this._isStencilMaskDirty) {
  10972. gl.stencilMask(this.stencilMask);
  10973. this._isStencilMaskDirty = false;
  10974. }
  10975. // Stencil func
  10976. if (this._isStencilFuncDirty) {
  10977. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10978. this._isStencilFuncDirty = false;
  10979. }
  10980. // Stencil op
  10981. if (this._isStencilOpDirty) {
  10982. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10983. this._isStencilOpDirty = false;
  10984. }
  10985. };
  10986. return _StencilState;
  10987. }());
  10988. BABYLON._StencilState = _StencilState;
  10989. })(BABYLON || (BABYLON = {}));
  10990. //# sourceMappingURL=babylon.stencilState.js.map
  10991. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10992. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10993. s = arguments[i];
  10994. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10995. t[p] = s[p];
  10996. }
  10997. return t;
  10998. };
  10999. var BABYLON;
  11000. (function (BABYLON) {
  11001. var compileShader = function (gl, source, type, defines, shaderVersion) {
  11002. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  11003. };
  11004. var compileRawShader = function (gl, source, type) {
  11005. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  11006. gl.shaderSource(shader, source);
  11007. gl.compileShader(shader);
  11008. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  11009. var log = gl.getShaderInfoLog(shader);
  11010. if (log) {
  11011. throw new Error(log);
  11012. }
  11013. }
  11014. if (!shader) {
  11015. throw new Error("Something went wrong while compile the shader.");
  11016. }
  11017. return shader;
  11018. };
  11019. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  11020. var magFilter = gl.NEAREST;
  11021. var minFilter = gl.NEAREST;
  11022. switch (samplingMode) {
  11023. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11024. magFilter = gl.LINEAR;
  11025. if (generateMipMaps) {
  11026. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11027. }
  11028. else {
  11029. minFilter = gl.LINEAR;
  11030. }
  11031. break;
  11032. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11033. magFilter = gl.LINEAR;
  11034. if (generateMipMaps) {
  11035. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11036. }
  11037. else {
  11038. minFilter = gl.LINEAR;
  11039. }
  11040. break;
  11041. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11042. magFilter = gl.NEAREST;
  11043. if (generateMipMaps) {
  11044. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11045. }
  11046. else {
  11047. minFilter = gl.NEAREST;
  11048. }
  11049. break;
  11050. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11051. magFilter = gl.NEAREST;
  11052. if (generateMipMaps) {
  11053. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11054. }
  11055. else {
  11056. minFilter = gl.NEAREST;
  11057. }
  11058. break;
  11059. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11060. magFilter = gl.NEAREST;
  11061. if (generateMipMaps) {
  11062. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11063. }
  11064. else {
  11065. minFilter = gl.LINEAR;
  11066. }
  11067. break;
  11068. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11069. magFilter = gl.NEAREST;
  11070. if (generateMipMaps) {
  11071. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11072. }
  11073. else {
  11074. minFilter = gl.LINEAR;
  11075. }
  11076. break;
  11077. case BABYLON.Texture.NEAREST_LINEAR:
  11078. magFilter = gl.NEAREST;
  11079. minFilter = gl.LINEAR;
  11080. break;
  11081. case BABYLON.Texture.NEAREST_NEAREST:
  11082. magFilter = gl.NEAREST;
  11083. minFilter = gl.NEAREST;
  11084. break;
  11085. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11086. magFilter = gl.LINEAR;
  11087. if (generateMipMaps) {
  11088. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11089. }
  11090. else {
  11091. minFilter = gl.NEAREST;
  11092. }
  11093. break;
  11094. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11095. magFilter = gl.LINEAR;
  11096. if (generateMipMaps) {
  11097. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11098. }
  11099. else {
  11100. minFilter = gl.NEAREST;
  11101. }
  11102. break;
  11103. case BABYLON.Texture.LINEAR_LINEAR:
  11104. magFilter = gl.LINEAR;
  11105. minFilter = gl.LINEAR;
  11106. break;
  11107. case BABYLON.Texture.LINEAR_NEAREST:
  11108. magFilter = gl.LINEAR;
  11109. minFilter = gl.NEAREST;
  11110. break;
  11111. }
  11112. return {
  11113. min: minFilter,
  11114. mag: magFilter
  11115. };
  11116. };
  11117. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11118. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11119. var img;
  11120. var onload = function () {
  11121. loadedImages[index] = img;
  11122. loadedImages._internalCount++;
  11123. if (scene) {
  11124. scene._removePendingData(img);
  11125. }
  11126. if (loadedImages._internalCount === 6) {
  11127. onfinish(loadedImages);
  11128. }
  11129. };
  11130. var onerror = function (message, exception) {
  11131. if (scene) {
  11132. scene._removePendingData(img);
  11133. }
  11134. if (onErrorCallBack) {
  11135. onErrorCallBack(message, exception);
  11136. }
  11137. };
  11138. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11139. if (scene) {
  11140. scene._addPendingData(img);
  11141. }
  11142. };
  11143. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11144. if (onError === void 0) { onError = null; }
  11145. var loadedImages = [];
  11146. loadedImages._internalCount = 0;
  11147. for (var index = 0; index < 6; index++) {
  11148. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11149. }
  11150. };
  11151. var BufferPointer = /** @class */ (function () {
  11152. function BufferPointer() {
  11153. }
  11154. return BufferPointer;
  11155. }());
  11156. /**
  11157. * Interface for attribute information associated with buffer instanciation
  11158. */
  11159. var InstancingAttributeInfo = /** @class */ (function () {
  11160. function InstancingAttributeInfo() {
  11161. }
  11162. return InstancingAttributeInfo;
  11163. }());
  11164. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11165. /**
  11166. * Define options used to create a render target texture
  11167. */
  11168. var RenderTargetCreationOptions = /** @class */ (function () {
  11169. function RenderTargetCreationOptions() {
  11170. }
  11171. return RenderTargetCreationOptions;
  11172. }());
  11173. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11174. /**
  11175. * Define options used to create a depth texture
  11176. */
  11177. var DepthTextureCreationOptions = /** @class */ (function () {
  11178. function DepthTextureCreationOptions() {
  11179. }
  11180. return DepthTextureCreationOptions;
  11181. }());
  11182. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11183. /**
  11184. * Class used to describe the capabilities of the engine relatively to the current browser
  11185. */
  11186. var EngineCapabilities = /** @class */ (function () {
  11187. function EngineCapabilities() {
  11188. }
  11189. return EngineCapabilities;
  11190. }());
  11191. BABYLON.EngineCapabilities = EngineCapabilities;
  11192. /**
  11193. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11194. */
  11195. var Engine = /** @class */ (function () {
  11196. /**
  11197. * Creates a new engine
  11198. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11199. * @param antialias defines enable antialiasing (default: false)
  11200. * @param options defines further options to be sent to the getContext() function
  11201. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11202. */
  11203. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11204. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11205. var _this = this;
  11206. // Public members
  11207. /**
  11208. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11209. */
  11210. this.forcePOTTextures = false;
  11211. /**
  11212. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11213. */
  11214. this.isFullscreen = false;
  11215. /**
  11216. * Gets a boolean indicating if the pointer is currently locked
  11217. */
  11218. this.isPointerLock = false;
  11219. /**
  11220. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11221. */
  11222. this.cullBackFaces = true;
  11223. /**
  11224. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11225. */
  11226. this.renderEvenInBackground = true;
  11227. /**
  11228. * Gets or sets a boolean indicating that cache can be kept between frames
  11229. */
  11230. this.preventCacheWipeBetweenFrames = false;
  11231. /**
  11232. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11233. **/
  11234. this.enableOfflineSupport = false;
  11235. /**
  11236. * 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)
  11237. **/
  11238. this.disableManifestCheck = false;
  11239. /**
  11240. * Gets the list of created scenes
  11241. */
  11242. this.scenes = new Array();
  11243. /**
  11244. * Gets the list of created postprocesses
  11245. */
  11246. this.postProcesses = new Array();
  11247. // Observables
  11248. /**
  11249. * Observable event triggered each time the rendering canvas is resized
  11250. */
  11251. this.onResizeObservable = new BABYLON.Observable();
  11252. /**
  11253. * Observable event triggered each time the canvas loses focus
  11254. */
  11255. this.onCanvasBlurObservable = new BABYLON.Observable();
  11256. /**
  11257. * Observable event triggered each time the canvas gains focus
  11258. */
  11259. this.onCanvasFocusObservable = new BABYLON.Observable();
  11260. /**
  11261. * Observable event triggered each time the canvas receives pointerout event
  11262. */
  11263. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11264. /**
  11265. * Observable event triggered before each texture is initialized
  11266. */
  11267. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11268. //WebVR
  11269. this._vrDisplay = undefined;
  11270. this._vrSupported = false;
  11271. this._vrExclusivePointerMode = false;
  11272. // Uniform buffers list
  11273. /**
  11274. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11275. */
  11276. this.disableUniformBuffers = false;
  11277. /** @hidden */
  11278. this._uniformBuffers = new Array();
  11279. // Observables
  11280. /**
  11281. * Observable raised when the engine begins a new frame
  11282. */
  11283. this.onBeginFrameObservable = new BABYLON.Observable();
  11284. /**
  11285. * Observable raised when the engine ends the current frame
  11286. */
  11287. this.onEndFrameObservable = new BABYLON.Observable();
  11288. /**
  11289. * Observable raised when the engine is about to compile a shader
  11290. */
  11291. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11292. /**
  11293. * Observable raised when the engine has jsut compiled a shader
  11294. */
  11295. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11296. this._windowIsBackground = false;
  11297. this._webGLVersion = 1.0;
  11298. /** @hidden */
  11299. this._badOS = false;
  11300. /** @hidden */
  11301. this._badDesktopOS = false;
  11302. /**
  11303. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11304. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11305. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11306. */
  11307. this.disableTextureBindingOptimization = false;
  11308. /**
  11309. * Observable signaled when VR display mode changes
  11310. */
  11311. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11312. /**
  11313. * Observable signaled when VR request present is complete
  11314. */
  11315. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11316. /**
  11317. * Observable signaled when VR request present starts
  11318. */
  11319. this.onVRRequestPresentStart = new BABYLON.Observable();
  11320. this._colorWrite = true;
  11321. /** @hidden */
  11322. this._drawCalls = new BABYLON.PerfCounter();
  11323. /** @hidden */
  11324. this._textureCollisions = new BABYLON.PerfCounter();
  11325. this._renderingQueueLaunched = false;
  11326. this._activeRenderLoops = new Array();
  11327. // Deterministic lockstepMaxSteps
  11328. this._deterministicLockstep = false;
  11329. this._lockstepMaxSteps = 4;
  11330. // Lost context
  11331. /**
  11332. * Observable signaled when a context lost event is raised
  11333. */
  11334. this.onContextLostObservable = new BABYLON.Observable();
  11335. /**
  11336. * Observable signaled when a context restored event is raised
  11337. */
  11338. this.onContextRestoredObservable = new BABYLON.Observable();
  11339. this._contextWasLost = false;
  11340. this._doNotHandleContextLost = false;
  11341. // FPS
  11342. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11343. this._fps = 60;
  11344. this._deltaTime = 0;
  11345. /**
  11346. * Turn this value on if you want to pause FPS computation when in background
  11347. */
  11348. this.disablePerformanceMonitorInBackground = false;
  11349. // States
  11350. /** @hidden */
  11351. this._depthCullingState = new BABYLON._DepthCullingState();
  11352. /** @hidden */
  11353. this._stencilState = new BABYLON._StencilState();
  11354. /** @hidden */
  11355. this._alphaState = new BABYLON._AlphaState();
  11356. /** @hidden */
  11357. this._alphaMode = Engine.ALPHA_DISABLE;
  11358. // Cache
  11359. this._internalTexturesCache = new Array();
  11360. /** @hidden */
  11361. this._activeChannel = 0;
  11362. this._currentTextureChannel = -1;
  11363. /** @hidden */
  11364. this._boundTexturesCache = {};
  11365. this._compiledEffects = {};
  11366. this._vertexAttribArraysEnabled = [];
  11367. this._uintIndicesCurrentlySet = false;
  11368. this._currentBoundBuffer = new Array();
  11369. this._currentBufferPointers = new Array();
  11370. this._currentInstanceLocations = new Array();
  11371. this._currentInstanceBuffers = new Array();
  11372. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11373. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11374. this._vaoRecordInProgress = false;
  11375. this._mustWipeVertexAttributes = false;
  11376. this._nextFreeTextureSlots = new Array();
  11377. this._maxSimultaneousTextures = 0;
  11378. this._activeRequests = new Array();
  11379. // Hardware supported Compressed Textures
  11380. this._texturesSupported = new Array();
  11381. this._onVRFullScreenTriggered = function () {
  11382. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11383. //get the old size before we change
  11384. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11385. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11386. //get the width and height, change the render size
  11387. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11388. _this.setHardwareScalingLevel(1);
  11389. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11390. }
  11391. else {
  11392. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11393. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11394. }
  11395. };
  11396. this._boundUniforms = {};
  11397. // Register promises
  11398. BABYLON.PromisePolyfill.Apply();
  11399. var canvas = null;
  11400. Engine.Instances.push(this);
  11401. if (!canvasOrContext) {
  11402. return;
  11403. }
  11404. options = options || {};
  11405. if (canvasOrContext.getContext) {
  11406. canvas = canvasOrContext;
  11407. this._renderingCanvas = canvas;
  11408. if (antialias != null) {
  11409. options.antialias = antialias;
  11410. }
  11411. if (options.deterministicLockstep === undefined) {
  11412. options.deterministicLockstep = false;
  11413. }
  11414. if (options.lockstepMaxSteps === undefined) {
  11415. options.lockstepMaxSteps = 4;
  11416. }
  11417. if (options.preserveDrawingBuffer === undefined) {
  11418. options.preserveDrawingBuffer = false;
  11419. }
  11420. if (options.audioEngine === undefined) {
  11421. options.audioEngine = true;
  11422. }
  11423. if (options.stencil === undefined) {
  11424. options.stencil = true;
  11425. }
  11426. this._deterministicLockstep = options.deterministicLockstep;
  11427. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11428. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11429. // Exceptions
  11430. if (navigator && navigator.userAgent) {
  11431. var ua = navigator.userAgent;
  11432. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11433. var exception = _a[_i];
  11434. var key = exception.key;
  11435. var targets = exception.targets;
  11436. if (ua.indexOf(key) > -1) {
  11437. if (exception.capture && exception.captureConstraint) {
  11438. var capture = exception.capture;
  11439. var constraint = exception.captureConstraint;
  11440. var regex = new RegExp(capture);
  11441. var matches = regex.exec(ua);
  11442. if (matches && matches.length > 0) {
  11443. var capturedValue = parseInt(matches[matches.length - 1]);
  11444. if (capturedValue >= constraint) {
  11445. continue;
  11446. }
  11447. }
  11448. }
  11449. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11450. var target = targets_1[_b];
  11451. switch (target) {
  11452. case "uniformBuffer":
  11453. this.disableUniformBuffers = true;
  11454. break;
  11455. case "textureBindingOptimization":
  11456. this.disableTextureBindingOptimization = true;
  11457. break;
  11458. }
  11459. }
  11460. }
  11461. }
  11462. }
  11463. // GL
  11464. if (!options.disableWebGL2Support) {
  11465. try {
  11466. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11467. if (this._gl) {
  11468. this._webGLVersion = 2.0;
  11469. }
  11470. }
  11471. catch (e) {
  11472. // Do nothing
  11473. }
  11474. }
  11475. if (!this._gl) {
  11476. if (!canvas) {
  11477. throw new Error("The provided canvas is null or undefined.");
  11478. }
  11479. try {
  11480. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11481. }
  11482. catch (e) {
  11483. throw new Error("WebGL not supported");
  11484. }
  11485. }
  11486. if (!this._gl) {
  11487. throw new Error("WebGL not supported");
  11488. }
  11489. this._onCanvasFocus = function () {
  11490. _this.onCanvasFocusObservable.notifyObservers(_this);
  11491. };
  11492. this._onCanvasBlur = function () {
  11493. _this.onCanvasBlurObservable.notifyObservers(_this);
  11494. };
  11495. canvas.addEventListener("focus", this._onCanvasFocus);
  11496. canvas.addEventListener("blur", this._onCanvasBlur);
  11497. this._onBlur = function () {
  11498. if (_this.disablePerformanceMonitorInBackground) {
  11499. _this._performanceMonitor.disable();
  11500. }
  11501. _this._windowIsBackground = true;
  11502. };
  11503. this._onFocus = function () {
  11504. if (_this.disablePerformanceMonitorInBackground) {
  11505. _this._performanceMonitor.enable();
  11506. }
  11507. _this._windowIsBackground = false;
  11508. };
  11509. this._onCanvasPointerOut = function (ev) {
  11510. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11511. };
  11512. window.addEventListener("blur", this._onBlur);
  11513. window.addEventListener("focus", this._onFocus);
  11514. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11515. // Context lost
  11516. if (!this._doNotHandleContextLost) {
  11517. this._onContextLost = function (evt) {
  11518. evt.preventDefault();
  11519. _this._contextWasLost = true;
  11520. BABYLON.Tools.Warn("WebGL context lost.");
  11521. _this.onContextLostObservable.notifyObservers(_this);
  11522. };
  11523. this._onContextRestored = function (evt) {
  11524. // Adding a timeout to avoid race condition at browser level
  11525. setTimeout(function () {
  11526. // Rebuild gl context
  11527. _this._initGLContext();
  11528. // Rebuild effects
  11529. _this._rebuildEffects();
  11530. // Rebuild textures
  11531. _this._rebuildInternalTextures();
  11532. // Rebuild buffers
  11533. _this._rebuildBuffers();
  11534. // Cache
  11535. _this.wipeCaches(true);
  11536. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11537. _this.onContextRestoredObservable.notifyObservers(_this);
  11538. _this._contextWasLost = false;
  11539. }, 0);
  11540. };
  11541. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11542. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11543. }
  11544. }
  11545. else {
  11546. this._gl = canvasOrContext;
  11547. this._renderingCanvas = this._gl.canvas;
  11548. if (this._gl.renderbufferStorageMultisample) {
  11549. this._webGLVersion = 2.0;
  11550. }
  11551. options.stencil = this._gl.getContextAttributes().stencil;
  11552. }
  11553. // Viewport
  11554. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11555. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11556. this.resize();
  11557. this._isStencilEnable = options.stencil ? true : false;
  11558. this._initGLContext();
  11559. if (canvas) {
  11560. // Fullscreen
  11561. this._onFullscreenChange = function () {
  11562. if (document.fullscreen !== undefined) {
  11563. _this.isFullscreen = document.fullscreen;
  11564. }
  11565. else if (document.mozFullScreen !== undefined) {
  11566. _this.isFullscreen = document.mozFullScreen;
  11567. }
  11568. else if (document.webkitIsFullScreen !== undefined) {
  11569. _this.isFullscreen = document.webkitIsFullScreen;
  11570. }
  11571. else if (document.msIsFullScreen !== undefined) {
  11572. _this.isFullscreen = document.msIsFullScreen;
  11573. }
  11574. // Pointer lock
  11575. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11576. canvas.requestPointerLock = canvas.requestPointerLock ||
  11577. canvas.msRequestPointerLock ||
  11578. canvas.mozRequestPointerLock ||
  11579. canvas.webkitRequestPointerLock;
  11580. if (canvas.requestPointerLock) {
  11581. canvas.requestPointerLock();
  11582. }
  11583. }
  11584. };
  11585. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11586. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11587. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11588. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11589. // Pointer lock
  11590. this._onPointerLockChange = function () {
  11591. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11592. document.webkitPointerLockElement === canvas ||
  11593. document.msPointerLockElement === canvas ||
  11594. document.pointerLockElement === canvas);
  11595. };
  11596. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11597. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11598. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11599. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11600. this._onVRDisplayPointerRestricted = function () {
  11601. if (canvas) {
  11602. canvas.requestPointerLock();
  11603. }
  11604. };
  11605. this._onVRDisplayPointerUnrestricted = function () {
  11606. document.exitPointerLock();
  11607. };
  11608. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11609. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11610. }
  11611. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11612. Engine.audioEngine = new BABYLON.AudioEngine();
  11613. }
  11614. // Prepare buffer pointers
  11615. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11616. this._currentBufferPointers[i] = new BufferPointer();
  11617. }
  11618. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11619. // Load WebVR Devices
  11620. if (options.autoEnableWebVR) {
  11621. this.initWebVR();
  11622. }
  11623. // Detect if we are running on a faulty buggy OS.
  11624. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11625. // Detect if we are running on a faulty buggy desktop OS.
  11626. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11627. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11628. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11629. }
  11630. Object.defineProperty(Engine, "LastCreatedEngine", {
  11631. /**
  11632. * Gets the latest created engine
  11633. */
  11634. get: function () {
  11635. if (Engine.Instances.length === 0) {
  11636. return null;
  11637. }
  11638. return Engine.Instances[Engine.Instances.length - 1];
  11639. },
  11640. enumerable: true,
  11641. configurable: true
  11642. });
  11643. Object.defineProperty(Engine, "LastCreatedScene", {
  11644. /**
  11645. * Gets the latest created scene
  11646. */
  11647. get: function () {
  11648. var lastCreatedEngine = Engine.LastCreatedEngine;
  11649. if (!lastCreatedEngine) {
  11650. return null;
  11651. }
  11652. if (lastCreatedEngine.scenes.length === 0) {
  11653. return null;
  11654. }
  11655. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11656. },
  11657. enumerable: true,
  11658. configurable: true
  11659. });
  11660. /**
  11661. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11662. * @param flag defines which part of the materials must be marked as dirty
  11663. * @param predicate defines a predicate used to filter which materials should be affected
  11664. */
  11665. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11666. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11667. var engine = Engine.Instances[engineIndex];
  11668. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11669. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11670. }
  11671. }
  11672. };
  11673. Object.defineProperty(Engine, "NEVER", {
  11674. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11675. get: function () {
  11676. return Engine._NEVER;
  11677. },
  11678. enumerable: true,
  11679. configurable: true
  11680. });
  11681. Object.defineProperty(Engine, "ALWAYS", {
  11682. /** 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 */
  11683. get: function () {
  11684. return Engine._ALWAYS;
  11685. },
  11686. enumerable: true,
  11687. configurable: true
  11688. });
  11689. Object.defineProperty(Engine, "LESS", {
  11690. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11691. get: function () {
  11692. return Engine._LESS;
  11693. },
  11694. enumerable: true,
  11695. configurable: true
  11696. });
  11697. Object.defineProperty(Engine, "EQUAL", {
  11698. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11699. get: function () {
  11700. return Engine._EQUAL;
  11701. },
  11702. enumerable: true,
  11703. configurable: true
  11704. });
  11705. Object.defineProperty(Engine, "LEQUAL", {
  11706. /** 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 */
  11707. get: function () {
  11708. return Engine._LEQUAL;
  11709. },
  11710. enumerable: true,
  11711. configurable: true
  11712. });
  11713. Object.defineProperty(Engine, "GREATER", {
  11714. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11715. get: function () {
  11716. return Engine._GREATER;
  11717. },
  11718. enumerable: true,
  11719. configurable: true
  11720. });
  11721. Object.defineProperty(Engine, "GEQUAL", {
  11722. /** 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 */
  11723. get: function () {
  11724. return Engine._GEQUAL;
  11725. },
  11726. enumerable: true,
  11727. configurable: true
  11728. });
  11729. Object.defineProperty(Engine, "NOTEQUAL", {
  11730. /** 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 */
  11731. get: function () {
  11732. return Engine._NOTEQUAL;
  11733. },
  11734. enumerable: true,
  11735. configurable: true
  11736. });
  11737. Object.defineProperty(Engine, "KEEP", {
  11738. /** Passed to stencilOperation to specify that stencil value must be kept */
  11739. get: function () {
  11740. return Engine._KEEP;
  11741. },
  11742. enumerable: true,
  11743. configurable: true
  11744. });
  11745. Object.defineProperty(Engine, "REPLACE", {
  11746. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11747. get: function () {
  11748. return Engine._REPLACE;
  11749. },
  11750. enumerable: true,
  11751. configurable: true
  11752. });
  11753. Object.defineProperty(Engine, "INCR", {
  11754. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11755. get: function () {
  11756. return Engine._INCR;
  11757. },
  11758. enumerable: true,
  11759. configurable: true
  11760. });
  11761. Object.defineProperty(Engine, "DECR", {
  11762. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11763. get: function () {
  11764. return Engine._DECR;
  11765. },
  11766. enumerable: true,
  11767. configurable: true
  11768. });
  11769. Object.defineProperty(Engine, "INVERT", {
  11770. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11771. get: function () {
  11772. return Engine._INVERT;
  11773. },
  11774. enumerable: true,
  11775. configurable: true
  11776. });
  11777. Object.defineProperty(Engine, "INCR_WRAP", {
  11778. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11779. get: function () {
  11780. return Engine._INCR_WRAP;
  11781. },
  11782. enumerable: true,
  11783. configurable: true
  11784. });
  11785. Object.defineProperty(Engine, "DECR_WRAP", {
  11786. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11787. get: function () {
  11788. return Engine._DECR_WRAP;
  11789. },
  11790. enumerable: true,
  11791. configurable: true
  11792. });
  11793. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11794. // Alpha
  11795. /** Defines that alpha blending is disabled */
  11796. get: function () {
  11797. return Engine._ALPHA_DISABLE;
  11798. },
  11799. enumerable: true,
  11800. configurable: true
  11801. });
  11802. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11803. /** Defines that alpha blending to SRC + DEST */
  11804. get: function () {
  11805. return Engine._ALPHA_ONEONE;
  11806. },
  11807. enumerable: true,
  11808. configurable: true
  11809. });
  11810. Object.defineProperty(Engine, "ALPHA_ADD", {
  11811. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11812. get: function () {
  11813. return Engine._ALPHA_ADD;
  11814. },
  11815. enumerable: true,
  11816. configurable: true
  11817. });
  11818. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11819. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11820. get: function () {
  11821. return Engine._ALPHA_COMBINE;
  11822. },
  11823. enumerable: true,
  11824. configurable: true
  11825. });
  11826. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11827. /** Defines that alpha blending to DEST - SRC * DEST */
  11828. get: function () {
  11829. return Engine._ALPHA_SUBTRACT;
  11830. },
  11831. enumerable: true,
  11832. configurable: true
  11833. });
  11834. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11835. /** Defines that alpha blending to SRC * DEST */
  11836. get: function () {
  11837. return Engine._ALPHA_MULTIPLY;
  11838. },
  11839. enumerable: true,
  11840. configurable: true
  11841. });
  11842. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11843. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11844. get: function () {
  11845. return Engine._ALPHA_MAXIMIZED;
  11846. },
  11847. enumerable: true,
  11848. configurable: true
  11849. });
  11850. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11851. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11852. get: function () {
  11853. return Engine._ALPHA_PREMULTIPLIED;
  11854. },
  11855. enumerable: true,
  11856. configurable: true
  11857. });
  11858. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11859. /**
  11860. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11861. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11862. */
  11863. get: function () {
  11864. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11865. },
  11866. enumerable: true,
  11867. configurable: true
  11868. });
  11869. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11870. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11871. get: function () {
  11872. return Engine._ALPHA_INTERPOLATE;
  11873. },
  11874. enumerable: true,
  11875. configurable: true
  11876. });
  11877. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11878. /**
  11879. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11880. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11881. */
  11882. get: function () {
  11883. return Engine._ALPHA_SCREENMODE;
  11884. },
  11885. enumerable: true,
  11886. configurable: true
  11887. });
  11888. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11889. // Delays
  11890. /** Defines that the ressource is not delayed*/
  11891. get: function () {
  11892. return Engine._DELAYLOADSTATE_NONE;
  11893. },
  11894. enumerable: true,
  11895. configurable: true
  11896. });
  11897. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11898. /** Defines that the ressource was successfully delay loaded */
  11899. get: function () {
  11900. return Engine._DELAYLOADSTATE_LOADED;
  11901. },
  11902. enumerable: true,
  11903. configurable: true
  11904. });
  11905. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11906. /** Defines that the ressource is currently delay loading */
  11907. get: function () {
  11908. return Engine._DELAYLOADSTATE_LOADING;
  11909. },
  11910. enumerable: true,
  11911. configurable: true
  11912. });
  11913. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11914. /** Defines that the ressource is delayed and has not started loading */
  11915. get: function () {
  11916. return Engine._DELAYLOADSTATE_NOTLOADED;
  11917. },
  11918. enumerable: true,
  11919. configurable: true
  11920. });
  11921. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11922. /** ALPHA */
  11923. get: function () {
  11924. return Engine._TEXTUREFORMAT_ALPHA;
  11925. },
  11926. enumerable: true,
  11927. configurable: true
  11928. });
  11929. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11930. /** LUMINANCE */
  11931. get: function () {
  11932. return Engine._TEXTUREFORMAT_LUMINANCE;
  11933. },
  11934. enumerable: true,
  11935. configurable: true
  11936. });
  11937. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11938. /**
  11939. * R32F
  11940. */
  11941. get: function () {
  11942. return Engine._TEXTUREFORMAT_R32F;
  11943. },
  11944. enumerable: true,
  11945. configurable: true
  11946. });
  11947. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11948. /**
  11949. * RG32F
  11950. */
  11951. get: function () {
  11952. return Engine._TEXTUREFORMAT_RG32F;
  11953. },
  11954. enumerable: true,
  11955. configurable: true
  11956. });
  11957. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11958. /**
  11959. * RGB32F
  11960. */
  11961. get: function () {
  11962. return Engine._TEXTUREFORMAT_RGB32F;
  11963. },
  11964. enumerable: true,
  11965. configurable: true
  11966. });
  11967. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11968. /**
  11969. * RGBA32F
  11970. */
  11971. get: function () {
  11972. return Engine._TEXTUREFORMAT_RGBA32F;
  11973. },
  11974. enumerable: true,
  11975. configurable: true
  11976. });
  11977. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11978. /** LUMINANCE_ALPHA */
  11979. get: function () {
  11980. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11981. },
  11982. enumerable: true,
  11983. configurable: true
  11984. });
  11985. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11986. /** RGB */
  11987. get: function () {
  11988. return Engine._TEXTUREFORMAT_RGB;
  11989. },
  11990. enumerable: true,
  11991. configurable: true
  11992. });
  11993. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11994. /** RGBA */
  11995. get: function () {
  11996. return Engine._TEXTUREFORMAT_RGBA;
  11997. },
  11998. enumerable: true,
  11999. configurable: true
  12000. });
  12001. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  12002. /** UNSIGNED_INT */
  12003. get: function () {
  12004. return Engine._TEXTURETYPE_UNSIGNED_INT;
  12005. },
  12006. enumerable: true,
  12007. configurable: true
  12008. });
  12009. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  12010. /** FLOAT */
  12011. get: function () {
  12012. return Engine._TEXTURETYPE_FLOAT;
  12013. },
  12014. enumerable: true,
  12015. configurable: true
  12016. });
  12017. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  12018. /** HALF_FLOAT */
  12019. get: function () {
  12020. return Engine._TEXTURETYPE_HALF_FLOAT;
  12021. },
  12022. enumerable: true,
  12023. configurable: true
  12024. });
  12025. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  12026. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  12027. get: function () {
  12028. return Engine._SCALEMODE_FLOOR;
  12029. },
  12030. enumerable: true,
  12031. configurable: true
  12032. });
  12033. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12034. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12035. get: function () {
  12036. return Engine._SCALEMODE_NEAREST;
  12037. },
  12038. enumerable: true,
  12039. configurable: true
  12040. });
  12041. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12042. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12043. get: function () {
  12044. return Engine._SCALEMODE_CEILING;
  12045. },
  12046. enumerable: true,
  12047. configurable: true
  12048. });
  12049. Object.defineProperty(Engine, "Version", {
  12050. /**
  12051. * Returns the current version of the framework
  12052. */
  12053. get: function () {
  12054. return "3.2.0-rc.2";
  12055. },
  12056. enumerable: true,
  12057. configurable: true
  12058. });
  12059. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12060. /**
  12061. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12062. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12063. */
  12064. get: function () {
  12065. return this._vrExclusivePointerMode;
  12066. },
  12067. enumerable: true,
  12068. configurable: true
  12069. });
  12070. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12071. /**
  12072. * Gets a boolean indicating that the engine supports uniform buffers
  12073. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12074. */
  12075. get: function () {
  12076. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12077. },
  12078. enumerable: true,
  12079. configurable: true
  12080. });
  12081. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12082. /**
  12083. * Gets a boolean indicating that only power of 2 textures are supported
  12084. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12085. */
  12086. get: function () {
  12087. return this._webGLVersion < 2 || this.forcePOTTextures;
  12088. },
  12089. enumerable: true,
  12090. configurable: true
  12091. });
  12092. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12093. /**
  12094. * Gets the performance monitor attached to this engine
  12095. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12096. */
  12097. get: function () {
  12098. return this._performanceMonitor;
  12099. },
  12100. enumerable: true,
  12101. configurable: true
  12102. });
  12103. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12104. /**
  12105. * Gets the list of texture formats supported
  12106. */
  12107. get: function () {
  12108. return this._texturesSupported;
  12109. },
  12110. enumerable: true,
  12111. configurable: true
  12112. });
  12113. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12114. /**
  12115. * Gets the list of texture formats in use
  12116. */
  12117. get: function () {
  12118. return this._textureFormatInUse;
  12119. },
  12120. enumerable: true,
  12121. configurable: true
  12122. });
  12123. Object.defineProperty(Engine.prototype, "currentViewport", {
  12124. /**
  12125. * Gets the current viewport
  12126. */
  12127. get: function () {
  12128. return this._cachedViewport;
  12129. },
  12130. enumerable: true,
  12131. configurable: true
  12132. });
  12133. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12134. /**
  12135. * Gets the default empty texture
  12136. */
  12137. get: function () {
  12138. if (!this._emptyTexture) {
  12139. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12140. }
  12141. return this._emptyTexture;
  12142. },
  12143. enumerable: true,
  12144. configurable: true
  12145. });
  12146. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12147. /**
  12148. * Gets the default empty 3D texture
  12149. */
  12150. get: function () {
  12151. if (!this._emptyTexture3D) {
  12152. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12153. }
  12154. return this._emptyTexture3D;
  12155. },
  12156. enumerable: true,
  12157. configurable: true
  12158. });
  12159. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12160. /**
  12161. * Gets the default empty cube texture
  12162. */
  12163. get: function () {
  12164. if (!this._emptyCubeTexture) {
  12165. var faceData = new Uint8Array(4);
  12166. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12167. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12168. }
  12169. return this._emptyCubeTexture;
  12170. },
  12171. enumerable: true,
  12172. configurable: true
  12173. });
  12174. Engine.prototype._rebuildInternalTextures = function () {
  12175. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12176. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12177. var internalTexture = currentState_1[_i];
  12178. internalTexture._rebuild();
  12179. }
  12180. };
  12181. Engine.prototype._rebuildEffects = function () {
  12182. for (var key in this._compiledEffects) {
  12183. var effect = this._compiledEffects[key];
  12184. effect._prepareEffect();
  12185. }
  12186. BABYLON.Effect.ResetCache();
  12187. };
  12188. Engine.prototype._rebuildBuffers = function () {
  12189. // Index / Vertex
  12190. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12191. var scene = _a[_i];
  12192. scene.resetCachedMaterial();
  12193. scene._rebuildGeometries();
  12194. scene._rebuildTextures();
  12195. }
  12196. // Uniforms
  12197. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12198. var uniformBuffer = _c[_b];
  12199. uniformBuffer._rebuild();
  12200. }
  12201. };
  12202. Engine.prototype._initGLContext = function () {
  12203. // Caps
  12204. this._caps = new EngineCapabilities();
  12205. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12206. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12207. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12208. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12209. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12210. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12211. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12212. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12213. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12214. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12215. // Infos
  12216. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12217. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12218. if (rendererInfo != null) {
  12219. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12220. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12221. }
  12222. if (!this._glVendor) {
  12223. this._glVendor = "Unknown vendor";
  12224. }
  12225. if (!this._glRenderer) {
  12226. this._glRenderer = "Unknown renderer";
  12227. }
  12228. // Constants
  12229. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12230. if (this._gl.RGBA16F !== 0x881A) {
  12231. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12232. }
  12233. if (this._gl.RGBA32F !== 0x8814) {
  12234. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12235. }
  12236. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12237. this._gl.DEPTH24_STENCIL8 = 35056;
  12238. }
  12239. // Extensions
  12240. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12241. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12242. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12243. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12244. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12245. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12246. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12247. 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');
  12248. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12249. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12250. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12251. this._caps.highPrecisionShaderSupported = true;
  12252. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12253. if (this._caps.timerQuery) {
  12254. if (this._webGLVersion === 1) {
  12255. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12256. }
  12257. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12258. }
  12259. // Checks if some of the format renders first to allow the use of webgl inspector.
  12260. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12261. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12262. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12263. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12264. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12265. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12266. if (this._webGLVersion > 1) {
  12267. this._gl.HALF_FLOAT_OES = 0x140B;
  12268. }
  12269. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12270. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12271. // Draw buffers
  12272. if (this._webGLVersion > 1) {
  12273. this._caps.drawBuffersExtension = true;
  12274. }
  12275. else {
  12276. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12277. if (drawBuffersExtension !== null) {
  12278. this._caps.drawBuffersExtension = true;
  12279. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12280. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12281. for (var i = 0; i < 16; i++) {
  12282. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12283. }
  12284. }
  12285. else {
  12286. this._caps.drawBuffersExtension = false;
  12287. }
  12288. }
  12289. // Depth Texture
  12290. if (this._webGLVersion > 1) {
  12291. this._caps.depthTextureExtension = true;
  12292. }
  12293. else {
  12294. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12295. if (depthTextureExtension != null) {
  12296. this._caps.depthTextureExtension = true;
  12297. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12298. }
  12299. }
  12300. // Vertex array object
  12301. if (this._webGLVersion > 1) {
  12302. this._caps.vertexArrayObject = true;
  12303. }
  12304. else {
  12305. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12306. if (vertexArrayObjectExtension != null) {
  12307. this._caps.vertexArrayObject = true;
  12308. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12309. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12310. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12311. }
  12312. else {
  12313. this._caps.vertexArrayObject = false;
  12314. }
  12315. }
  12316. // Instances count
  12317. if (this._webGLVersion > 1) {
  12318. this._caps.instancedArrays = true;
  12319. }
  12320. else {
  12321. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12322. if (instanceExtension != null) {
  12323. this._caps.instancedArrays = true;
  12324. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12325. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12326. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12327. }
  12328. else {
  12329. this._caps.instancedArrays = false;
  12330. }
  12331. }
  12332. // Intelligently add supported compressed formats in order to check for.
  12333. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12334. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12335. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12336. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12337. if (this._caps.astc)
  12338. this.texturesSupported.push('-astc.ktx');
  12339. if (this._caps.s3tc)
  12340. this.texturesSupported.push('-dxt.ktx');
  12341. if (this._caps.pvrtc)
  12342. this.texturesSupported.push('-pvrtc.ktx');
  12343. if (this._caps.etc2)
  12344. this.texturesSupported.push('-etc2.ktx');
  12345. if (this._caps.etc1)
  12346. this.texturesSupported.push('-etc1.ktx');
  12347. if (this._gl.getShaderPrecisionFormat) {
  12348. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12349. if (highp) {
  12350. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12351. }
  12352. }
  12353. // Depth buffer
  12354. this.setDepthBuffer(true);
  12355. this.setDepthFunctionToLessOrEqual();
  12356. this.setDepthWrite(true);
  12357. // Texture maps
  12358. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12359. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12360. this._nextFreeTextureSlots.push(slot);
  12361. }
  12362. };
  12363. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12364. /**
  12365. * Gets version of the current webGL context
  12366. */
  12367. get: function () {
  12368. return this._webGLVersion;
  12369. },
  12370. enumerable: true,
  12371. configurable: true
  12372. });
  12373. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12374. /**
  12375. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12376. */
  12377. get: function () {
  12378. return this._isStencilEnable;
  12379. },
  12380. enumerable: true,
  12381. configurable: true
  12382. });
  12383. Engine.prototype._prepareWorkingCanvas = function () {
  12384. if (this._workingCanvas) {
  12385. return;
  12386. }
  12387. this._workingCanvas = document.createElement("canvas");
  12388. var context = this._workingCanvas.getContext("2d");
  12389. if (context) {
  12390. this._workingContext = context;
  12391. }
  12392. };
  12393. /**
  12394. * Reset the texture cache to empty state
  12395. */
  12396. Engine.prototype.resetTextureCache = function () {
  12397. for (var key in this._boundTexturesCache) {
  12398. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12399. continue;
  12400. }
  12401. var boundTexture = this._boundTexturesCache[key];
  12402. if (boundTexture) {
  12403. this._removeDesignatedSlot(boundTexture);
  12404. }
  12405. this._boundTexturesCache[key] = null;
  12406. }
  12407. if (!this.disableTextureBindingOptimization) {
  12408. this._nextFreeTextureSlots = [];
  12409. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12410. this._nextFreeTextureSlots.push(slot);
  12411. }
  12412. }
  12413. this._currentTextureChannel = -1;
  12414. };
  12415. /**
  12416. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12417. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12418. * @returns true if engine is in deterministic lock step mode
  12419. */
  12420. Engine.prototype.isDeterministicLockStep = function () {
  12421. return this._deterministicLockstep;
  12422. };
  12423. /**
  12424. * Gets the max steps when engine is running in deterministic lock step
  12425. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12426. * @returns the max steps
  12427. */
  12428. Engine.prototype.getLockstepMaxSteps = function () {
  12429. return this._lockstepMaxSteps;
  12430. };
  12431. /**
  12432. * Gets an object containing information about the current webGL context
  12433. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12434. */
  12435. Engine.prototype.getGlInfo = function () {
  12436. return {
  12437. vendor: this._glVendor,
  12438. renderer: this._glRenderer,
  12439. version: this._glVersion
  12440. };
  12441. };
  12442. /**
  12443. * Gets current aspect ratio
  12444. * @param camera defines the camera to use to get the aspect ratio
  12445. * @param useScreen defines if screen size must be used (or the current render target if any)
  12446. * @returns a number defining the aspect ratio
  12447. */
  12448. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12449. if (useScreen === void 0) { useScreen = false; }
  12450. var viewport = camera.viewport;
  12451. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12452. };
  12453. /**
  12454. * Gets the current render width
  12455. * @param useScreen defines if screen size must be used (or the current render target if any)
  12456. * @returns a number defining the current render width
  12457. */
  12458. Engine.prototype.getRenderWidth = function (useScreen) {
  12459. if (useScreen === void 0) { useScreen = false; }
  12460. if (!useScreen && this._currentRenderTarget) {
  12461. return this._currentRenderTarget.width;
  12462. }
  12463. return this._gl.drawingBufferWidth;
  12464. };
  12465. /**
  12466. * Gets the current render height
  12467. * @param useScreen defines if screen size must be used (or the current render target if any)
  12468. * @returns a number defining the current render height
  12469. */
  12470. Engine.prototype.getRenderHeight = function (useScreen) {
  12471. if (useScreen === void 0) { useScreen = false; }
  12472. if (!useScreen && this._currentRenderTarget) {
  12473. return this._currentRenderTarget.height;
  12474. }
  12475. return this._gl.drawingBufferHeight;
  12476. };
  12477. /**
  12478. * Gets the HTML canvas attached with the current webGL context
  12479. * @returns a HTML canvas
  12480. */
  12481. Engine.prototype.getRenderingCanvas = function () {
  12482. return this._renderingCanvas;
  12483. };
  12484. /**
  12485. * Gets the client rect of the HTML canvas attached with the current webGL context
  12486. * @returns a client rectanglee
  12487. */
  12488. Engine.prototype.getRenderingCanvasClientRect = function () {
  12489. if (!this._renderingCanvas) {
  12490. return null;
  12491. }
  12492. return this._renderingCanvas.getBoundingClientRect();
  12493. };
  12494. /**
  12495. * Defines the hardware scaling level.
  12496. * By default the hardware scaling level is computed from the window device ratio.
  12497. * 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.
  12498. * @param level defines the level to use
  12499. */
  12500. Engine.prototype.setHardwareScalingLevel = function (level) {
  12501. this._hardwareScalingLevel = level;
  12502. this.resize();
  12503. };
  12504. /**
  12505. * Gets the current hardware scaling level.
  12506. * By default the hardware scaling level is computed from the window device ratio.
  12507. * 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.
  12508. * @returns a number indicating the current hardware scaling level
  12509. */
  12510. Engine.prototype.getHardwareScalingLevel = function () {
  12511. return this._hardwareScalingLevel;
  12512. };
  12513. /**
  12514. * Gets the list of loaded textures
  12515. * @returns an array containing all loaded textures
  12516. */
  12517. Engine.prototype.getLoadedTexturesCache = function () {
  12518. return this._internalTexturesCache;
  12519. };
  12520. /**
  12521. * Gets the object containing all engine capabilities
  12522. * @returns the EngineCapabilities object
  12523. */
  12524. Engine.prototype.getCaps = function () {
  12525. return this._caps;
  12526. };
  12527. Object.defineProperty(Engine.prototype, "drawCalls", {
  12528. /** @hidden */
  12529. get: function () {
  12530. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12531. return 0;
  12532. },
  12533. enumerable: true,
  12534. configurable: true
  12535. });
  12536. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12537. /** @hidden */
  12538. get: function () {
  12539. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12540. return null;
  12541. },
  12542. enumerable: true,
  12543. configurable: true
  12544. });
  12545. /**
  12546. * Gets the current depth function
  12547. * @returns a number defining the depth function
  12548. */
  12549. Engine.prototype.getDepthFunction = function () {
  12550. return this._depthCullingState.depthFunc;
  12551. };
  12552. /**
  12553. * Sets the current depth function
  12554. * @param depthFunc defines the function to use
  12555. */
  12556. Engine.prototype.setDepthFunction = function (depthFunc) {
  12557. this._depthCullingState.depthFunc = depthFunc;
  12558. };
  12559. /**
  12560. * Sets the current depth function to GREATER
  12561. */
  12562. Engine.prototype.setDepthFunctionToGreater = function () {
  12563. this._depthCullingState.depthFunc = this._gl.GREATER;
  12564. };
  12565. /**
  12566. * Sets the current depth function to GEQUAL
  12567. */
  12568. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12569. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12570. };
  12571. /**
  12572. * Sets the current depth function to LESS
  12573. */
  12574. Engine.prototype.setDepthFunctionToLess = function () {
  12575. this._depthCullingState.depthFunc = this._gl.LESS;
  12576. };
  12577. /**
  12578. * Sets the current depth function to LEQUAL
  12579. */
  12580. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12581. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12582. };
  12583. /**
  12584. * Gets a boolean indicating if stencil buffer is enabled
  12585. * @returns the current stencil buffer state
  12586. */
  12587. Engine.prototype.getStencilBuffer = function () {
  12588. return this._stencilState.stencilTest;
  12589. };
  12590. /**
  12591. * Enable or disable the stencil buffer
  12592. * @param enable defines if the stencil buffer must be enabled or disabled
  12593. */
  12594. Engine.prototype.setStencilBuffer = function (enable) {
  12595. this._stencilState.stencilTest = enable;
  12596. };
  12597. /**
  12598. * Gets the current stencil mask
  12599. * @returns a number defining the new stencil mask to use
  12600. */
  12601. Engine.prototype.getStencilMask = function () {
  12602. return this._stencilState.stencilMask;
  12603. };
  12604. /**
  12605. * Sets the current stencil mask
  12606. * @param mask defines the new stencil mask to use
  12607. */
  12608. Engine.prototype.setStencilMask = function (mask) {
  12609. this._stencilState.stencilMask = mask;
  12610. };
  12611. /**
  12612. * Gets the current stencil function
  12613. * @returns a number defining the stencil function to use
  12614. */
  12615. Engine.prototype.getStencilFunction = function () {
  12616. return this._stencilState.stencilFunc;
  12617. };
  12618. /**
  12619. * Gets the current stencil reference value
  12620. * @returns a number defining the stencil reference value to use
  12621. */
  12622. Engine.prototype.getStencilFunctionReference = function () {
  12623. return this._stencilState.stencilFuncRef;
  12624. };
  12625. /**
  12626. * Gets the current stencil mask
  12627. * @returns a number defining the stencil mask to use
  12628. */
  12629. Engine.prototype.getStencilFunctionMask = function () {
  12630. return this._stencilState.stencilFuncMask;
  12631. };
  12632. /**
  12633. * Sets the current stencil function
  12634. * @param stencilFunc defines the new stencil function to use
  12635. */
  12636. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12637. this._stencilState.stencilFunc = stencilFunc;
  12638. };
  12639. /**
  12640. * Sets the current stencil reference
  12641. * @param reference defines the new stencil reference to use
  12642. */
  12643. Engine.prototype.setStencilFunctionReference = function (reference) {
  12644. this._stencilState.stencilFuncRef = reference;
  12645. };
  12646. /**
  12647. * Sets the current stencil mask
  12648. * @param mask defines the new stencil mask to use
  12649. */
  12650. Engine.prototype.setStencilFunctionMask = function (mask) {
  12651. this._stencilState.stencilFuncMask = mask;
  12652. };
  12653. /**
  12654. * Gets the current stencil operation when stencil fails
  12655. * @returns a number defining stencil operation to use when stencil fails
  12656. */
  12657. Engine.prototype.getStencilOperationFail = function () {
  12658. return this._stencilState.stencilOpStencilFail;
  12659. };
  12660. /**
  12661. * Gets the current stencil operation when depth fails
  12662. * @returns a number defining stencil operation to use when depth fails
  12663. */
  12664. Engine.prototype.getStencilOperationDepthFail = function () {
  12665. return this._stencilState.stencilOpDepthFail;
  12666. };
  12667. /**
  12668. * Gets the current stencil operation when stencil passes
  12669. * @returns a number defining stencil operation to use when stencil passes
  12670. */
  12671. Engine.prototype.getStencilOperationPass = function () {
  12672. return this._stencilState.stencilOpStencilDepthPass;
  12673. };
  12674. /**
  12675. * Sets the stencil operation to use when stencil fails
  12676. * @param operation defines the stencil operation to use when stencil fails
  12677. */
  12678. Engine.prototype.setStencilOperationFail = function (operation) {
  12679. this._stencilState.stencilOpStencilFail = operation;
  12680. };
  12681. /**
  12682. * Sets the stencil operation to use when depth fails
  12683. * @param operation defines the stencil operation to use when depth fails
  12684. */
  12685. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12686. this._stencilState.stencilOpDepthFail = operation;
  12687. };
  12688. /**
  12689. * Sets the stencil operation to use when stencil passes
  12690. * @param operation defines the stencil operation to use when stencil passes
  12691. */
  12692. Engine.prototype.setStencilOperationPass = function (operation) {
  12693. this._stencilState.stencilOpStencilDepthPass = operation;
  12694. };
  12695. /**
  12696. * Sets a boolean indicating if the dithering state is enabled or disabled
  12697. * @param value defines the dithering state
  12698. */
  12699. Engine.prototype.setDitheringState = function (value) {
  12700. if (value) {
  12701. this._gl.enable(this._gl.DITHER);
  12702. }
  12703. else {
  12704. this._gl.disable(this._gl.DITHER);
  12705. }
  12706. };
  12707. /**
  12708. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12709. * @param value defines the rasterizer state
  12710. */
  12711. Engine.prototype.setRasterizerState = function (value) {
  12712. if (value) {
  12713. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12714. }
  12715. else {
  12716. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12717. }
  12718. };
  12719. /**
  12720. * stop executing a render loop function and remove it from the execution array
  12721. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12722. */
  12723. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12724. if (!renderFunction) {
  12725. this._activeRenderLoops = [];
  12726. return;
  12727. }
  12728. var index = this._activeRenderLoops.indexOf(renderFunction);
  12729. if (index >= 0) {
  12730. this._activeRenderLoops.splice(index, 1);
  12731. }
  12732. };
  12733. /** @hidden */
  12734. Engine.prototype._renderLoop = function () {
  12735. if (!this._contextWasLost) {
  12736. var shouldRender = true;
  12737. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12738. shouldRender = false;
  12739. }
  12740. if (shouldRender) {
  12741. // Start new frame
  12742. this.beginFrame();
  12743. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12744. var renderFunction = this._activeRenderLoops[index];
  12745. renderFunction();
  12746. }
  12747. // Present
  12748. this.endFrame();
  12749. }
  12750. }
  12751. if (this._activeRenderLoops.length > 0) {
  12752. // Register new frame
  12753. var requester = null;
  12754. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12755. requester = this._vrDisplay;
  12756. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12757. }
  12758. else {
  12759. this._renderingQueueLaunched = false;
  12760. }
  12761. };
  12762. /**
  12763. * Register and execute a render loop. The engine can have more than one render function
  12764. * @param renderFunction defines the function to continuously execute
  12765. */
  12766. Engine.prototype.runRenderLoop = function (renderFunction) {
  12767. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12768. return;
  12769. }
  12770. this._activeRenderLoops.push(renderFunction);
  12771. if (!this._renderingQueueLaunched) {
  12772. this._renderingQueueLaunched = true;
  12773. this._bindedRenderFunction = this._renderLoop.bind(this);
  12774. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12775. }
  12776. };
  12777. /**
  12778. * Toggle full screen mode
  12779. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12780. * @param options defines an option object to be sent to the requestFullscreen function
  12781. */
  12782. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12783. if (this.isFullscreen) {
  12784. BABYLON.Tools.ExitFullscreen();
  12785. }
  12786. else {
  12787. this._pointerLockRequested = requestPointerLock;
  12788. if (this._renderingCanvas) {
  12789. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12790. }
  12791. }
  12792. };
  12793. /**
  12794. * Clear the current render buffer or the current render target (if any is set up)
  12795. * @param color defines the color to use
  12796. * @param backBuffer defines if the back buffer must be cleared
  12797. * @param depth defines if the depth buffer must be cleared
  12798. * @param stencil defines if the stencil buffer must be cleared
  12799. */
  12800. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12801. if (stencil === void 0) { stencil = false; }
  12802. this.applyStates();
  12803. var mode = 0;
  12804. if (backBuffer && color) {
  12805. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12806. mode |= this._gl.COLOR_BUFFER_BIT;
  12807. }
  12808. if (depth) {
  12809. this._gl.clearDepth(1.0);
  12810. mode |= this._gl.DEPTH_BUFFER_BIT;
  12811. }
  12812. if (stencil) {
  12813. this._gl.clearStencil(0);
  12814. mode |= this._gl.STENCIL_BUFFER_BIT;
  12815. }
  12816. this._gl.clear(mode);
  12817. };
  12818. /**
  12819. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12820. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12821. * @param y defines the y-coordinate of the corner of the clear rectangle
  12822. * @param width defines the width of the clear rectangle
  12823. * @param height defines the height of the clear rectangle
  12824. * @param clearColor defines the clear color
  12825. */
  12826. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12827. var gl = this._gl;
  12828. // Save state
  12829. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12830. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12831. // Change state
  12832. gl.enable(gl.SCISSOR_TEST);
  12833. gl.scissor(x, y, width, height);
  12834. // Clear
  12835. this.clear(clearColor, true, true, true);
  12836. // Restore state
  12837. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12838. if (curScissor === true) {
  12839. gl.enable(gl.SCISSOR_TEST);
  12840. }
  12841. else {
  12842. gl.disable(gl.SCISSOR_TEST);
  12843. }
  12844. };
  12845. /**
  12846. * Set the WebGL's viewport
  12847. * @param viewport defines the viewport element to be used
  12848. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12849. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12850. */
  12851. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12852. var width = requiredWidth || this.getRenderWidth();
  12853. var height = requiredHeight || this.getRenderHeight();
  12854. var x = viewport.x || 0;
  12855. var y = viewport.y || 0;
  12856. this._cachedViewport = viewport;
  12857. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12858. };
  12859. /**
  12860. * Directly set the WebGL Viewport
  12861. * @param x defines the x coordinate of the viewport (in screen space)
  12862. * @param y defines the y coordinate of the viewport (in screen space)
  12863. * @param width defines the width of the viewport (in screen space)
  12864. * @param height defines the height of the viewport (in screen space)
  12865. * @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
  12866. */
  12867. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12868. var currentViewport = this._cachedViewport;
  12869. this._cachedViewport = null;
  12870. this._gl.viewport(x, y, width, height);
  12871. return currentViewport;
  12872. };
  12873. /**
  12874. * Begin a new frame
  12875. */
  12876. Engine.prototype.beginFrame = function () {
  12877. this.onBeginFrameObservable.notifyObservers(this);
  12878. this._measureFps();
  12879. };
  12880. /**
  12881. * Enf the current frame
  12882. */
  12883. Engine.prototype.endFrame = function () {
  12884. // Force a flush in case we are using a bad OS.
  12885. if (this._badOS) {
  12886. this.flushFramebuffer();
  12887. }
  12888. // Submit frame to the vr device, if enabled
  12889. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12890. // TODO: We should only submit the frame if we read frameData successfully.
  12891. this._vrDisplay.submitFrame();
  12892. }
  12893. this.onEndFrameObservable.notifyObservers(this);
  12894. };
  12895. /**
  12896. * Resize the view according to the canvas' size
  12897. */
  12898. Engine.prototype.resize = function () {
  12899. // We're not resizing the size of the canvas while in VR mode & presenting
  12900. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12901. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12902. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12903. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12904. }
  12905. };
  12906. /**
  12907. * Force a specific size of the canvas
  12908. * @param width defines the new canvas' width
  12909. * @param height defines the new canvas' height
  12910. */
  12911. Engine.prototype.setSize = function (width, height) {
  12912. if (!this._renderingCanvas) {
  12913. return;
  12914. }
  12915. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12916. return;
  12917. }
  12918. this._renderingCanvas.width = width;
  12919. this._renderingCanvas.height = height;
  12920. for (var index = 0; index < this.scenes.length; index++) {
  12921. var scene = this.scenes[index];
  12922. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12923. var cam = scene.cameras[camIndex];
  12924. cam._currentRenderId = 0;
  12925. }
  12926. }
  12927. if (this.onResizeObservable.hasObservers) {
  12928. this.onResizeObservable.notifyObservers(this);
  12929. }
  12930. };
  12931. // WebVR functions
  12932. /**
  12933. * Gets a boolean indicating if a webVR device was detected
  12934. * @returns true if a webVR device was detected
  12935. */
  12936. Engine.prototype.isVRDevicePresent = function () {
  12937. return !!this._vrDisplay;
  12938. };
  12939. /**
  12940. * Gets the current webVR device
  12941. * @returns the current webVR device (or null)
  12942. */
  12943. Engine.prototype.getVRDevice = function () {
  12944. return this._vrDisplay;
  12945. };
  12946. /**
  12947. * Initializes a webVR display and starts listening to display change events
  12948. * The onVRDisplayChangedObservable will be notified upon these changes
  12949. * @returns The onVRDisplayChangedObservable
  12950. */
  12951. Engine.prototype.initWebVR = function () {
  12952. this.initWebVRAsync();
  12953. return this.onVRDisplayChangedObservable;
  12954. };
  12955. /**
  12956. * Initializes a webVR display and starts listening to display change events
  12957. * The onVRDisplayChangedObservable will be notified upon these changes
  12958. * @returns A promise containing a VRDisplay and if vr is supported
  12959. */
  12960. Engine.prototype.initWebVRAsync = function () {
  12961. var _this = this;
  12962. var notifyObservers = function () {
  12963. var eventArgs = {
  12964. vrDisplay: _this._vrDisplay,
  12965. vrSupported: _this._vrSupported
  12966. };
  12967. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12968. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12969. };
  12970. if (!this._onVrDisplayConnect) {
  12971. this._onVrDisplayConnect = function (event) {
  12972. _this._vrDisplay = event.display;
  12973. notifyObservers();
  12974. };
  12975. this._onVrDisplayDisconnect = function () {
  12976. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12977. _this._vrDisplay = undefined;
  12978. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12979. notifyObservers();
  12980. };
  12981. this._onVrDisplayPresentChange = function () {
  12982. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12983. };
  12984. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12985. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12986. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12987. }
  12988. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12989. this._webVRInitPromise.then(notifyObservers);
  12990. return this._webVRInitPromise;
  12991. };
  12992. /**
  12993. * Call this function to switch to webVR mode
  12994. * Will do nothing if webVR is not supported or if there is no webVR device
  12995. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12996. */
  12997. Engine.prototype.enableVR = function () {
  12998. var _this = this;
  12999. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13000. var onResolved = function () {
  13001. _this.onVRRequestPresentComplete.notifyObservers(true);
  13002. _this._onVRFullScreenTriggered();
  13003. };
  13004. var onRejected = function () {
  13005. _this.onVRRequestPresentComplete.notifyObservers(false);
  13006. };
  13007. this.onVRRequestPresentStart.notifyObservers(this);
  13008. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13009. }
  13010. };
  13011. /**
  13012. * Call this function to leave webVR mode
  13013. * Will do nothing if webVR is not supported or if there is no webVR device
  13014. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13015. */
  13016. Engine.prototype.disableVR = function () {
  13017. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13018. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13019. }
  13020. };
  13021. Engine.prototype._getVRDisplaysAsync = function () {
  13022. var _this = this;
  13023. return new Promise(function (res, rej) {
  13024. if (navigator.getVRDisplays) {
  13025. navigator.getVRDisplays().then(function (devices) {
  13026. _this._vrSupported = true;
  13027. // note that devices may actually be an empty array. This is fine;
  13028. // we expect this._vrDisplay to be undefined in this case.
  13029. _this._vrDisplay = devices[0];
  13030. res({
  13031. vrDisplay: _this._vrDisplay,
  13032. vrSupported: _this._vrSupported
  13033. });
  13034. });
  13035. }
  13036. else {
  13037. _this._vrDisplay = undefined;
  13038. _this._vrSupported = false;
  13039. res({
  13040. vrDisplay: _this._vrDisplay,
  13041. vrSupported: _this._vrSupported
  13042. });
  13043. }
  13044. });
  13045. };
  13046. /**
  13047. * Binds the frame buffer to the specified texture.
  13048. * @param texture The texture to render to or null for the default canvas
  13049. * @param faceIndex The face of the texture to render to in case of cube texture
  13050. * @param requiredWidth The width of the target to render to
  13051. * @param requiredHeight The height of the target to render to
  13052. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13053. * @param depthStencilTexture The depth stencil texture to use to render
  13054. */
  13055. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  13056. if (this._currentRenderTarget) {
  13057. this.unBindFramebuffer(this._currentRenderTarget);
  13058. }
  13059. this._currentRenderTarget = texture;
  13060. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13061. var gl = this._gl;
  13062. if (texture.isCube) {
  13063. if (faceIndex === undefined) {
  13064. faceIndex = 0;
  13065. }
  13066. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13067. if (depthStencilTexture) {
  13068. if (depthStencilTexture._generateStencilBuffer) {
  13069. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13070. }
  13071. else {
  13072. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13073. }
  13074. }
  13075. }
  13076. if (this._cachedViewport && !forceFullscreenViewport) {
  13077. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13078. }
  13079. else {
  13080. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  13081. }
  13082. this.wipeCaches();
  13083. };
  13084. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13085. if (this._currentFramebuffer !== framebuffer) {
  13086. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13087. this._currentFramebuffer = framebuffer;
  13088. }
  13089. };
  13090. /**
  13091. * Unbind the current render target texture from the webGL context
  13092. * @param texture defines the render target texture to unbind
  13093. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13094. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13095. */
  13096. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13097. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13098. this._currentRenderTarget = null;
  13099. // If MSAA, we need to bitblt back to main texture
  13100. var gl = this._gl;
  13101. if (texture._MSAAFramebuffer) {
  13102. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13103. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13104. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13105. }
  13106. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13107. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13108. gl.generateMipmap(gl.TEXTURE_2D);
  13109. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13110. }
  13111. if (onBeforeUnbind) {
  13112. if (texture._MSAAFramebuffer) {
  13113. // Bind the correct framebuffer
  13114. this.bindUnboundFramebuffer(texture._framebuffer);
  13115. }
  13116. onBeforeUnbind();
  13117. }
  13118. this.bindUnboundFramebuffer(null);
  13119. };
  13120. /**
  13121. * Unbind a list of render target textures from the webGL context
  13122. * This is used only when drawBuffer extension or webGL2 are active
  13123. * @param textures defines the render target textures to unbind
  13124. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13125. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13126. */
  13127. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13128. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13129. this._currentRenderTarget = null;
  13130. // If MSAA, we need to bitblt back to main texture
  13131. var gl = this._gl;
  13132. if (textures[0]._MSAAFramebuffer) {
  13133. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13134. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13135. var attachments = textures[0]._attachments;
  13136. if (!attachments) {
  13137. attachments = new Array(textures.length);
  13138. textures[0]._attachments = attachments;
  13139. }
  13140. for (var i = 0; i < textures.length; i++) {
  13141. var texture = textures[i];
  13142. for (var j = 0; j < attachments.length; j++) {
  13143. attachments[j] = gl.NONE;
  13144. }
  13145. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13146. gl.readBuffer(attachments[i]);
  13147. gl.drawBuffers(attachments);
  13148. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13149. }
  13150. for (var i = 0; i < attachments.length; i++) {
  13151. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13152. }
  13153. gl.drawBuffers(attachments);
  13154. }
  13155. for (var i = 0; i < textures.length; i++) {
  13156. var texture = textures[i];
  13157. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13158. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13159. gl.generateMipmap(gl.TEXTURE_2D);
  13160. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13161. }
  13162. }
  13163. if (onBeforeUnbind) {
  13164. if (textures[0]._MSAAFramebuffer) {
  13165. // Bind the correct framebuffer
  13166. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13167. }
  13168. onBeforeUnbind();
  13169. }
  13170. this.bindUnboundFramebuffer(null);
  13171. };
  13172. /**
  13173. * Force the mipmap generation for the given render target texture
  13174. * @param texture defines the render target texture to use
  13175. */
  13176. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13177. if (texture.generateMipMaps) {
  13178. var gl = this._gl;
  13179. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13180. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13181. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13182. }
  13183. };
  13184. /**
  13185. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13186. */
  13187. Engine.prototype.flushFramebuffer = function () {
  13188. this._gl.flush();
  13189. };
  13190. /**
  13191. * Unbind the current render target and bind the default framebuffer
  13192. */
  13193. Engine.prototype.restoreDefaultFramebuffer = function () {
  13194. if (this._currentRenderTarget) {
  13195. this.unBindFramebuffer(this._currentRenderTarget);
  13196. }
  13197. else {
  13198. this.bindUnboundFramebuffer(null);
  13199. }
  13200. if (this._cachedViewport) {
  13201. this.setViewport(this._cachedViewport);
  13202. }
  13203. this.wipeCaches();
  13204. };
  13205. // UBOs
  13206. /**
  13207. * Create an uniform buffer
  13208. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13209. * @param elements defines the content of the uniform buffer
  13210. * @returns the webGL uniform buffer
  13211. */
  13212. Engine.prototype.createUniformBuffer = function (elements) {
  13213. var ubo = this._gl.createBuffer();
  13214. if (!ubo) {
  13215. throw new Error("Unable to create uniform buffer");
  13216. }
  13217. this.bindUniformBuffer(ubo);
  13218. if (elements instanceof Float32Array) {
  13219. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13220. }
  13221. else {
  13222. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13223. }
  13224. this.bindUniformBuffer(null);
  13225. ubo.references = 1;
  13226. return ubo;
  13227. };
  13228. /**
  13229. * Create a dynamic uniform buffer
  13230. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13231. * @param elements defines the content of the uniform buffer
  13232. * @returns the webGL uniform buffer
  13233. */
  13234. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13235. var ubo = this._gl.createBuffer();
  13236. if (!ubo) {
  13237. throw new Error("Unable to create dynamic uniform buffer");
  13238. }
  13239. this.bindUniformBuffer(ubo);
  13240. if (elements instanceof Float32Array) {
  13241. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13242. }
  13243. else {
  13244. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13245. }
  13246. this.bindUniformBuffer(null);
  13247. ubo.references = 1;
  13248. return ubo;
  13249. };
  13250. /**
  13251. * Update an existing uniform buffer
  13252. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13253. * @param uniformBuffer defines the target uniform buffer
  13254. * @param elements defines the content to update
  13255. * @param offset defines the offset in the uniform buffer where update should start
  13256. * @param count defines the size of the data to update
  13257. */
  13258. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13259. this.bindUniformBuffer(uniformBuffer);
  13260. if (offset === undefined) {
  13261. offset = 0;
  13262. }
  13263. if (count === undefined) {
  13264. if (elements instanceof Float32Array) {
  13265. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13266. }
  13267. else {
  13268. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13269. }
  13270. }
  13271. else {
  13272. if (elements instanceof Float32Array) {
  13273. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13274. }
  13275. else {
  13276. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13277. }
  13278. }
  13279. this.bindUniformBuffer(null);
  13280. };
  13281. // VBOs
  13282. Engine.prototype._resetVertexBufferBinding = function () {
  13283. this.bindArrayBuffer(null);
  13284. this._cachedVertexBuffers = null;
  13285. };
  13286. /**
  13287. * Creates a vertex buffer
  13288. * @param data the data for the vertex buffer
  13289. * @returns the new WebGL static buffer
  13290. */
  13291. Engine.prototype.createVertexBuffer = function (data) {
  13292. var vbo = this._gl.createBuffer();
  13293. if (!vbo) {
  13294. throw new Error("Unable to create vertex buffer");
  13295. }
  13296. this.bindArrayBuffer(vbo);
  13297. if (data instanceof Array) {
  13298. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13299. }
  13300. else {
  13301. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13302. }
  13303. this._resetVertexBufferBinding();
  13304. vbo.references = 1;
  13305. return vbo;
  13306. };
  13307. /**
  13308. * Creates a dynamic vertex buffer
  13309. * @param data the data for the dynamic vertex buffer
  13310. * @returns the new WebGL dynamic buffer
  13311. */
  13312. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13313. var vbo = this._gl.createBuffer();
  13314. if (!vbo) {
  13315. throw new Error("Unable to create dynamic vertex buffer");
  13316. }
  13317. this.bindArrayBuffer(vbo);
  13318. if (data instanceof Array) {
  13319. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13320. }
  13321. else {
  13322. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13323. }
  13324. this._resetVertexBufferBinding();
  13325. vbo.references = 1;
  13326. return vbo;
  13327. };
  13328. /**
  13329. * Update a dynamic index buffer
  13330. * @param indexBuffer defines the target index buffer
  13331. * @param indices defines the data to update
  13332. * @param offset defines the offset in the target index buffer where update should start
  13333. */
  13334. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13335. if (offset === void 0) { offset = 0; }
  13336. // Force cache update
  13337. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13338. this.bindIndexBuffer(indexBuffer);
  13339. var arrayBuffer;
  13340. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13341. arrayBuffer = indices;
  13342. }
  13343. else {
  13344. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13345. }
  13346. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13347. this._resetIndexBufferBinding();
  13348. };
  13349. /**
  13350. * Updates a dynamic vertex buffer.
  13351. * @param vertexBuffer the vertex buffer to update
  13352. * @param data the data used to update the vertex buffer
  13353. * @param byteOffset the byte offset of the data
  13354. * @param byteLength the byte length of the data
  13355. */
  13356. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13357. this.bindArrayBuffer(vertexBuffer);
  13358. if (byteOffset === undefined) {
  13359. byteOffset = 0;
  13360. }
  13361. if (byteLength === undefined) {
  13362. if (data instanceof Array) {
  13363. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13364. }
  13365. else {
  13366. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13367. }
  13368. }
  13369. else {
  13370. if (data instanceof Array) {
  13371. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13372. }
  13373. else {
  13374. if (data instanceof ArrayBuffer) {
  13375. data = new Uint8Array(data, byteOffset, byteLength);
  13376. }
  13377. else {
  13378. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13379. }
  13380. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13381. }
  13382. }
  13383. this._resetVertexBufferBinding();
  13384. };
  13385. Engine.prototype._resetIndexBufferBinding = function () {
  13386. this.bindIndexBuffer(null);
  13387. this._cachedIndexBuffer = null;
  13388. };
  13389. /**
  13390. * Creates a new index buffer
  13391. * @param indices defines the content of the index buffer
  13392. * @param updatable defines if the index buffer must be updatable
  13393. * @returns a new webGL buffer
  13394. */
  13395. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13396. var vbo = this._gl.createBuffer();
  13397. if (!vbo) {
  13398. throw new Error("Unable to create index buffer");
  13399. }
  13400. this.bindIndexBuffer(vbo);
  13401. // Check for 32 bits indices
  13402. var arrayBuffer;
  13403. var need32Bits = false;
  13404. if (indices instanceof Uint16Array) {
  13405. arrayBuffer = indices;
  13406. }
  13407. else {
  13408. //check 32 bit support
  13409. if (this._caps.uintIndices) {
  13410. if (indices instanceof Uint32Array) {
  13411. arrayBuffer = indices;
  13412. need32Bits = true;
  13413. }
  13414. else {
  13415. //number[] or Int32Array, check if 32 bit is necessary
  13416. for (var index = 0; index < indices.length; index++) {
  13417. if (indices[index] > 65535) {
  13418. need32Bits = true;
  13419. break;
  13420. }
  13421. }
  13422. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13423. }
  13424. }
  13425. else {
  13426. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13427. arrayBuffer = new Uint16Array(indices);
  13428. }
  13429. }
  13430. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13431. this._resetIndexBufferBinding();
  13432. vbo.references = 1;
  13433. vbo.is32Bits = need32Bits;
  13434. return vbo;
  13435. };
  13436. /**
  13437. * Bind a webGL buffer to the webGL context
  13438. * @param buffer defines the buffer to bind
  13439. */
  13440. Engine.prototype.bindArrayBuffer = function (buffer) {
  13441. if (!this._vaoRecordInProgress) {
  13442. this._unbindVertexArrayObject();
  13443. }
  13444. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13445. };
  13446. /**
  13447. * Bind an uniform buffer to the current webGL context
  13448. * @param buffer defines the buffer to bind
  13449. */
  13450. Engine.prototype.bindUniformBuffer = function (buffer) {
  13451. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13452. };
  13453. /**
  13454. * Bind a buffer to the current webGL context at a given location
  13455. * @param buffer defines the buffer to bind
  13456. * @param location defines the index where to bind the buffer
  13457. */
  13458. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13459. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13460. };
  13461. /**
  13462. * Bind a specific block at a given index in a specific shader program
  13463. * @param shaderProgram defines the shader program
  13464. * @param blockName defines the block name
  13465. * @param index defines the index where to bind the block
  13466. */
  13467. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13468. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13469. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13470. };
  13471. ;
  13472. Engine.prototype.bindIndexBuffer = function (buffer) {
  13473. if (!this._vaoRecordInProgress) {
  13474. this._unbindVertexArrayObject();
  13475. }
  13476. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13477. };
  13478. Engine.prototype.bindBuffer = function (buffer, target) {
  13479. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13480. this._gl.bindBuffer(target, buffer);
  13481. this._currentBoundBuffer[target] = buffer;
  13482. }
  13483. };
  13484. /**
  13485. * update the bound buffer with the given data
  13486. * @param data defines the data to update
  13487. */
  13488. Engine.prototype.updateArrayBuffer = function (data) {
  13489. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13490. };
  13491. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13492. var pointer = this._currentBufferPointers[indx];
  13493. var changed = false;
  13494. if (!pointer.active) {
  13495. changed = true;
  13496. pointer.active = true;
  13497. pointer.index = indx;
  13498. pointer.size = size;
  13499. pointer.type = type;
  13500. pointer.normalized = normalized;
  13501. pointer.stride = stride;
  13502. pointer.offset = offset;
  13503. pointer.buffer = buffer;
  13504. }
  13505. else {
  13506. if (pointer.buffer !== buffer) {
  13507. pointer.buffer = buffer;
  13508. changed = true;
  13509. }
  13510. if (pointer.size !== size) {
  13511. pointer.size = size;
  13512. changed = true;
  13513. }
  13514. if (pointer.type !== type) {
  13515. pointer.type = type;
  13516. changed = true;
  13517. }
  13518. if (pointer.normalized !== normalized) {
  13519. pointer.normalized = normalized;
  13520. changed = true;
  13521. }
  13522. if (pointer.stride !== stride) {
  13523. pointer.stride = stride;
  13524. changed = true;
  13525. }
  13526. if (pointer.offset !== offset) {
  13527. pointer.offset = offset;
  13528. changed = true;
  13529. }
  13530. }
  13531. if (changed || this._vaoRecordInProgress) {
  13532. this.bindArrayBuffer(buffer);
  13533. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13534. }
  13535. };
  13536. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13537. if (indexBuffer == null) {
  13538. return;
  13539. }
  13540. if (this._cachedIndexBuffer !== indexBuffer) {
  13541. this._cachedIndexBuffer = indexBuffer;
  13542. this.bindIndexBuffer(indexBuffer);
  13543. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13544. }
  13545. };
  13546. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13547. var attributes = effect.getAttributesNames();
  13548. if (!this._vaoRecordInProgress) {
  13549. this._unbindVertexArrayObject();
  13550. }
  13551. this.unbindAllAttributes();
  13552. for (var index = 0; index < attributes.length; index++) {
  13553. var order = effect.getAttributeLocation(index);
  13554. if (order >= 0) {
  13555. var vertexBuffer = vertexBuffers[attributes[index]];
  13556. if (!vertexBuffer) {
  13557. continue;
  13558. }
  13559. this._gl.enableVertexAttribArray(order);
  13560. if (!this._vaoRecordInProgress) {
  13561. this._vertexAttribArraysEnabled[order] = true;
  13562. }
  13563. var buffer = vertexBuffer.getBuffer();
  13564. if (buffer) {
  13565. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13566. if (vertexBuffer.getIsInstanced()) {
  13567. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13568. if (!this._vaoRecordInProgress) {
  13569. this._currentInstanceLocations.push(order);
  13570. this._currentInstanceBuffers.push(buffer);
  13571. }
  13572. }
  13573. }
  13574. }
  13575. }
  13576. };
  13577. /**
  13578. * Records a vertex array object
  13579. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13580. * @param vertexBuffers defines the list of vertex buffers to store
  13581. * @param indexBuffer defines the index buffer to store
  13582. * @param effect defines the effect to store
  13583. * @returns the new vertex array object
  13584. */
  13585. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13586. var vao = this._gl.createVertexArray();
  13587. this._vaoRecordInProgress = true;
  13588. this._gl.bindVertexArray(vao);
  13589. this._mustWipeVertexAttributes = true;
  13590. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13591. this.bindIndexBuffer(indexBuffer);
  13592. this._vaoRecordInProgress = false;
  13593. this._gl.bindVertexArray(null);
  13594. return vao;
  13595. };
  13596. /**
  13597. * Bind a specific vertex array object
  13598. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13599. * @param vertexArrayObject defines the vertex array object to bind
  13600. * @param indexBuffer defines the index buffer to bind
  13601. */
  13602. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13603. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13604. this._cachedVertexArrayObject = vertexArrayObject;
  13605. this._gl.bindVertexArray(vertexArrayObject);
  13606. this._cachedVertexBuffers = null;
  13607. this._cachedIndexBuffer = null;
  13608. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13609. this._mustWipeVertexAttributes = true;
  13610. }
  13611. };
  13612. /**
  13613. * Bind webGl buffers directly to the webGL context
  13614. * @param vertexBuffer defines the vertex buffer to bind
  13615. * @param indexBuffer defines the index buffer to bind
  13616. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13617. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13618. * @param effect defines the effect associated with the vertex buffer
  13619. */
  13620. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13621. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13622. this._cachedVertexBuffers = vertexBuffer;
  13623. this._cachedEffectForVertexBuffers = effect;
  13624. var attributesCount = effect.getAttributesCount();
  13625. this._unbindVertexArrayObject();
  13626. this.unbindAllAttributes();
  13627. var offset = 0;
  13628. for (var index = 0; index < attributesCount; index++) {
  13629. if (index < vertexDeclaration.length) {
  13630. var order = effect.getAttributeLocation(index);
  13631. if (order >= 0) {
  13632. this._gl.enableVertexAttribArray(order);
  13633. this._vertexAttribArraysEnabled[order] = true;
  13634. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13635. }
  13636. offset += vertexDeclaration[index] * 4;
  13637. }
  13638. }
  13639. }
  13640. this._bindIndexBufferWithCache(indexBuffer);
  13641. };
  13642. Engine.prototype._unbindVertexArrayObject = function () {
  13643. if (!this._cachedVertexArrayObject) {
  13644. return;
  13645. }
  13646. this._cachedVertexArrayObject = null;
  13647. this._gl.bindVertexArray(null);
  13648. };
  13649. /**
  13650. * Bind a list of vertex buffers to the webGL context
  13651. * @param vertexBuffers defines the list of vertex buffers to bind
  13652. * @param indexBuffer defines the index buffer to bind
  13653. * @param effect defines the effect associated with the vertex buffers
  13654. */
  13655. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13656. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13657. this._cachedVertexBuffers = vertexBuffers;
  13658. this._cachedEffectForVertexBuffers = effect;
  13659. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13660. }
  13661. this._bindIndexBufferWithCache(indexBuffer);
  13662. };
  13663. /**
  13664. * Unbind all instance attributes
  13665. */
  13666. Engine.prototype.unbindInstanceAttributes = function () {
  13667. var boundBuffer;
  13668. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13669. var instancesBuffer = this._currentInstanceBuffers[i];
  13670. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13671. boundBuffer = instancesBuffer;
  13672. this.bindArrayBuffer(instancesBuffer);
  13673. }
  13674. var offsetLocation = this._currentInstanceLocations[i];
  13675. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13676. }
  13677. this._currentInstanceBuffers.length = 0;
  13678. this._currentInstanceLocations.length = 0;
  13679. };
  13680. /**
  13681. * Release and free the memory of a vertex array object
  13682. * @param vao defines the vertex array object to delete
  13683. */
  13684. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13685. this._gl.deleteVertexArray(vao);
  13686. };
  13687. /** @hidden */
  13688. Engine.prototype._releaseBuffer = function (buffer) {
  13689. buffer.references--;
  13690. if (buffer.references === 0) {
  13691. this._gl.deleteBuffer(buffer);
  13692. return true;
  13693. }
  13694. return false;
  13695. };
  13696. /**
  13697. * Creates a webGL buffer to use with instanciation
  13698. * @param capacity defines the size of the buffer
  13699. * @returns the webGL buffer
  13700. */
  13701. Engine.prototype.createInstancesBuffer = function (capacity) {
  13702. var buffer = this._gl.createBuffer();
  13703. if (!buffer) {
  13704. throw new Error("Unable to create instance buffer");
  13705. }
  13706. buffer.capacity = capacity;
  13707. this.bindArrayBuffer(buffer);
  13708. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13709. return buffer;
  13710. };
  13711. /**
  13712. * Delete a webGL buffer used with instanciation
  13713. * @param buffer defines the webGL buffer to delete
  13714. */
  13715. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13716. this._gl.deleteBuffer(buffer);
  13717. };
  13718. /**
  13719. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13720. * @param instancesBuffer defines the webGL buffer to update and bind
  13721. * @param data defines the data to store in the buffer
  13722. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13723. */
  13724. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13725. this.bindArrayBuffer(instancesBuffer);
  13726. if (data) {
  13727. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13728. }
  13729. if (offsetLocations[0].index !== undefined) {
  13730. var stride = 0;
  13731. for (var i = 0; i < offsetLocations.length; i++) {
  13732. var ai = offsetLocations[i];
  13733. stride += ai.attributeSize * 4;
  13734. }
  13735. for (var i = 0; i < offsetLocations.length; i++) {
  13736. var ai = offsetLocations[i];
  13737. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13738. this._gl.enableVertexAttribArray(ai.index);
  13739. this._vertexAttribArraysEnabled[ai.index] = true;
  13740. }
  13741. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13742. this._gl.vertexAttribDivisor(ai.index, 1);
  13743. this._currentInstanceLocations.push(ai.index);
  13744. this._currentInstanceBuffers.push(instancesBuffer);
  13745. }
  13746. }
  13747. else {
  13748. for (var index = 0; index < 4; index++) {
  13749. var offsetLocation = offsetLocations[index];
  13750. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13751. this._gl.enableVertexAttribArray(offsetLocation);
  13752. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13753. }
  13754. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13755. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13756. this._currentInstanceLocations.push(offsetLocation);
  13757. this._currentInstanceBuffers.push(instancesBuffer);
  13758. }
  13759. }
  13760. };
  13761. /**
  13762. * Apply all cached states (depth, culling, stencil and alpha)
  13763. */
  13764. Engine.prototype.applyStates = function () {
  13765. this._depthCullingState.apply(this._gl);
  13766. this._stencilState.apply(this._gl);
  13767. this._alphaState.apply(this._gl);
  13768. };
  13769. /**
  13770. * Send a draw order
  13771. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13772. * @param indexStart defines the starting index
  13773. * @param indexCount defines the number of index to draw
  13774. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13775. */
  13776. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13777. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13778. };
  13779. /**
  13780. * Draw a list of points
  13781. * @param verticesStart defines the index of first vertex to draw
  13782. * @param verticesCount defines the count of vertices to draw
  13783. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13784. */
  13785. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13786. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13787. };
  13788. /**
  13789. * Draw a list of unindexed primitives
  13790. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13791. * @param verticesStart defines the index of first vertex to draw
  13792. * @param verticesCount defines the count of vertices to draw
  13793. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13794. */
  13795. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13796. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13797. };
  13798. /**
  13799. * Draw a list of indexed primitives
  13800. * @param fillMode defines the primitive to use
  13801. * @param indexStart defines the starting index
  13802. * @param indexCount defines the number of index to draw
  13803. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13804. */
  13805. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13806. // Apply states
  13807. this.applyStates();
  13808. this._drawCalls.addCount(1, false);
  13809. // Render
  13810. var drawMode = this._drawMode(fillMode);
  13811. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13812. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13813. if (instancesCount) {
  13814. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13815. }
  13816. else {
  13817. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13818. }
  13819. };
  13820. /**
  13821. * Draw a list of unindexed primitives
  13822. * @param fillMode defines the primitive to use
  13823. * @param verticesStart defines the index of first vertex to draw
  13824. * @param verticesCount defines the count of vertices to draw
  13825. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13826. */
  13827. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13828. // Apply states
  13829. this.applyStates();
  13830. this._drawCalls.addCount(1, false);
  13831. var drawMode = this._drawMode(fillMode);
  13832. if (instancesCount) {
  13833. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13834. }
  13835. else {
  13836. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13837. }
  13838. };
  13839. Engine.prototype._drawMode = function (fillMode) {
  13840. switch (fillMode) {
  13841. // Triangle views
  13842. case BABYLON.Material.TriangleFillMode:
  13843. return this._gl.TRIANGLES;
  13844. case BABYLON.Material.PointFillMode:
  13845. return this._gl.POINTS;
  13846. case BABYLON.Material.WireFrameFillMode:
  13847. return this._gl.LINES;
  13848. // Draw modes
  13849. case BABYLON.Material.PointListDrawMode:
  13850. return this._gl.POINTS;
  13851. case BABYLON.Material.LineListDrawMode:
  13852. return this._gl.LINES;
  13853. case BABYLON.Material.LineLoopDrawMode:
  13854. return this._gl.LINE_LOOP;
  13855. case BABYLON.Material.LineStripDrawMode:
  13856. return this._gl.LINE_STRIP;
  13857. case BABYLON.Material.TriangleStripDrawMode:
  13858. return this._gl.TRIANGLE_STRIP;
  13859. case BABYLON.Material.TriangleFanDrawMode:
  13860. return this._gl.TRIANGLE_FAN;
  13861. default:
  13862. return this._gl.TRIANGLES;
  13863. }
  13864. };
  13865. // Shaders
  13866. /** @hidden */
  13867. Engine.prototype._releaseEffect = function (effect) {
  13868. if (this._compiledEffects[effect._key]) {
  13869. delete this._compiledEffects[effect._key];
  13870. this._deleteProgram(effect.getProgram());
  13871. }
  13872. };
  13873. /** @hidden */
  13874. Engine.prototype._deleteProgram = function (program) {
  13875. if (program) {
  13876. program.__SPECTOR_rebuildProgram = null;
  13877. if (program.transformFeedback) {
  13878. this.deleteTransformFeedback(program.transformFeedback);
  13879. program.transformFeedback = null;
  13880. }
  13881. this._gl.deleteProgram(program);
  13882. }
  13883. };
  13884. /**
  13885. * Create a new effect (used to store vertex/fragment shaders)
  13886. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13887. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13888. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13889. * @param samplers defines an array of string used to represent textures
  13890. * @param defines defines the string containing the defines to use to compile the shaders
  13891. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13892. * @param onCompiled defines a function to call when the effect creation is successful
  13893. * @param onError defines a function to call when the effect creation has failed
  13894. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13895. * @returns the new Effect
  13896. */
  13897. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13898. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13899. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13900. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13901. if (this._compiledEffects[name]) {
  13902. var compiledEffect = this._compiledEffects[name];
  13903. if (onCompiled && compiledEffect.isReady()) {
  13904. onCompiled(compiledEffect);
  13905. }
  13906. return compiledEffect;
  13907. }
  13908. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13909. effect._key = name;
  13910. this._compiledEffects[name] = effect;
  13911. return effect;
  13912. };
  13913. /**
  13914. * Create an effect to use with particle systems
  13915. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13916. * @param uniformsNames defines a list of attribute names
  13917. * @param samplers defines an array of string used to represent textures
  13918. * @param defines defines the string containing the defines to use to compile the shaders
  13919. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13920. * @param onCompiled defines a function to call when the effect creation is successful
  13921. * @param onError defines a function to call when the effect creation has failed
  13922. * @returns the new Effect
  13923. */
  13924. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13925. if (uniformsNames === void 0) { uniformsNames = []; }
  13926. if (samplers === void 0) { samplers = []; }
  13927. if (defines === void 0) { defines = ""; }
  13928. return this.createEffect({
  13929. vertex: "particles",
  13930. fragmentElement: fragmentName
  13931. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13932. };
  13933. /**
  13934. * Directly creates a webGL program
  13935. * @param vertexCode defines the vertex shader code to use
  13936. * @param fragmentCode defines the fragment shader code to use
  13937. * @param context defines the webGL context to use (if not set, the current one will be used)
  13938. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13939. * @returns the new webGL program
  13940. */
  13941. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13942. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13943. context = context || this._gl;
  13944. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13945. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13946. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13947. };
  13948. /**
  13949. * Creates a webGL program
  13950. * @param vertexCode defines the vertex shader code to use
  13951. * @param fragmentCode defines the fragment shader code to use
  13952. * @param defines defines the string containing the defines to use to compile the shaders
  13953. * @param context defines the webGL context to use (if not set, the current one will be used)
  13954. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13955. * @returns the new webGL program
  13956. */
  13957. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13958. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13959. context = context || this._gl;
  13960. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13961. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13962. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13963. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13964. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13965. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13966. return program;
  13967. };
  13968. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13969. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13970. var shaderProgram = context.createProgram();
  13971. if (!shaderProgram) {
  13972. throw new Error("Unable to create program");
  13973. }
  13974. context.attachShader(shaderProgram, vertexShader);
  13975. context.attachShader(shaderProgram, fragmentShader);
  13976. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13977. var transformFeedback = this.createTransformFeedback();
  13978. this.bindTransformFeedback(transformFeedback);
  13979. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13980. shaderProgram.transformFeedback = transformFeedback;
  13981. }
  13982. context.linkProgram(shaderProgram);
  13983. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13984. this.bindTransformFeedback(null);
  13985. }
  13986. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13987. if (!linked) {
  13988. context.validateProgram(shaderProgram);
  13989. var error = context.getProgramInfoLog(shaderProgram);
  13990. if (error) {
  13991. throw new Error(error);
  13992. }
  13993. }
  13994. context.deleteShader(vertexShader);
  13995. context.deleteShader(fragmentShader);
  13996. return shaderProgram;
  13997. };
  13998. /**
  13999. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14000. * @param shaderProgram defines the webGL program to use
  14001. * @param uniformsNames defines the list of uniform names
  14002. * @returns an array of webGL uniform locations
  14003. */
  14004. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14005. var results = new Array();
  14006. for (var index = 0; index < uniformsNames.length; index++) {
  14007. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14008. }
  14009. return results;
  14010. };
  14011. /**
  14012. * Gets the lsit of active attributes for a given webGL program
  14013. * @param shaderProgram defines the webGL program to use
  14014. * @param attributesNames defines the list of attribute names to get
  14015. * @returns an array of indices indicating the offset of each attribute
  14016. */
  14017. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14018. var results = [];
  14019. for (var index = 0; index < attributesNames.length; index++) {
  14020. try {
  14021. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14022. }
  14023. catch (e) {
  14024. results.push(-1);
  14025. }
  14026. }
  14027. return results;
  14028. };
  14029. /**
  14030. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14031. * @param effect defines the effect to activate
  14032. */
  14033. Engine.prototype.enableEffect = function (effect) {
  14034. if (!effect) {
  14035. return;
  14036. }
  14037. // Use program
  14038. this.bindSamplers(effect);
  14039. this._currentEffect = effect;
  14040. if (effect.onBind) {
  14041. effect.onBind(effect);
  14042. }
  14043. effect.onBindObservable.notifyObservers(effect);
  14044. };
  14045. /**
  14046. * Set the value of an uniform to an array of int32
  14047. * @param uniform defines the webGL uniform location where to store the value
  14048. * @param array defines the array of int32 to store
  14049. */
  14050. Engine.prototype.setIntArray = function (uniform, array) {
  14051. if (!uniform)
  14052. return;
  14053. this._gl.uniform1iv(uniform, array);
  14054. };
  14055. /**
  14056. * Set the value of an uniform to an array of int32 (stored as vec2)
  14057. * @param uniform defines the webGL uniform location where to store the value
  14058. * @param array defines the array of int32 to store
  14059. */
  14060. Engine.prototype.setIntArray2 = function (uniform, array) {
  14061. if (!uniform || array.length % 2 !== 0)
  14062. return;
  14063. this._gl.uniform2iv(uniform, array);
  14064. };
  14065. /**
  14066. * Set the value of an uniform to an array of int32 (stored as vec3)
  14067. * @param uniform defines the webGL uniform location where to store the value
  14068. * @param array defines the array of int32 to store
  14069. */
  14070. Engine.prototype.setIntArray3 = function (uniform, array) {
  14071. if (!uniform || array.length % 3 !== 0)
  14072. return;
  14073. this._gl.uniform3iv(uniform, array);
  14074. };
  14075. /**
  14076. * Set the value of an uniform to an array of int32 (stored as vec4)
  14077. * @param uniform defines the webGL uniform location where to store the value
  14078. * @param array defines the array of int32 to store
  14079. */
  14080. Engine.prototype.setIntArray4 = function (uniform, array) {
  14081. if (!uniform || array.length % 4 !== 0)
  14082. return;
  14083. this._gl.uniform4iv(uniform, array);
  14084. };
  14085. /**
  14086. * Set the value of an uniform to an array of float32
  14087. * @param uniform defines the webGL uniform location where to store the value
  14088. * @param array defines the array of float32 to store
  14089. */
  14090. Engine.prototype.setFloatArray = function (uniform, array) {
  14091. if (!uniform)
  14092. return;
  14093. this._gl.uniform1fv(uniform, array);
  14094. };
  14095. /**
  14096. * Set the value of an uniform to an array of float32 (stored as vec2)
  14097. * @param uniform defines the webGL uniform location where to store the value
  14098. * @param array defines the array of float32 to store
  14099. */
  14100. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14101. if (!uniform || array.length % 2 !== 0)
  14102. return;
  14103. this._gl.uniform2fv(uniform, array);
  14104. };
  14105. /**
  14106. * Set the value of an uniform to an array of float32 (stored as vec3)
  14107. * @param uniform defines the webGL uniform location where to store the value
  14108. * @param array defines the array of float32 to store
  14109. */
  14110. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14111. if (!uniform || array.length % 3 !== 0)
  14112. return;
  14113. this._gl.uniform3fv(uniform, array);
  14114. };
  14115. /**
  14116. * Set the value of an uniform to an array of float32 (stored as vec4)
  14117. * @param uniform defines the webGL uniform location where to store the value
  14118. * @param array defines the array of float32 to store
  14119. */
  14120. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14121. if (!uniform || array.length % 4 !== 0)
  14122. return;
  14123. this._gl.uniform4fv(uniform, array);
  14124. };
  14125. /**
  14126. * Set the value of an uniform to an array of number
  14127. * @param uniform defines the webGL uniform location where to store the value
  14128. * @param array defines the array of number to store
  14129. */
  14130. Engine.prototype.setArray = function (uniform, array) {
  14131. if (!uniform)
  14132. return;
  14133. this._gl.uniform1fv(uniform, array);
  14134. };
  14135. /**
  14136. * Set the value of an uniform to an array of number (stored as vec2)
  14137. * @param uniform defines the webGL uniform location where to store the value
  14138. * @param array defines the array of number to store
  14139. */
  14140. Engine.prototype.setArray2 = function (uniform, array) {
  14141. if (!uniform || array.length % 2 !== 0)
  14142. return;
  14143. this._gl.uniform2fv(uniform, array);
  14144. };
  14145. /**
  14146. * Set the value of an uniform to an array of number (stored as vec3)
  14147. * @param uniform defines the webGL uniform location where to store the value
  14148. * @param array defines the array of number to store
  14149. */
  14150. Engine.prototype.setArray3 = function (uniform, array) {
  14151. if (!uniform || array.length % 3 !== 0)
  14152. return;
  14153. this._gl.uniform3fv(uniform, array);
  14154. };
  14155. /**
  14156. * Set the value of an uniform to an array of number (stored as vec4)
  14157. * @param uniform defines the webGL uniform location where to store the value
  14158. * @param array defines the array of number to store
  14159. */
  14160. Engine.prototype.setArray4 = function (uniform, array) {
  14161. if (!uniform || array.length % 4 !== 0)
  14162. return;
  14163. this._gl.uniform4fv(uniform, array);
  14164. };
  14165. /**
  14166. * Set the value of an uniform to an array of float32 (stored as matrices)
  14167. * @param uniform defines the webGL uniform location where to store the value
  14168. * @param matrices defines the array of float32 to store
  14169. */
  14170. Engine.prototype.setMatrices = function (uniform, matrices) {
  14171. if (!uniform)
  14172. return;
  14173. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14174. };
  14175. /**
  14176. * Set the value of an uniform to a matrix
  14177. * @param uniform defines the webGL uniform location where to store the value
  14178. * @param matrix defines the matrix to store
  14179. */
  14180. Engine.prototype.setMatrix = function (uniform, matrix) {
  14181. if (!uniform)
  14182. return;
  14183. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14184. };
  14185. /**
  14186. * Set the value of an uniform to a matrix (3x3)
  14187. * @param uniform defines the webGL uniform location where to store the value
  14188. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14189. */
  14190. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14191. if (!uniform)
  14192. return;
  14193. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14194. };
  14195. /**
  14196. * Set the value of an uniform to a matrix (2x2)
  14197. * @param uniform defines the webGL uniform location where to store the value
  14198. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14199. */
  14200. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14201. if (!uniform)
  14202. return;
  14203. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14204. };
  14205. /**
  14206. * Set the value of an uniform to a number (int)
  14207. * @param uniform defines the webGL uniform location where to store the value
  14208. * @param value defines the int number to store
  14209. */
  14210. Engine.prototype.setInt = function (uniform, value) {
  14211. if (!uniform)
  14212. return;
  14213. this._gl.uniform1i(uniform, value);
  14214. };
  14215. /**
  14216. * Set the value of an uniform to a number (float)
  14217. * @param uniform defines the webGL uniform location where to store the value
  14218. * @param value defines the float number to store
  14219. */
  14220. Engine.prototype.setFloat = function (uniform, value) {
  14221. if (!uniform)
  14222. return;
  14223. this._gl.uniform1f(uniform, value);
  14224. };
  14225. /**
  14226. * Set the value of an uniform to a vec2
  14227. * @param uniform defines the webGL uniform location where to store the value
  14228. * @param x defines the 1st component of the value
  14229. * @param y defines the 2nd component of the value
  14230. */
  14231. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14232. if (!uniform)
  14233. return;
  14234. this._gl.uniform2f(uniform, x, y);
  14235. };
  14236. /**
  14237. * Set the value of an uniform to a vec3
  14238. * @param uniform defines the webGL uniform location where to store the value
  14239. * @param x defines the 1st component of the value
  14240. * @param y defines the 2nd component of the value
  14241. * @param z defines the 3rd component of the value
  14242. */
  14243. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14244. if (!uniform)
  14245. return;
  14246. this._gl.uniform3f(uniform, x, y, z);
  14247. };
  14248. /**
  14249. * Set the value of an uniform to a boolean
  14250. * @param uniform defines the webGL uniform location where to store the value
  14251. * @param bool defines the boolean to store
  14252. */
  14253. Engine.prototype.setBool = function (uniform, bool) {
  14254. if (!uniform)
  14255. return;
  14256. this._gl.uniform1i(uniform, bool);
  14257. };
  14258. /**
  14259. * Set the value of an uniform to a vec4
  14260. * @param uniform defines the webGL uniform location where to store the value
  14261. * @param x defines the 1st component of the value
  14262. * @param y defines the 2nd component of the value
  14263. * @param z defines the 3rd component of the value
  14264. * @param w defines the 4th component of the value
  14265. */
  14266. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14267. if (!uniform)
  14268. return;
  14269. this._gl.uniform4f(uniform, x, y, z, w);
  14270. };
  14271. /**
  14272. * Set the value of an uniform to a Color3
  14273. * @param uniform defines the webGL uniform location where to store the value
  14274. * @param color3 defines the color to store
  14275. */
  14276. Engine.prototype.setColor3 = function (uniform, color3) {
  14277. if (!uniform)
  14278. return;
  14279. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14280. };
  14281. /**
  14282. * Set the value of an uniform to a Color3 and an alpha value
  14283. * @param uniform defines the webGL uniform location where to store the value
  14284. * @param color3 defines the color to store
  14285. * @param alpha defines the alpha component to store
  14286. */
  14287. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14288. if (!uniform)
  14289. return;
  14290. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14291. };
  14292. /**
  14293. * Sets a Color4 on a uniform variable
  14294. * @param uniform defines the uniform location
  14295. * @param color4 defines the value to be set
  14296. */
  14297. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14298. if (!uniform)
  14299. return;
  14300. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14301. };
  14302. // States
  14303. /**
  14304. * Set various states to the webGL context
  14305. * @param culling defines backface culling state
  14306. * @param zOffset defines the value to apply to zOffset (0 by default)
  14307. * @param force defines if states must be applied even if cache is up to date
  14308. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14309. */
  14310. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14311. if (zOffset === void 0) { zOffset = 0; }
  14312. if (reverseSide === void 0) { reverseSide = false; }
  14313. // Culling
  14314. if (this._depthCullingState.cull !== culling || force) {
  14315. this._depthCullingState.cull = culling;
  14316. }
  14317. // Cull face
  14318. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14319. if (this._depthCullingState.cullFace !== cullFace || force) {
  14320. this._depthCullingState.cullFace = cullFace;
  14321. }
  14322. // Z offset
  14323. this.setZOffset(zOffset);
  14324. // Front face
  14325. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14326. if (this._depthCullingState.frontFace !== frontFace || force) {
  14327. this._depthCullingState.frontFace = frontFace;
  14328. }
  14329. };
  14330. /**
  14331. * Set the z offset to apply to current rendering
  14332. * @param value defines the offset to apply
  14333. */
  14334. Engine.prototype.setZOffset = function (value) {
  14335. this._depthCullingState.zOffset = value;
  14336. };
  14337. /**
  14338. * Gets the current value of the zOffset
  14339. * @returns the current zOffset state
  14340. */
  14341. Engine.prototype.getZOffset = function () {
  14342. return this._depthCullingState.zOffset;
  14343. };
  14344. /**
  14345. * Enable or disable depth buffering
  14346. * @param enable defines the state to set
  14347. */
  14348. Engine.prototype.setDepthBuffer = function (enable) {
  14349. this._depthCullingState.depthTest = enable;
  14350. };
  14351. /**
  14352. * Gets a boolean indicating if depth writing is enabled
  14353. * @returns the current depth writing state
  14354. */
  14355. Engine.prototype.getDepthWrite = function () {
  14356. return this._depthCullingState.depthMask;
  14357. };
  14358. /**
  14359. * Enable or disable depth writing
  14360. * @param enable defines the state to set
  14361. */
  14362. Engine.prototype.setDepthWrite = function (enable) {
  14363. this._depthCullingState.depthMask = enable;
  14364. };
  14365. /**
  14366. * Enable or disable color writing
  14367. * @param enable defines the state to set
  14368. */
  14369. Engine.prototype.setColorWrite = function (enable) {
  14370. this._gl.colorMask(enable, enable, enable, enable);
  14371. this._colorWrite = enable;
  14372. };
  14373. /**
  14374. * Gets a boolean indicating if color writing is enabled
  14375. * @returns the current color writing state
  14376. */
  14377. Engine.prototype.getColorWrite = function () {
  14378. return this._colorWrite;
  14379. };
  14380. /**
  14381. * Sets alpha constants used by some alpha blending modes
  14382. * @param r defines the red component
  14383. * @param g defines the green component
  14384. * @param b defines the blue component
  14385. * @param a defines the alpha component
  14386. */
  14387. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14388. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14389. };
  14390. /**
  14391. * Sets the current alpha mode
  14392. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14393. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14394. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14395. */
  14396. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14397. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14398. if (this._alphaMode === mode) {
  14399. return;
  14400. }
  14401. switch (mode) {
  14402. case Engine.ALPHA_DISABLE:
  14403. this._alphaState.alphaBlend = false;
  14404. break;
  14405. case Engine.ALPHA_PREMULTIPLIED:
  14406. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14407. this._alphaState.alphaBlend = true;
  14408. break;
  14409. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14410. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14411. this._alphaState.alphaBlend = true;
  14412. break;
  14413. case Engine.ALPHA_COMBINE:
  14414. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14415. this._alphaState.alphaBlend = true;
  14416. break;
  14417. case Engine.ALPHA_ONEONE:
  14418. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14419. this._alphaState.alphaBlend = true;
  14420. break;
  14421. case Engine.ALPHA_ADD:
  14422. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14423. this._alphaState.alphaBlend = true;
  14424. break;
  14425. case Engine.ALPHA_SUBTRACT:
  14426. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14427. this._alphaState.alphaBlend = true;
  14428. break;
  14429. case Engine.ALPHA_MULTIPLY:
  14430. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14431. this._alphaState.alphaBlend = true;
  14432. break;
  14433. case Engine.ALPHA_MAXIMIZED:
  14434. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14435. this._alphaState.alphaBlend = true;
  14436. break;
  14437. case Engine.ALPHA_INTERPOLATE:
  14438. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14439. this._alphaState.alphaBlend = true;
  14440. break;
  14441. case Engine.ALPHA_SCREENMODE:
  14442. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14443. this._alphaState.alphaBlend = true;
  14444. break;
  14445. }
  14446. if (!noDepthWriteChange) {
  14447. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14448. }
  14449. this._alphaMode = mode;
  14450. };
  14451. /**
  14452. * Gets the current alpha mode
  14453. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14454. * @returns the current alpha mode
  14455. */
  14456. Engine.prototype.getAlphaMode = function () {
  14457. return this._alphaMode;
  14458. };
  14459. // Textures
  14460. /**
  14461. * Force the entire cache to be cleared
  14462. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14463. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14464. */
  14465. Engine.prototype.wipeCaches = function (bruteForce) {
  14466. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14467. return;
  14468. }
  14469. this._currentEffect = null;
  14470. if (bruteForce) {
  14471. this.resetTextureCache();
  14472. this._currentProgram = null;
  14473. this._stencilState.reset();
  14474. this._depthCullingState.reset();
  14475. this.setDepthFunctionToLessOrEqual();
  14476. this._alphaState.reset();
  14477. }
  14478. this._resetVertexBufferBinding();
  14479. this._cachedIndexBuffer = null;
  14480. this._cachedEffectForVertexBuffers = null;
  14481. this._unbindVertexArrayObject();
  14482. this.bindIndexBuffer(null);
  14483. };
  14484. /**
  14485. * Set the compressed texture format to use, based on the formats you have, and the formats
  14486. * supported by the hardware / browser.
  14487. *
  14488. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14489. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14490. * to API arguments needed to compressed textures. This puts the burden on the container
  14491. * generator to house the arcane code for determining these for current & future formats.
  14492. *
  14493. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14494. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14495. *
  14496. * Note: The result of this call is not taken into account when a texture is base64.
  14497. *
  14498. * @param formatsAvailable defines the list of those format families you have created
  14499. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14500. *
  14501. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14502. * @returns The extension selected.
  14503. */
  14504. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14505. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14506. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14507. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14508. return this._textureFormatInUse = this._texturesSupported[i];
  14509. }
  14510. }
  14511. }
  14512. // actively set format to nothing, to allow this to be called more than once
  14513. // and possibly fail the 2nd time
  14514. this._textureFormatInUse = null;
  14515. return null;
  14516. };
  14517. /** @hidden */
  14518. Engine.prototype._createTexture = function () {
  14519. var texture = this._gl.createTexture();
  14520. if (!texture) {
  14521. throw new Error("Unable to create texture");
  14522. }
  14523. return texture;
  14524. };
  14525. /**
  14526. * Usually called from BABYLON.Texture.ts.
  14527. * Passed information to create a WebGLTexture
  14528. * @param urlArg defines a value which contains one of the following:
  14529. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14530. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14531. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14532. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14533. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14534. * @param scene needed for loading to the correct scene
  14535. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14536. * @param onLoad optional callback to be called upon successful completion
  14537. * @param onError optional callback to be called upon failure
  14538. * @param buffer a source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  14539. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14540. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14541. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14542. */
  14543. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14544. var _this = this;
  14545. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14546. if (onLoad === void 0) { onLoad = null; }
  14547. if (onError === void 0) { onError = null; }
  14548. if (buffer === void 0) { buffer = null; }
  14549. if (fallback === void 0) { fallback = null; }
  14550. if (format === void 0) { format = null; }
  14551. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14552. var fromData = url.substr(0, 5) === "data:";
  14553. var fromBlob = url.substr(0, 5) === "blob:";
  14554. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14555. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14556. // establish the file extension, if possible
  14557. var lastDot = url.lastIndexOf('.');
  14558. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14559. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14560. var isTGA = (extension.indexOf(".tga") === 0);
  14561. // determine if a ktx file should be substituted
  14562. var isKTX = false;
  14563. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14564. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14565. isKTX = true;
  14566. }
  14567. if (scene) {
  14568. scene._addPendingData(texture);
  14569. }
  14570. texture.url = url;
  14571. texture.generateMipMaps = !noMipmap;
  14572. texture.samplingMode = samplingMode;
  14573. texture.invertY = invertY;
  14574. if (!this._doNotHandleContextLost) {
  14575. // Keep a link to the buffer only if we plan to handle context lost
  14576. texture._buffer = buffer;
  14577. }
  14578. var onLoadObserver = null;
  14579. if (onLoad && !fallback) {
  14580. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14581. }
  14582. if (!fallback)
  14583. this._internalTexturesCache.push(texture);
  14584. var onerror = function (message, exception) {
  14585. if (scene) {
  14586. scene._removePendingData(texture);
  14587. }
  14588. if (onLoadObserver) {
  14589. texture.onLoadedObservable.remove(onLoadObserver);
  14590. }
  14591. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14592. if (isKTX) {
  14593. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14594. }
  14595. else if (BABYLON.Tools.UseFallbackTexture) {
  14596. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14597. }
  14598. if (onError) {
  14599. onError(message || "Unknown error", exception);
  14600. }
  14601. };
  14602. var callback = null;
  14603. // processing for non-image formats
  14604. if (isKTX || isTGA || isDDS) {
  14605. if (isKTX) {
  14606. callback = function (data) {
  14607. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14608. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14609. ktx.uploadLevels(_this._gl, !noMipmap);
  14610. return false;
  14611. }, samplingMode);
  14612. };
  14613. }
  14614. else if (isTGA) {
  14615. callback = function (arrayBuffer) {
  14616. var data = new Uint8Array(arrayBuffer);
  14617. var header = BABYLON.TGATools.GetTGAHeader(data);
  14618. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14619. BABYLON.TGATools.UploadContent(_this._gl, data);
  14620. return false;
  14621. }, samplingMode);
  14622. };
  14623. }
  14624. else if (isDDS) {
  14625. callback = function (data) {
  14626. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14627. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14628. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14629. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14630. return false;
  14631. }, samplingMode);
  14632. };
  14633. }
  14634. if (!buffer) {
  14635. this._loadFile(url, function (data) {
  14636. if (callback) {
  14637. callback(data);
  14638. }
  14639. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14640. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14641. });
  14642. }
  14643. else {
  14644. if (callback) {
  14645. callback(buffer);
  14646. }
  14647. }
  14648. // image format processing
  14649. }
  14650. else {
  14651. var onload = function (img) {
  14652. if (fromBlob && !_this._doNotHandleContextLost) {
  14653. // We need to store the image if we need to rebuild the texture
  14654. // in case of a webgl context lost
  14655. texture._buffer = img;
  14656. }
  14657. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14658. var gl = _this._gl;
  14659. var isPot = (img.width === potWidth && img.height === potHeight);
  14660. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14661. if (isPot) {
  14662. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14663. return false;
  14664. }
  14665. // Using shaders to rescale because canvas.drawImage is lossy
  14666. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14667. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14668. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14669. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14670. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14671. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14672. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14673. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14674. _this._releaseTexture(source);
  14675. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14676. continuationCallback();
  14677. });
  14678. return true;
  14679. }, samplingMode);
  14680. };
  14681. if (!fromData || isBase64)
  14682. if (buffer instanceof HTMLImageElement) {
  14683. onload(buffer);
  14684. }
  14685. else {
  14686. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14687. }
  14688. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  14689. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14690. else
  14691. onload(buffer);
  14692. }
  14693. return texture;
  14694. };
  14695. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14696. var _this = this;
  14697. var rtt = this.createRenderTargetTexture({
  14698. width: destination.width,
  14699. height: destination.height,
  14700. }, {
  14701. generateMipMaps: false,
  14702. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14703. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14704. generateDepthBuffer: false,
  14705. generateStencilBuffer: false
  14706. });
  14707. if (!this._rescalePostProcess) {
  14708. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14709. }
  14710. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14711. _this._rescalePostProcess.onApply = function (effect) {
  14712. effect._bindTexture("textureSampler", source);
  14713. };
  14714. var hostingScene = scene;
  14715. if (!hostingScene) {
  14716. hostingScene = _this.scenes[_this.scenes.length - 1];
  14717. }
  14718. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14719. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14720. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14721. _this.unBindFramebuffer(rtt);
  14722. _this._releaseTexture(rtt);
  14723. if (onComplete) {
  14724. onComplete();
  14725. }
  14726. });
  14727. };
  14728. /**
  14729. * Update a raw texture
  14730. * @param texture defines the texture to update
  14731. * @param data defines the data to store in the texture
  14732. * @param format defines the format of the data
  14733. * @param invertY defines if data must be stored with Y axis inverted
  14734. * @param compression defines the compression used (null by default)
  14735. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14736. */
  14737. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14738. if (compression === void 0) { compression = null; }
  14739. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14740. if (!texture) {
  14741. return;
  14742. }
  14743. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14744. var internalFormat = this._getInternalFormat(format);
  14745. var textureType = this._getWebGLTextureType(type);
  14746. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14747. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14748. if (!this._doNotHandleContextLost) {
  14749. texture._bufferView = data;
  14750. texture.format = format;
  14751. texture.type = type;
  14752. texture.invertY = invertY;
  14753. texture._compression = compression;
  14754. }
  14755. if (texture.width % 4 !== 0) {
  14756. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14757. }
  14758. if (compression && data) {
  14759. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14760. }
  14761. else {
  14762. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14763. }
  14764. if (texture.generateMipMaps) {
  14765. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14766. }
  14767. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14768. // this.resetTextureCache();
  14769. texture.isReady = true;
  14770. };
  14771. /**
  14772. * Creates a raw texture
  14773. * @param data defines the data to store in the texture
  14774. * @param width defines the width of the texture
  14775. * @param height defines the height of the texture
  14776. * @param format defines the format of the data
  14777. * @param generateMipMaps defines if the engine should generate the mip levels
  14778. * @param invertY defines if data must be stored with Y axis inverted
  14779. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14780. * @param compression defines the compression used (null by default)
  14781. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14782. * @returns the raw texture inside an InternalTexture
  14783. */
  14784. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14785. if (compression === void 0) { compression = null; }
  14786. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14787. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14788. texture.baseWidth = width;
  14789. texture.baseHeight = height;
  14790. texture.width = width;
  14791. texture.height = height;
  14792. texture.format = format;
  14793. texture.generateMipMaps = generateMipMaps;
  14794. texture.samplingMode = samplingMode;
  14795. texture.invertY = invertY;
  14796. texture._compression = compression;
  14797. texture.type = type;
  14798. if (!this._doNotHandleContextLost) {
  14799. texture._bufferView = data;
  14800. }
  14801. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14802. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14803. // Filters
  14804. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14805. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14806. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14807. if (generateMipMaps) {
  14808. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14809. }
  14810. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14811. this._internalTexturesCache.push(texture);
  14812. return texture;
  14813. };
  14814. /**
  14815. * Creates a dynamic texture
  14816. * @param width defines the width of the texture
  14817. * @param height defines the height of the texture
  14818. * @param generateMipMaps defines if the engine should generate the mip levels
  14819. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14820. * @returns the dynamic texture inside an InternalTexture
  14821. */
  14822. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14823. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14824. texture.baseWidth = width;
  14825. texture.baseHeight = height;
  14826. if (generateMipMaps) {
  14827. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14828. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14829. }
  14830. // this.resetTextureCache();
  14831. texture.width = width;
  14832. texture.height = height;
  14833. texture.isReady = false;
  14834. texture.generateMipMaps = generateMipMaps;
  14835. texture.samplingMode = samplingMode;
  14836. this.updateTextureSamplingMode(samplingMode, texture);
  14837. this._internalTexturesCache.push(texture);
  14838. return texture;
  14839. };
  14840. /**
  14841. * Update the sampling mode of a given texture
  14842. * @param samplingMode defines the required sampling mode
  14843. * @param texture defines the texture to update
  14844. */
  14845. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14846. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14847. if (texture.isCube) {
  14848. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14849. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14850. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14851. }
  14852. else if (texture.is3D) {
  14853. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14854. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14855. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14856. }
  14857. else {
  14858. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14859. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14860. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14861. }
  14862. texture.samplingMode = samplingMode;
  14863. };
  14864. /**
  14865. * Update the content of a dynamic texture
  14866. * @param texture defines the texture to update
  14867. * @param canvas defines the canvas containing the source
  14868. * @param invertY defines if data must be stored with Y axis inverted
  14869. * @param premulAlpha defines if alpha is stored as premultiplied
  14870. * @param format defines the format of the data
  14871. */
  14872. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14873. if (premulAlpha === void 0) { premulAlpha = false; }
  14874. if (!texture) {
  14875. return;
  14876. }
  14877. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14878. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14879. if (premulAlpha) {
  14880. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14881. }
  14882. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14883. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14884. if (texture.generateMipMaps) {
  14885. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14886. }
  14887. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14888. if (premulAlpha) {
  14889. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14890. }
  14891. texture.isReady = true;
  14892. };
  14893. /**
  14894. * Update a video texture
  14895. * @param texture defines the texture to update
  14896. * @param video defines the video element to use
  14897. * @param invertY defines if data must be stored with Y axis inverted
  14898. */
  14899. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14900. if (!texture || texture._isDisabled) {
  14901. return;
  14902. }
  14903. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14904. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14905. try {
  14906. // Testing video texture support
  14907. if (this._videoTextureSupported === undefined) {
  14908. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14909. if (this._gl.getError() !== 0) {
  14910. this._videoTextureSupported = false;
  14911. }
  14912. else {
  14913. this._videoTextureSupported = true;
  14914. }
  14915. }
  14916. // Copy video through the current working canvas if video texture is not supported
  14917. if (!this._videoTextureSupported) {
  14918. if (!texture._workingCanvas) {
  14919. texture._workingCanvas = document.createElement("canvas");
  14920. var context = texture._workingCanvas.getContext("2d");
  14921. if (!context) {
  14922. throw new Error("Unable to get 2d context");
  14923. }
  14924. texture._workingContext = context;
  14925. texture._workingCanvas.width = texture.width;
  14926. texture._workingCanvas.height = texture.height;
  14927. }
  14928. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14929. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14930. }
  14931. else {
  14932. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14933. }
  14934. if (texture.generateMipMaps) {
  14935. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14936. }
  14937. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14938. // this.resetTextureCache();
  14939. texture.isReady = true;
  14940. }
  14941. catch (ex) {
  14942. // Something unexpected
  14943. // Let's disable the texture
  14944. texture._isDisabled = true;
  14945. }
  14946. };
  14947. /**
  14948. * Updates a depth texture Comparison Mode and Function.
  14949. * If the comparison Function is equal to 0, the mode will be set to none.
  14950. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14951. * @param texture The texture to set the comparison function for
  14952. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14953. */
  14954. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14955. if (this.webGLVersion === 1) {
  14956. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14957. return;
  14958. }
  14959. var gl = this._gl;
  14960. if (texture.isCube) {
  14961. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14962. if (comparisonFunction === 0) {
  14963. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14964. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14965. }
  14966. else {
  14967. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14968. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14969. }
  14970. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14971. }
  14972. else {
  14973. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14974. if (comparisonFunction === 0) {
  14975. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14976. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14977. }
  14978. else {
  14979. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14980. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14981. }
  14982. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14983. }
  14984. texture._comparisonFunction = comparisonFunction;
  14985. };
  14986. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14987. var width = size.width || size;
  14988. var height = size.height || size;
  14989. internalTexture.baseWidth = width;
  14990. internalTexture.baseHeight = height;
  14991. internalTexture.width = width;
  14992. internalTexture.height = height;
  14993. internalTexture.isReady = true;
  14994. internalTexture.samples = 1;
  14995. internalTexture.generateMipMaps = false;
  14996. internalTexture._generateDepthBuffer = true;
  14997. internalTexture._generateStencilBuffer = generateStencil;
  14998. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14999. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15000. internalTexture._comparisonFunction = comparisonFunction;
  15001. var gl = this._gl;
  15002. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15003. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15004. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15005. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15006. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15007. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15008. if (comparisonFunction === 0) {
  15009. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15010. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15011. }
  15012. else {
  15013. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15014. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15015. }
  15016. };
  15017. /**
  15018. * Creates a depth stencil texture.
  15019. * This is only available in WebGL 2 or with the depth texture extension available.
  15020. * @param size The size of face edge in the texture.
  15021. * @param options The options defining the texture.
  15022. * @returns The texture
  15023. */
  15024. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15025. if (options.isCube) {
  15026. var width = size.width || size;
  15027. return this._createDepthStencilCubeTexture(width, options);
  15028. }
  15029. else {
  15030. return this._createDepthStencilTexture(size, options);
  15031. }
  15032. };
  15033. /**
  15034. * Creates a depth stencil texture.
  15035. * This is only available in WebGL 2 or with the depth texture extension available.
  15036. * @param size The size of face edge in the texture.
  15037. * @param options The options defining the texture.
  15038. * @returns The texture
  15039. */
  15040. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15041. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15042. if (!this._caps.depthTextureExtension) {
  15043. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15044. return internalTexture;
  15045. }
  15046. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15047. var gl = this._gl;
  15048. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15049. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15050. if (this.webGLVersion > 1) {
  15051. if (internalOptions.generateStencil) {
  15052. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15053. }
  15054. else {
  15055. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15056. }
  15057. }
  15058. else {
  15059. if (internalOptions.generateStencil) {
  15060. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15061. }
  15062. else {
  15063. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15064. }
  15065. }
  15066. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15067. return internalTexture;
  15068. };
  15069. /**
  15070. * Creates a depth stencil cube texture.
  15071. * This is only available in WebGL 2.
  15072. * @param size The size of face edge in the cube texture.
  15073. * @param options The options defining the cube texture.
  15074. * @returns The cube texture
  15075. */
  15076. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15077. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15078. internalTexture.isCube = true;
  15079. if (this.webGLVersion === 1) {
  15080. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15081. return internalTexture;
  15082. }
  15083. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15084. var gl = this._gl;
  15085. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15086. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15087. // Create the depth/stencil buffer
  15088. for (var face = 0; face < 6; face++) {
  15089. if (internalOptions.generateStencil) {
  15090. 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);
  15091. }
  15092. else {
  15093. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15094. }
  15095. }
  15096. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15097. return internalTexture;
  15098. };
  15099. /**
  15100. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15101. * @param renderTarget The render target to set the frame buffer for
  15102. */
  15103. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15104. // Create the framebuffer
  15105. var internalTexture = renderTarget.getInternalTexture();
  15106. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15107. return;
  15108. }
  15109. var gl = this._gl;
  15110. var depthStencilTexture = renderTarget.depthStencilTexture;
  15111. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15112. if (depthStencilTexture.isCube) {
  15113. if (depthStencilTexture._generateStencilBuffer) {
  15114. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15115. }
  15116. else {
  15117. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15118. }
  15119. }
  15120. else {
  15121. if (depthStencilTexture._generateStencilBuffer) {
  15122. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15123. }
  15124. else {
  15125. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15126. }
  15127. }
  15128. this.bindUnboundFramebuffer(null);
  15129. };
  15130. /**
  15131. * Creates a new render target texture
  15132. * @param size defines the size of the texture
  15133. * @param options defines the options used to create the texture
  15134. * @returns a new render target texture stored in an InternalTexture
  15135. */
  15136. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15137. var fullOptions = new RenderTargetCreationOptions();
  15138. if (options !== undefined && typeof options === "object") {
  15139. fullOptions.generateMipMaps = options.generateMipMaps;
  15140. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15141. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15142. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15143. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15144. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15145. }
  15146. else {
  15147. fullOptions.generateMipMaps = options;
  15148. fullOptions.generateDepthBuffer = true;
  15149. fullOptions.generateStencilBuffer = false;
  15150. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15151. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15152. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15153. }
  15154. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15155. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15156. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15157. }
  15158. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15159. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15160. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15161. }
  15162. var gl = this._gl;
  15163. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15164. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15165. var width = size.width || size;
  15166. var height = size.height || size;
  15167. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15168. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15169. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15170. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15171. }
  15172. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15173. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15174. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15175. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15176. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15177. // Create the framebuffer
  15178. var framebuffer = gl.createFramebuffer();
  15179. this.bindUnboundFramebuffer(framebuffer);
  15180. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15181. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15182. if (fullOptions.generateMipMaps) {
  15183. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15184. }
  15185. // Unbind
  15186. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15187. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15188. this.bindUnboundFramebuffer(null);
  15189. texture._framebuffer = framebuffer;
  15190. texture.baseWidth = width;
  15191. texture.baseHeight = height;
  15192. texture.width = width;
  15193. texture.height = height;
  15194. texture.isReady = true;
  15195. texture.samples = 1;
  15196. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15197. texture.samplingMode = fullOptions.samplingMode;
  15198. texture.type = fullOptions.type;
  15199. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15200. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15201. // this.resetTextureCache();
  15202. this._internalTexturesCache.push(texture);
  15203. return texture;
  15204. };
  15205. /**
  15206. * Create a multi render target texture
  15207. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15208. * @param size defines the size of the texture
  15209. * @param options defines the creation options
  15210. * @returns the cube texture as an InternalTexture
  15211. */
  15212. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15213. var generateMipMaps = false;
  15214. var generateDepthBuffer = true;
  15215. var generateStencilBuffer = false;
  15216. var generateDepthTexture = false;
  15217. var textureCount = 1;
  15218. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15219. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15220. var types = new Array();
  15221. var samplingModes = new Array();
  15222. if (options !== undefined) {
  15223. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15224. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15225. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15226. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15227. textureCount = options.textureCount || 1;
  15228. if (options.types) {
  15229. types = options.types;
  15230. }
  15231. if (options.samplingModes) {
  15232. samplingModes = options.samplingModes;
  15233. }
  15234. }
  15235. var gl = this._gl;
  15236. // Create the framebuffer
  15237. var framebuffer = gl.createFramebuffer();
  15238. this.bindUnboundFramebuffer(framebuffer);
  15239. var width = size.width || size;
  15240. var height = size.height || size;
  15241. var textures = [];
  15242. var attachments = [];
  15243. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15244. for (var i = 0; i < textureCount; i++) {
  15245. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15246. var type = types[i] || defaultType;
  15247. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15248. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15249. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15250. }
  15251. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15252. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15253. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15254. }
  15255. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15256. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15257. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15258. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15259. }
  15260. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15261. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15262. textures.push(texture);
  15263. attachments.push(attachment);
  15264. gl.activeTexture(gl["TEXTURE" + i]);
  15265. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15266. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15267. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15268. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15269. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15270. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15271. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15272. if (generateMipMaps) {
  15273. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15274. }
  15275. // Unbind
  15276. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15277. texture._framebuffer = framebuffer;
  15278. texture._depthStencilBuffer = depthStencilBuffer;
  15279. texture.baseWidth = width;
  15280. texture.baseHeight = height;
  15281. texture.width = width;
  15282. texture.height = height;
  15283. texture.isReady = true;
  15284. texture.samples = 1;
  15285. texture.generateMipMaps = generateMipMaps;
  15286. texture.samplingMode = samplingMode;
  15287. texture.type = type;
  15288. texture._generateDepthBuffer = generateDepthBuffer;
  15289. texture._generateStencilBuffer = generateStencilBuffer;
  15290. texture._attachments = attachments;
  15291. this._internalTexturesCache.push(texture);
  15292. }
  15293. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15294. // Depth texture
  15295. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15296. gl.activeTexture(gl.TEXTURE0);
  15297. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15298. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15299. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15300. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15301. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15302. 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);
  15303. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15304. depthTexture._framebuffer = framebuffer;
  15305. depthTexture.baseWidth = width;
  15306. depthTexture.baseHeight = height;
  15307. depthTexture.width = width;
  15308. depthTexture.height = height;
  15309. depthTexture.isReady = true;
  15310. depthTexture.samples = 1;
  15311. depthTexture.generateMipMaps = generateMipMaps;
  15312. depthTexture.samplingMode = gl.NEAREST;
  15313. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15314. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15315. textures.push(depthTexture);
  15316. this._internalTexturesCache.push(depthTexture);
  15317. }
  15318. gl.drawBuffers(attachments);
  15319. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15320. this.bindUnboundFramebuffer(null);
  15321. this.resetTextureCache();
  15322. return textures;
  15323. };
  15324. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15325. if (samples === void 0) { samples = 1; }
  15326. var depthStencilBuffer = null;
  15327. var gl = this._gl;
  15328. // Create the depth/stencil buffer
  15329. if (generateStencilBuffer) {
  15330. depthStencilBuffer = gl.createRenderbuffer();
  15331. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15332. if (samples > 1) {
  15333. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15334. }
  15335. else {
  15336. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15337. }
  15338. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15339. }
  15340. else if (generateDepthBuffer) {
  15341. depthStencilBuffer = gl.createRenderbuffer();
  15342. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15343. if (samples > 1) {
  15344. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15345. }
  15346. else {
  15347. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15348. }
  15349. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15350. }
  15351. return depthStencilBuffer;
  15352. };
  15353. /**
  15354. * Updates the sample count of a render target texture
  15355. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15356. * @param texture defines the texture to update
  15357. * @param samples defines the sample count to set
  15358. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15359. */
  15360. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15361. if (this.webGLVersion < 2 || !texture) {
  15362. return 1;
  15363. }
  15364. if (texture.samples === samples) {
  15365. return samples;
  15366. }
  15367. var gl = this._gl;
  15368. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15369. // Dispose previous render buffers
  15370. if (texture._depthStencilBuffer) {
  15371. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15372. texture._depthStencilBuffer = null;
  15373. }
  15374. if (texture._MSAAFramebuffer) {
  15375. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15376. texture._MSAAFramebuffer = null;
  15377. }
  15378. if (texture._MSAARenderBuffer) {
  15379. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15380. texture._MSAARenderBuffer = null;
  15381. }
  15382. if (samples > 1) {
  15383. var framebuffer = gl.createFramebuffer();
  15384. if (!framebuffer) {
  15385. throw new Error("Unable to create multi sampled framebuffer");
  15386. }
  15387. texture._MSAAFramebuffer = framebuffer;
  15388. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15389. var colorRenderbuffer = gl.createRenderbuffer();
  15390. if (!colorRenderbuffer) {
  15391. throw new Error("Unable to create multi sampled framebuffer");
  15392. }
  15393. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15394. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15395. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15396. texture._MSAARenderBuffer = colorRenderbuffer;
  15397. }
  15398. else {
  15399. this.bindUnboundFramebuffer(texture._framebuffer);
  15400. }
  15401. texture.samples = samples;
  15402. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15403. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15404. this.bindUnboundFramebuffer(null);
  15405. return samples;
  15406. };
  15407. /**
  15408. * Update the sample count for a given multiple render target texture
  15409. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15410. * @param textures defines the textures to update
  15411. * @param samples defines the sample count to set
  15412. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15413. */
  15414. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15415. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15416. return 1;
  15417. }
  15418. if (textures[0].samples === samples) {
  15419. return samples;
  15420. }
  15421. var gl = this._gl;
  15422. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15423. // Dispose previous render buffers
  15424. if (textures[0]._depthStencilBuffer) {
  15425. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15426. textures[0]._depthStencilBuffer = null;
  15427. }
  15428. if (textures[0]._MSAAFramebuffer) {
  15429. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15430. textures[0]._MSAAFramebuffer = null;
  15431. }
  15432. for (var i = 0; i < textures.length; i++) {
  15433. if (textures[i]._MSAARenderBuffer) {
  15434. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15435. textures[i]._MSAARenderBuffer = null;
  15436. }
  15437. }
  15438. if (samples > 1) {
  15439. var framebuffer = gl.createFramebuffer();
  15440. if (!framebuffer) {
  15441. throw new Error("Unable to create multi sampled framebuffer");
  15442. }
  15443. this.bindUnboundFramebuffer(framebuffer);
  15444. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15445. var attachments = [];
  15446. for (var i = 0; i < textures.length; i++) {
  15447. var texture = textures[i];
  15448. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15449. var colorRenderbuffer = gl.createRenderbuffer();
  15450. if (!colorRenderbuffer) {
  15451. throw new Error("Unable to create multi sampled framebuffer");
  15452. }
  15453. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15454. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15455. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15456. texture._MSAAFramebuffer = framebuffer;
  15457. texture._MSAARenderBuffer = colorRenderbuffer;
  15458. texture.samples = samples;
  15459. texture._depthStencilBuffer = depthStencilBuffer;
  15460. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15461. attachments.push(attachment);
  15462. }
  15463. gl.drawBuffers(attachments);
  15464. }
  15465. else {
  15466. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15467. }
  15468. this.bindUnboundFramebuffer(null);
  15469. return samples;
  15470. };
  15471. /** @hidden */
  15472. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15473. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15474. };
  15475. /** @hidden */
  15476. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15477. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15478. };
  15479. /**
  15480. * Creates a new render target cube texture
  15481. * @param size defines the size of the texture
  15482. * @param options defines the options used to create the texture
  15483. * @returns a new render target cube texture stored in an InternalTexture
  15484. */
  15485. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15486. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15487. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15488. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15489. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15490. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15491. }
  15492. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15493. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15494. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15495. }
  15496. var gl = this._gl;
  15497. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15498. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15499. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15500. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15501. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15502. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15503. }
  15504. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15505. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15506. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15507. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15508. for (var face = 0; face < 6; face++) {
  15509. 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);
  15510. }
  15511. // Create the framebuffer
  15512. var framebuffer = gl.createFramebuffer();
  15513. this.bindUnboundFramebuffer(framebuffer);
  15514. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15515. // MipMaps
  15516. if (fullOptions.generateMipMaps) {
  15517. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15518. }
  15519. // Unbind
  15520. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15521. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15522. this.bindUnboundFramebuffer(null);
  15523. texture._framebuffer = framebuffer;
  15524. texture.width = size;
  15525. texture.height = size;
  15526. texture.isReady = true;
  15527. texture.isCube = true;
  15528. texture.samples = 1;
  15529. texture.generateMipMaps = fullOptions.generateMipMaps;
  15530. texture.samplingMode = fullOptions.samplingMode;
  15531. texture.type = fullOptions.type;
  15532. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15533. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15534. this._internalTexturesCache.push(texture);
  15535. return texture;
  15536. };
  15537. /**
  15538. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15539. * @param rootUrl defines the url where the file to load is located
  15540. * @param scene defines the current scene
  15541. * @param scale defines scale to apply to the mip map selection
  15542. * @param offset defines offset to apply to the mip map selection
  15543. * @param onLoad defines an optional callback raised when the texture is loaded
  15544. * @param onError defines an optional callback raised if there is an issue to load the texture
  15545. * @param format defines the format of the data
  15546. * @param forcedExtension defines the extension to use to pick the right loader
  15547. * @returns the cube texture as an InternalTexture
  15548. */
  15549. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  15550. var _this = this;
  15551. if (onLoad === void 0) { onLoad = null; }
  15552. if (onError === void 0) { onError = null; }
  15553. if (forcedExtension === void 0) { forcedExtension = null; }
  15554. var callback = function (loadData) {
  15555. if (!loadData) {
  15556. if (onLoad) {
  15557. onLoad(null);
  15558. }
  15559. return;
  15560. }
  15561. var texture = loadData.texture;
  15562. if (loadData.info.sphericalPolynomial) {
  15563. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15564. }
  15565. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15566. texture._lodGenerationScale = scale;
  15567. texture._lodGenerationOffset = offset;
  15568. if (_this._caps.textureLOD) {
  15569. // Do not add extra process if texture lod is supported.
  15570. if (onLoad) {
  15571. onLoad(texture);
  15572. }
  15573. return;
  15574. }
  15575. var mipSlices = 3;
  15576. var gl = _this._gl;
  15577. var width = loadData.width;
  15578. if (!width) {
  15579. return;
  15580. }
  15581. var textures = [];
  15582. for (var i = 0; i < mipSlices; i++) {
  15583. //compute LOD from even spacing in smoothness (matching shader calculation)
  15584. var smoothness = i / (mipSlices - 1);
  15585. var roughness = 1 - smoothness;
  15586. var minLODIndex = offset; // roughness = 0
  15587. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15588. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15589. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15590. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15591. glTextureFromLod.isCube = true;
  15592. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15593. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15594. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15595. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15596. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15597. if (loadData.isDDS) {
  15598. var info = loadData.info;
  15599. var data = loadData.data;
  15600. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15601. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15602. }
  15603. else {
  15604. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15605. }
  15606. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15607. // Wrap in a base texture for easy binding.
  15608. var lodTexture = new BABYLON.BaseTexture(scene);
  15609. lodTexture.isCube = true;
  15610. lodTexture._texture = glTextureFromLod;
  15611. glTextureFromLod.isReady = true;
  15612. textures.push(lodTexture);
  15613. }
  15614. texture._lodTextureHigh = textures[2];
  15615. texture._lodTextureMid = textures[1];
  15616. texture._lodTextureLow = textures[0];
  15617. if (onLoad) {
  15618. onLoad(texture);
  15619. }
  15620. };
  15621. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, true);
  15622. };
  15623. /**
  15624. * Creates a cube texture
  15625. * @param rootUrl defines the url where the files to load is located
  15626. * @param scene defines the current scene
  15627. * @param files defines the list of files to load (1 per face)
  15628. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15629. * @param onLoad defines an optional callback raised when the texture is loaded
  15630. * @param onError defines an optional callback raised if there is an issue to load the texture
  15631. * @param format defines the format of the data
  15632. * @param forcedExtension defines the extension to use to pick the right loader
  15633. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15634. * @returns the cube texture as an InternalTexture
  15635. */
  15636. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials) {
  15637. var _this = this;
  15638. if (onLoad === void 0) { onLoad = null; }
  15639. if (onError === void 0) { onError = null; }
  15640. if (forcedExtension === void 0) { forcedExtension = null; }
  15641. if (createPolynomials === void 0) { createPolynomials = false; }
  15642. var gl = this._gl;
  15643. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15644. texture.isCube = true;
  15645. texture.url = rootUrl;
  15646. texture.generateMipMaps = !noMipmap;
  15647. if (!this._doNotHandleContextLost) {
  15648. texture._extension = forcedExtension;
  15649. texture._files = files;
  15650. }
  15651. var isKTX = false;
  15652. var isDDS = false;
  15653. var lastDot = rootUrl.lastIndexOf('.');
  15654. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15655. if (this._textureFormatInUse) {
  15656. extension = this._textureFormatInUse;
  15657. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15658. isKTX = true;
  15659. }
  15660. else {
  15661. isDDS = (extension === ".dds");
  15662. }
  15663. var onerror = function (request, exception) {
  15664. if (onError && request) {
  15665. onError(request.status + " " + request.statusText, exception);
  15666. }
  15667. };
  15668. if (isKTX) {
  15669. this._loadFile(rootUrl, function (data) {
  15670. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15671. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15672. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15673. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15674. ktx.uploadLevels(_this._gl, !noMipmap);
  15675. _this.setCubeMapTextureParams(gl, loadMipmap);
  15676. texture.width = ktx.pixelWidth;
  15677. texture.height = ktx.pixelHeight;
  15678. texture.isReady = true;
  15679. }, undefined, undefined, true, onerror);
  15680. }
  15681. else if (isDDS) {
  15682. if (files && files.length === 6) {
  15683. this._cascadeLoadFiles(scene, function (imgs) {
  15684. var info;
  15685. var loadMipmap = false;
  15686. var width = 0;
  15687. for (var index = 0; index < imgs.length; index++) {
  15688. var data = imgs[index];
  15689. info = BABYLON.DDSTools.GetDDSInfo(data);
  15690. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15691. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15692. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15693. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15694. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15695. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15696. }
  15697. texture.width = info.width;
  15698. texture.height = info.height;
  15699. texture.type = info.textureType;
  15700. width = info.width;
  15701. }
  15702. _this.setCubeMapTextureParams(gl, loadMipmap);
  15703. texture.isReady = true;
  15704. if (onLoad) {
  15705. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15706. }
  15707. }, files, onError);
  15708. }
  15709. else {
  15710. this._loadFile(rootUrl, function (data) {
  15711. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15712. if (createPolynomials) {
  15713. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15714. }
  15715. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15716. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15717. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15718. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15719. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15720. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15721. }
  15722. _this.setCubeMapTextureParams(gl, loadMipmap);
  15723. texture.width = info.width;
  15724. texture.height = info.height;
  15725. texture.isReady = true;
  15726. texture.type = info.textureType;
  15727. if (onLoad) {
  15728. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15729. }
  15730. }, undefined, undefined, true, onerror);
  15731. }
  15732. }
  15733. else {
  15734. if (!files) {
  15735. throw new Error("Cannot load cubemap because files were not defined");
  15736. }
  15737. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15738. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15739. var height = width;
  15740. _this._prepareWorkingCanvas();
  15741. if (!_this._workingCanvas || !_this._workingContext) {
  15742. return;
  15743. }
  15744. _this._workingCanvas.width = width;
  15745. _this._workingCanvas.height = height;
  15746. var faces = [
  15747. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15748. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15749. ];
  15750. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15751. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15752. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15753. for (var index = 0; index < faces.length; index++) {
  15754. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15755. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15756. }
  15757. if (!noMipmap) {
  15758. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15759. }
  15760. _this.setCubeMapTextureParams(gl, !noMipmap);
  15761. texture.width = width;
  15762. texture.height = height;
  15763. texture.isReady = true;
  15764. if (format) {
  15765. texture.format = format;
  15766. }
  15767. texture.onLoadedObservable.notifyObservers(texture);
  15768. texture.onLoadedObservable.clear();
  15769. if (onLoad) {
  15770. onLoad();
  15771. }
  15772. }, files, onError);
  15773. }
  15774. this._internalTexturesCache.push(texture);
  15775. return texture;
  15776. };
  15777. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15778. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15779. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15780. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15781. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15782. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15783. // this.resetTextureCache();
  15784. };
  15785. /**
  15786. * Update a raw cube texture
  15787. * @param texture defines the texture to udpdate
  15788. * @param data defines the data to store
  15789. * @param format defines the data format
  15790. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15791. * @param invertY defines if data must be stored with Y axis inverted
  15792. * @param compression defines the compression used (null by default)
  15793. * @param level defines which level of the texture to update
  15794. */
  15795. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15796. if (compression === void 0) { compression = null; }
  15797. if (level === void 0) { level = 0; }
  15798. texture._bufferViewArray = data;
  15799. texture.format = format;
  15800. texture.type = type;
  15801. texture.invertY = invertY;
  15802. texture._compression = compression;
  15803. var gl = this._gl;
  15804. var textureType = this._getWebGLTextureType(type);
  15805. var internalFormat = this._getInternalFormat(format);
  15806. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15807. var needConversion = false;
  15808. if (internalFormat === gl.RGB) {
  15809. internalFormat = gl.RGBA;
  15810. needConversion = true;
  15811. }
  15812. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15813. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15814. if (texture.width % 4 !== 0) {
  15815. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15816. }
  15817. // Data are known to be in +X +Y +Z -X -Y -Z
  15818. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15819. var faceData = data[faceIndex];
  15820. if (compression) {
  15821. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15822. }
  15823. else {
  15824. if (needConversion) {
  15825. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15826. }
  15827. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15828. }
  15829. }
  15830. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15831. if (isPot && texture.generateMipMaps && level === 0) {
  15832. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15833. }
  15834. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15835. // this.resetTextureCache();
  15836. texture.isReady = true;
  15837. };
  15838. /**
  15839. * Creates a new raw cube texture
  15840. * @param data defines the array of data to use to create each face
  15841. * @param size defines the size of the textures
  15842. * @param format defines the format of the data
  15843. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15844. * @param generateMipMaps defines if the engine should generate the mip levels
  15845. * @param invertY defines if data must be stored with Y axis inverted
  15846. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15847. * @param compression defines the compression used (null by default)
  15848. * @returns the cube texture as an InternalTexture
  15849. */
  15850. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15851. if (compression === void 0) { compression = null; }
  15852. var gl = this._gl;
  15853. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15854. texture.isCube = true;
  15855. texture.generateMipMaps = generateMipMaps;
  15856. texture.format = format;
  15857. texture.type = type;
  15858. if (!this._doNotHandleContextLost) {
  15859. texture._bufferViewArray = data;
  15860. }
  15861. var textureType = this._getWebGLTextureType(type);
  15862. var internalFormat = this._getInternalFormat(format);
  15863. if (internalFormat === gl.RGB) {
  15864. internalFormat = gl.RGBA;
  15865. }
  15866. var width = size;
  15867. var height = width;
  15868. texture.width = width;
  15869. texture.height = height;
  15870. // Double check on POT to generate Mips.
  15871. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15872. if (!isPot) {
  15873. generateMipMaps = false;
  15874. }
  15875. // Upload data if needed. The texture won't be ready until then.
  15876. if (data) {
  15877. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15878. }
  15879. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15880. // Filters
  15881. if (data && generateMipMaps) {
  15882. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15883. }
  15884. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15885. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15886. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15887. }
  15888. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15889. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15890. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15891. }
  15892. else {
  15893. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15894. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15895. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15896. }
  15897. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15898. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15899. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15900. return texture;
  15901. };
  15902. /**
  15903. * Creates a new raw cube texture from a specified url
  15904. * @param url defines the url where the data is located
  15905. * @param scene defines the current scene
  15906. * @param size defines the size of the textures
  15907. * @param format defines the format of the data
  15908. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15909. * @param noMipmap defines if the engine should avoid generating the mip levels
  15910. * @param callback defines a callback used to extract texture data from loaded data
  15911. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15912. * @param onLoad defines a callback called when texture is loaded
  15913. * @param onError defines a callback called if there is an error
  15914. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15915. * @param invertY defines if data must be stored with Y axis inverted
  15916. * @returns the cube texture as an InternalTexture
  15917. */
  15918. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15919. var _this = this;
  15920. if (onLoad === void 0) { onLoad = null; }
  15921. if (onError === void 0) { onError = null; }
  15922. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15923. if (invertY === void 0) { invertY = false; }
  15924. var gl = this._gl;
  15925. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15926. scene._addPendingData(texture);
  15927. texture.url = url;
  15928. this._internalTexturesCache.push(texture);
  15929. var onerror = function (request, exception) {
  15930. scene._removePendingData(texture);
  15931. if (onError && request) {
  15932. onError(request.status + " " + request.statusText, exception);
  15933. }
  15934. };
  15935. var internalCallback = function (data) {
  15936. var width = texture.width;
  15937. var faceDataArrays = callback(data);
  15938. if (!faceDataArrays) {
  15939. return;
  15940. }
  15941. if (mipmapGenerator) {
  15942. var textureType = _this._getWebGLTextureType(type);
  15943. var internalFormat = _this._getInternalFormat(format);
  15944. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15945. var needConversion = false;
  15946. if (internalFormat === gl.RGB) {
  15947. internalFormat = gl.RGBA;
  15948. needConversion = true;
  15949. }
  15950. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15951. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15952. var mipData = mipmapGenerator(faceDataArrays);
  15953. for (var level = 0; level < mipData.length; level++) {
  15954. var mipSize = width >> level;
  15955. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15956. var mipFaceData = mipData[level][faceIndex];
  15957. if (needConversion) {
  15958. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15959. }
  15960. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15961. }
  15962. }
  15963. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15964. }
  15965. else {
  15966. texture.generateMipMaps = !noMipmap;
  15967. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15968. }
  15969. texture.isReady = true;
  15970. // this.resetTextureCache();
  15971. scene._removePendingData(texture);
  15972. if (onLoad) {
  15973. onLoad();
  15974. }
  15975. };
  15976. this._loadFile(url, function (data) {
  15977. internalCallback(data);
  15978. }, undefined, scene.database, true, onerror);
  15979. return texture;
  15980. };
  15981. ;
  15982. /**
  15983. * Update a raw 3D texture
  15984. * @param texture defines the texture to update
  15985. * @param data defines the data to store
  15986. * @param format defines the data format
  15987. * @param invertY defines if data must be stored with Y axis inverted
  15988. * @param compression defines the used compression (can be null)
  15989. */
  15990. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  15991. if (compression === void 0) { compression = null; }
  15992. var internalFormat = this._getInternalFormat(format);
  15993. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15994. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15995. if (!this._doNotHandleContextLost) {
  15996. texture._bufferView = data;
  15997. texture.format = format;
  15998. texture.invertY = invertY;
  15999. texture._compression = compression;
  16000. }
  16001. if (texture.width % 4 !== 0) {
  16002. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16003. }
  16004. if (compression && data) {
  16005. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16006. }
  16007. else {
  16008. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  16009. }
  16010. if (texture.generateMipMaps) {
  16011. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16012. }
  16013. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16014. // this.resetTextureCache();
  16015. texture.isReady = true;
  16016. };
  16017. /**
  16018. * Creates a new raw 3D texture
  16019. * @param data defines the data used to create the texture
  16020. * @param width defines the width of the texture
  16021. * @param height defines the height of the texture
  16022. * @param depth defines the depth of the texture
  16023. * @param format defines the format of the texture
  16024. * @param generateMipMaps defines if the engine must generate mip levels
  16025. * @param invertY defines if data must be stored with Y axis inverted
  16026. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16027. * @param compression defines the compressed used (can be null)
  16028. * @returns a new raw 3D texture (stored in an InternalTexture)
  16029. */
  16030. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  16031. if (compression === void 0) { compression = null; }
  16032. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16033. texture.baseWidth = width;
  16034. texture.baseHeight = height;
  16035. texture.baseDepth = depth;
  16036. texture.width = width;
  16037. texture.height = height;
  16038. texture.depth = depth;
  16039. texture.format = format;
  16040. texture.generateMipMaps = generateMipMaps;
  16041. texture.samplingMode = samplingMode;
  16042. texture.is3D = true;
  16043. if (!this._doNotHandleContextLost) {
  16044. texture._bufferView = data;
  16045. }
  16046. this.updateRawTexture3D(texture, data, format, invertY, compression);
  16047. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16048. // Filters
  16049. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16050. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16051. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16052. if (generateMipMaps) {
  16053. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16054. }
  16055. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16056. this._internalTexturesCache.push(texture);
  16057. return texture;
  16058. };
  16059. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16060. var gl = this._gl;
  16061. if (!gl) {
  16062. return;
  16063. }
  16064. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16065. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16066. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16067. if (!noMipmap && !isCompressed) {
  16068. gl.generateMipmap(gl.TEXTURE_2D);
  16069. }
  16070. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16071. // this.resetTextureCache();
  16072. if (scene) {
  16073. scene._removePendingData(texture);
  16074. }
  16075. texture.onLoadedObservable.notifyObservers(texture);
  16076. texture.onLoadedObservable.clear();
  16077. };
  16078. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16079. var _this = this;
  16080. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16081. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16082. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16083. var gl = this._gl;
  16084. if (!gl) {
  16085. return;
  16086. }
  16087. if (!texture._webGLTexture) {
  16088. // this.resetTextureCache();
  16089. if (scene) {
  16090. scene._removePendingData(texture);
  16091. }
  16092. return;
  16093. }
  16094. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16095. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16096. texture.baseWidth = width;
  16097. texture.baseHeight = height;
  16098. texture.width = potWidth;
  16099. texture.height = potHeight;
  16100. texture.isReady = true;
  16101. if (processFunction(potWidth, potHeight, function () {
  16102. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16103. })) {
  16104. // Returning as texture needs extra async steps
  16105. return;
  16106. }
  16107. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16108. };
  16109. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16110. // Create new RGBA data container.
  16111. var rgbaData;
  16112. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16113. rgbaData = new Float32Array(width * height * 4);
  16114. }
  16115. else {
  16116. rgbaData = new Uint32Array(width * height * 4);
  16117. }
  16118. // Convert each pixel.
  16119. for (var x = 0; x < width; x++) {
  16120. for (var y = 0; y < height; y++) {
  16121. var index = (y * width + x) * 3;
  16122. var newIndex = (y * width + x) * 4;
  16123. // Map Old Value to new value.
  16124. rgbaData[newIndex + 0] = rgbData[index + 0];
  16125. rgbaData[newIndex + 1] = rgbData[index + 1];
  16126. rgbaData[newIndex + 2] = rgbData[index + 2];
  16127. // Add fully opaque alpha channel.
  16128. rgbaData[newIndex + 3] = 1;
  16129. }
  16130. }
  16131. return rgbaData;
  16132. };
  16133. /** @hidden */
  16134. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16135. var gl = this._gl;
  16136. if (texture._framebuffer) {
  16137. gl.deleteFramebuffer(texture._framebuffer);
  16138. texture._framebuffer = null;
  16139. }
  16140. if (texture._depthStencilBuffer) {
  16141. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16142. texture._depthStencilBuffer = null;
  16143. }
  16144. if (texture._MSAAFramebuffer) {
  16145. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16146. texture._MSAAFramebuffer = null;
  16147. }
  16148. if (texture._MSAARenderBuffer) {
  16149. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16150. texture._MSAARenderBuffer = null;
  16151. }
  16152. };
  16153. /** @hidden */
  16154. Engine.prototype._releaseTexture = function (texture) {
  16155. var gl = this._gl;
  16156. this._releaseFramebufferObjects(texture);
  16157. gl.deleteTexture(texture._webGLTexture);
  16158. // Unbind channels
  16159. this.unbindAllTextures();
  16160. var index = this._internalTexturesCache.indexOf(texture);
  16161. if (index !== -1) {
  16162. this._internalTexturesCache.splice(index, 1);
  16163. }
  16164. // Integrated fixed lod samplers.
  16165. if (texture._lodTextureHigh) {
  16166. texture._lodTextureHigh.dispose();
  16167. }
  16168. if (texture._lodTextureMid) {
  16169. texture._lodTextureMid.dispose();
  16170. }
  16171. if (texture._lodTextureLow) {
  16172. texture._lodTextureLow.dispose();
  16173. }
  16174. // Set output texture of post process to null if the texture has been released/disposed
  16175. this.scenes.forEach(function (scene) {
  16176. scene.postProcesses.forEach(function (postProcess) {
  16177. if (postProcess._outputTexture == texture) {
  16178. postProcess._outputTexture = null;
  16179. }
  16180. });
  16181. scene.cameras.forEach(function (camera) {
  16182. camera._postProcesses.forEach(function (postProcess) {
  16183. if (postProcess) {
  16184. if (postProcess._outputTexture == texture) {
  16185. postProcess._outputTexture = null;
  16186. }
  16187. }
  16188. });
  16189. });
  16190. });
  16191. };
  16192. Engine.prototype.setProgram = function (program) {
  16193. if (this._currentProgram !== program) {
  16194. this._gl.useProgram(program);
  16195. this._currentProgram = program;
  16196. }
  16197. };
  16198. /**
  16199. * Binds an effect to the webGL context
  16200. * @param effect defines the effect to bind
  16201. */
  16202. Engine.prototype.bindSamplers = function (effect) {
  16203. this.setProgram(effect.getProgram());
  16204. var samplers = effect.getSamplers();
  16205. for (var index = 0; index < samplers.length; index++) {
  16206. var uniform = effect.getUniform(samplers[index]);
  16207. if (uniform) {
  16208. this._boundUniforms[index] = uniform;
  16209. }
  16210. }
  16211. this._currentEffect = null;
  16212. };
  16213. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16214. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16215. return;
  16216. }
  16217. // Remove
  16218. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16219. // Bind last to it
  16220. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16221. // Bind to dummy
  16222. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16223. };
  16224. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16225. if (!internalTexture) {
  16226. return -1;
  16227. }
  16228. internalTexture._initialSlot = channel;
  16229. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16230. if (channel !== internalTexture._designatedSlot) {
  16231. this._textureCollisions.addCount(1, false);
  16232. }
  16233. }
  16234. else {
  16235. if (channel !== internalTexture._designatedSlot) {
  16236. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16237. return internalTexture._designatedSlot;
  16238. }
  16239. else {
  16240. // No slot for this texture, let's pick a new one (if we find a free slot)
  16241. if (this._nextFreeTextureSlots.length) {
  16242. return this._nextFreeTextureSlots[0];
  16243. }
  16244. // We need to recycle the oldest bound texture, sorry.
  16245. this._textureCollisions.addCount(1, false);
  16246. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16247. }
  16248. }
  16249. }
  16250. return channel;
  16251. };
  16252. Engine.prototype._linkTrackers = function (previous, next) {
  16253. previous.next = next;
  16254. next.previous = previous;
  16255. };
  16256. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16257. var currentSlot = internalTexture._designatedSlot;
  16258. if (currentSlot === -1) {
  16259. return -1;
  16260. }
  16261. internalTexture._designatedSlot = -1;
  16262. if (this.disableTextureBindingOptimization) {
  16263. return -1;
  16264. }
  16265. // Remove from bound list
  16266. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16267. // Free the slot
  16268. this._boundTexturesCache[currentSlot] = null;
  16269. this._nextFreeTextureSlots.push(currentSlot);
  16270. return currentSlot;
  16271. };
  16272. Engine.prototype._activateCurrentTexture = function () {
  16273. if (this._currentTextureChannel !== this._activeChannel) {
  16274. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16275. this._currentTextureChannel = this._activeChannel;
  16276. }
  16277. };
  16278. /** @hidden */
  16279. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16280. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16281. if (force === void 0) { force = false; }
  16282. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16283. this._activeChannel = texture._designatedSlot;
  16284. }
  16285. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16286. var isTextureForRendering = texture && texture._initialSlot > -1;
  16287. if (currentTextureBound !== texture || force) {
  16288. if (currentTextureBound) {
  16289. this._removeDesignatedSlot(currentTextureBound);
  16290. }
  16291. this._activateCurrentTexture();
  16292. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16293. this._boundTexturesCache[this._activeChannel] = texture;
  16294. if (texture) {
  16295. if (!this.disableTextureBindingOptimization) {
  16296. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16297. if (slotIndex > -1) {
  16298. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16299. }
  16300. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16301. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16302. }
  16303. texture._designatedSlot = this._activeChannel;
  16304. }
  16305. }
  16306. else if (forTextureDataUpdate) {
  16307. this._activateCurrentTexture();
  16308. }
  16309. if (isTextureForRendering && !forTextureDataUpdate) {
  16310. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16311. }
  16312. };
  16313. /** @hidden */
  16314. Engine.prototype._bindTexture = function (channel, texture) {
  16315. if (channel < 0) {
  16316. return;
  16317. }
  16318. if (texture) {
  16319. channel = this._getCorrectTextureChannel(channel, texture);
  16320. }
  16321. this._activeChannel = channel;
  16322. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16323. };
  16324. /**
  16325. * Sets a texture to the webGL context from a postprocess
  16326. * @param channel defines the channel to use
  16327. * @param postProcess defines the source postprocess
  16328. */
  16329. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16330. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16331. };
  16332. /**
  16333. * Binds the output of the passed in post process to the texture channel specified
  16334. * @param channel The channel the texture should be bound to
  16335. * @param postProcess The post process which's output should be bound
  16336. */
  16337. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16338. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16339. };
  16340. /**
  16341. * Unbind all textures from the webGL context
  16342. */
  16343. Engine.prototype.unbindAllTextures = function () {
  16344. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16345. this._activeChannel = channel;
  16346. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16347. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16348. if (this.webGLVersion > 1) {
  16349. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16350. }
  16351. }
  16352. };
  16353. /**
  16354. * Sets a texture to the according uniform.
  16355. * @param channel The texture channel
  16356. * @param uniform The uniform to set
  16357. * @param texture The texture to apply
  16358. */
  16359. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16360. if (channel < 0) {
  16361. return;
  16362. }
  16363. if (uniform) {
  16364. this._boundUniforms[channel] = uniform;
  16365. }
  16366. this._setTexture(channel, texture);
  16367. };
  16368. /**
  16369. * Sets a depth stencil texture from a render target to the according uniform.
  16370. * @param channel The texture channel
  16371. * @param uniform The uniform to set
  16372. * @param texture The render target texture containing the depth stencil texture to apply
  16373. */
  16374. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16375. if (channel < 0) {
  16376. return;
  16377. }
  16378. if (uniform) {
  16379. this._boundUniforms[channel] = uniform;
  16380. }
  16381. if (!texture || !texture.depthStencilTexture) {
  16382. this._setTexture(channel, null);
  16383. }
  16384. else {
  16385. this._setTexture(channel, texture, false, true);
  16386. }
  16387. };
  16388. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16389. var uniform = this._boundUniforms[sourceSlot];
  16390. if (uniform._currentState === destination) {
  16391. return;
  16392. }
  16393. this._gl.uniform1i(uniform, destination);
  16394. uniform._currentState = destination;
  16395. };
  16396. Engine.prototype._getTextureWrapMode = function (mode) {
  16397. switch (mode) {
  16398. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16399. return this._gl.REPEAT;
  16400. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16401. return this._gl.CLAMP_TO_EDGE;
  16402. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16403. return this._gl.MIRRORED_REPEAT;
  16404. }
  16405. return this._gl.REPEAT;
  16406. };
  16407. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16408. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16409. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16410. // Not ready?
  16411. if (!texture) {
  16412. if (this._boundTexturesCache[channel] != null) {
  16413. this._activeChannel = channel;
  16414. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16415. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16416. if (this.webGLVersion > 1) {
  16417. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16418. }
  16419. }
  16420. return false;
  16421. }
  16422. // Video
  16423. if (texture.video) {
  16424. this._activeChannel = channel;
  16425. texture.update();
  16426. }
  16427. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16428. texture.delayLoad();
  16429. return false;
  16430. }
  16431. var internalTexture;
  16432. if (depthStencilTexture) {
  16433. internalTexture = texture.depthStencilTexture;
  16434. }
  16435. else if (texture.isReady()) {
  16436. internalTexture = texture.getInternalTexture();
  16437. }
  16438. else if (texture.isCube) {
  16439. internalTexture = this.emptyCubeTexture;
  16440. }
  16441. else if (texture.is3D) {
  16442. internalTexture = this.emptyTexture3D;
  16443. }
  16444. else {
  16445. internalTexture = this.emptyTexture;
  16446. }
  16447. if (!isPartOfTextureArray) {
  16448. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16449. }
  16450. var needToBind = true;
  16451. if (this._boundTexturesCache[channel] === internalTexture) {
  16452. this._moveBoundTextureOnTop(internalTexture);
  16453. if (!isPartOfTextureArray) {
  16454. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16455. }
  16456. needToBind = false;
  16457. }
  16458. this._activeChannel = channel;
  16459. if (internalTexture && internalTexture.is3D) {
  16460. if (needToBind) {
  16461. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16462. }
  16463. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16464. internalTexture._cachedWrapU = texture.wrapU;
  16465. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16466. }
  16467. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16468. internalTexture._cachedWrapV = texture.wrapV;
  16469. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16470. }
  16471. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16472. internalTexture._cachedWrapR = texture.wrapR;
  16473. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16474. }
  16475. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16476. }
  16477. else if (internalTexture && internalTexture.isCube) {
  16478. if (needToBind) {
  16479. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16480. }
  16481. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16482. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16483. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16484. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16485. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16486. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16487. }
  16488. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16489. }
  16490. else {
  16491. if (needToBind) {
  16492. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16493. }
  16494. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16495. internalTexture._cachedWrapU = texture.wrapU;
  16496. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16497. }
  16498. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16499. internalTexture._cachedWrapV = texture.wrapV;
  16500. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16501. }
  16502. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16503. }
  16504. return true;
  16505. };
  16506. /**
  16507. * Sets an array of texture to the webGL context
  16508. * @param channel defines the channel where the texture array must be set
  16509. * @param uniform defines the associated uniform location
  16510. * @param textures defines the array of textures to bind
  16511. */
  16512. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16513. if (channel < 0 || !uniform) {
  16514. return;
  16515. }
  16516. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16517. this._textureUnits = new Int32Array(textures.length);
  16518. }
  16519. for (var i = 0; i < textures.length; i++) {
  16520. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16521. }
  16522. this._gl.uniform1iv(uniform, this._textureUnits);
  16523. for (var index = 0; index < textures.length; index++) {
  16524. this._setTexture(this._textureUnits[index], textures[index], true);
  16525. }
  16526. };
  16527. /** @hidden */
  16528. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16529. var internalTexture = texture.getInternalTexture();
  16530. if (!internalTexture) {
  16531. return;
  16532. }
  16533. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16534. var value = texture.anisotropicFilteringLevel;
  16535. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16536. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16537. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16538. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16539. }
  16540. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16541. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16542. internalTexture._cachedAnisotropicFilteringLevel = value;
  16543. }
  16544. };
  16545. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16546. this._bindTextureDirectly(target, texture, true, true);
  16547. this._gl.texParameterf(target, parameter, value);
  16548. };
  16549. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16550. if (texture) {
  16551. this._bindTextureDirectly(target, texture, true, true);
  16552. }
  16553. this._gl.texParameteri(target, parameter, value);
  16554. };
  16555. /**
  16556. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16557. * @param x defines the x coordinate of the rectangle where pixels must be read
  16558. * @param y defines the y coordinate of the rectangle where pixels must be read
  16559. * @param width defines the width of the rectangle where pixels must be read
  16560. * @param height defines the height of the rectangle where pixels must be read
  16561. * @returns a Uint8Array containing RGBA colors
  16562. */
  16563. Engine.prototype.readPixels = function (x, y, width, height) {
  16564. var data = new Uint8Array(height * width * 4);
  16565. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16566. return data;
  16567. };
  16568. /**
  16569. * Add an externaly attached data from its key.
  16570. * This method call will fail and return false, if such key already exists.
  16571. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16572. * @param key the unique key that identifies the data
  16573. * @param data the data object to associate to the key for this Engine instance
  16574. * @return true if no such key were already present and the data was added successfully, false otherwise
  16575. */
  16576. Engine.prototype.addExternalData = function (key, data) {
  16577. if (!this._externalData) {
  16578. this._externalData = new BABYLON.StringDictionary();
  16579. }
  16580. return this._externalData.add(key, data);
  16581. };
  16582. /**
  16583. * Get an externaly attached data from its key
  16584. * @param key the unique key that identifies the data
  16585. * @return the associated data, if present (can be null), or undefined if not present
  16586. */
  16587. Engine.prototype.getExternalData = function (key) {
  16588. if (!this._externalData) {
  16589. this._externalData = new BABYLON.StringDictionary();
  16590. }
  16591. return this._externalData.get(key);
  16592. };
  16593. /**
  16594. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16595. * @param key the unique key that identifies the data
  16596. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16597. * @return the associated data, can be null if the factory returned null.
  16598. */
  16599. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16600. if (!this._externalData) {
  16601. this._externalData = new BABYLON.StringDictionary();
  16602. }
  16603. return this._externalData.getOrAddWithFactory(key, factory);
  16604. };
  16605. /**
  16606. * Remove an externaly attached data from the Engine instance
  16607. * @param key the unique key that identifies the data
  16608. * @return true if the data was successfully removed, false if it doesn't exist
  16609. */
  16610. Engine.prototype.removeExternalData = function (key) {
  16611. if (!this._externalData) {
  16612. this._externalData = new BABYLON.StringDictionary();
  16613. }
  16614. return this._externalData.remove(key);
  16615. };
  16616. /**
  16617. * Unbind all vertex attributes from the webGL context
  16618. */
  16619. Engine.prototype.unbindAllAttributes = function () {
  16620. if (this._mustWipeVertexAttributes) {
  16621. this._mustWipeVertexAttributes = false;
  16622. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16623. this._gl.disableVertexAttribArray(i);
  16624. this._vertexAttribArraysEnabled[i] = false;
  16625. this._currentBufferPointers[i].active = false;
  16626. }
  16627. return;
  16628. }
  16629. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16630. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16631. continue;
  16632. }
  16633. this._gl.disableVertexAttribArray(i);
  16634. this._vertexAttribArraysEnabled[i] = false;
  16635. this._currentBufferPointers[i].active = false;
  16636. }
  16637. };
  16638. /**
  16639. * 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
  16640. */
  16641. Engine.prototype.releaseEffects = function () {
  16642. for (var name in this._compiledEffects) {
  16643. this._deleteProgram(this._compiledEffects[name]._program);
  16644. }
  16645. this._compiledEffects = {};
  16646. };
  16647. /**
  16648. * Dispose and release all associated resources
  16649. */
  16650. Engine.prototype.dispose = function () {
  16651. this.hideLoadingUI();
  16652. this.stopRenderLoop();
  16653. // Release postProcesses
  16654. while (this.postProcesses.length) {
  16655. this.postProcesses[0].dispose();
  16656. }
  16657. // Empty texture
  16658. if (this._emptyTexture) {
  16659. this._releaseTexture(this._emptyTexture);
  16660. this._emptyTexture = null;
  16661. }
  16662. if (this._emptyCubeTexture) {
  16663. this._releaseTexture(this._emptyCubeTexture);
  16664. this._emptyCubeTexture = null;
  16665. }
  16666. // Rescale PP
  16667. if (this._rescalePostProcess) {
  16668. this._rescalePostProcess.dispose();
  16669. }
  16670. // Release scenes
  16671. while (this.scenes.length) {
  16672. this.scenes[0].dispose();
  16673. }
  16674. // Release audio engine
  16675. if (Engine.audioEngine) {
  16676. Engine.audioEngine.dispose();
  16677. }
  16678. // Release effects
  16679. this.releaseEffects();
  16680. // Unbind
  16681. this.unbindAllAttributes();
  16682. this._boundUniforms = [];
  16683. if (this._dummyFramebuffer) {
  16684. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16685. }
  16686. //WebVR
  16687. this.disableVR();
  16688. // Events
  16689. if (BABYLON.Tools.IsWindowObjectExist()) {
  16690. window.removeEventListener("blur", this._onBlur);
  16691. window.removeEventListener("focus", this._onFocus);
  16692. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16693. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16694. if (this._renderingCanvas) {
  16695. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16696. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16697. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16698. if (!this._doNotHandleContextLost) {
  16699. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16700. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16701. }
  16702. }
  16703. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16704. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16705. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16706. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16707. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16708. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16709. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16710. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16711. if (this._onVrDisplayConnect) {
  16712. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16713. if (this._onVrDisplayDisconnect) {
  16714. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16715. }
  16716. if (this._onVrDisplayPresentChange) {
  16717. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16718. }
  16719. this._onVrDisplayConnect = null;
  16720. this._onVrDisplayDisconnect = null;
  16721. }
  16722. }
  16723. // Remove from Instances
  16724. var index = Engine.Instances.indexOf(this);
  16725. if (index >= 0) {
  16726. Engine.Instances.splice(index, 1);
  16727. }
  16728. this._workingCanvas = null;
  16729. this._workingContext = null;
  16730. this._currentBufferPointers = [];
  16731. this._renderingCanvas = null;
  16732. this._currentProgram = null;
  16733. this._bindedRenderFunction = null;
  16734. this.onResizeObservable.clear();
  16735. this.onCanvasBlurObservable.clear();
  16736. this.onCanvasFocusObservable.clear();
  16737. this.onCanvasPointerOutObservable.clear();
  16738. this.onBeginFrameObservable.clear();
  16739. this.onEndFrameObservable.clear();
  16740. BABYLON.Effect.ResetCache();
  16741. // Abort active requests
  16742. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16743. var request = _a[_i];
  16744. request.abort();
  16745. }
  16746. };
  16747. // Loading screen
  16748. /**
  16749. * Display the loading screen
  16750. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16751. */
  16752. Engine.prototype.displayLoadingUI = function () {
  16753. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16754. return;
  16755. }
  16756. var loadingScreen = this.loadingScreen;
  16757. if (loadingScreen) {
  16758. loadingScreen.displayLoadingUI();
  16759. }
  16760. };
  16761. /**
  16762. * Hide the loading screen
  16763. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16764. */
  16765. Engine.prototype.hideLoadingUI = function () {
  16766. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16767. return;
  16768. }
  16769. var loadingScreen = this.loadingScreen;
  16770. if (loadingScreen) {
  16771. loadingScreen.hideLoadingUI();
  16772. }
  16773. };
  16774. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16775. /**
  16776. * Gets the current loading screen object
  16777. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16778. */
  16779. get: function () {
  16780. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16781. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16782. return this._loadingScreen;
  16783. },
  16784. /**
  16785. * Sets the current loading screen object
  16786. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16787. */
  16788. set: function (loadingScreen) {
  16789. this._loadingScreen = loadingScreen;
  16790. },
  16791. enumerable: true,
  16792. configurable: true
  16793. });
  16794. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16795. /**
  16796. * Sets the current loading screen text
  16797. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16798. */
  16799. set: function (text) {
  16800. this.loadingScreen.loadingUIText = text;
  16801. },
  16802. enumerable: true,
  16803. configurable: true
  16804. });
  16805. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16806. /**
  16807. * Sets the current loading screen background color
  16808. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16809. */
  16810. set: function (color) {
  16811. this.loadingScreen.loadingUIBackgroundColor = color;
  16812. },
  16813. enumerable: true,
  16814. configurable: true
  16815. });
  16816. /**
  16817. * Attach a new callback raised when context lost event is fired
  16818. * @param callback defines the callback to call
  16819. */
  16820. Engine.prototype.attachContextLostEvent = function (callback) {
  16821. if (this._renderingCanvas) {
  16822. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16823. }
  16824. };
  16825. /**
  16826. * Attach a new callback raised when context restored event is fired
  16827. * @param callback defines the callback to call
  16828. */
  16829. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16830. if (this._renderingCanvas) {
  16831. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16832. }
  16833. };
  16834. /**
  16835. * Gets the source code of the vertex shader associated with a specific webGL program
  16836. * @param program defines the program to use
  16837. * @returns a string containing the source code of the vertex shader associated with the program
  16838. */
  16839. Engine.prototype.getVertexShaderSource = function (program) {
  16840. var shaders = this._gl.getAttachedShaders(program);
  16841. if (!shaders) {
  16842. return null;
  16843. }
  16844. return this._gl.getShaderSource(shaders[0]);
  16845. };
  16846. /**
  16847. * Gets the source code of the fragment shader associated with a specific webGL program
  16848. * @param program defines the program to use
  16849. * @returns a string containing the source code of the fragment shader associated with the program
  16850. */
  16851. Engine.prototype.getFragmentShaderSource = function (program) {
  16852. var shaders = this._gl.getAttachedShaders(program);
  16853. if (!shaders) {
  16854. return null;
  16855. }
  16856. return this._gl.getShaderSource(shaders[1]);
  16857. };
  16858. /**
  16859. * Get the current error code of the webGL context
  16860. * @returns the error code
  16861. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16862. */
  16863. Engine.prototype.getError = function () {
  16864. return this._gl.getError();
  16865. };
  16866. // FPS
  16867. /**
  16868. * Gets the current framerate
  16869. * @returns a number representing the framerate
  16870. */
  16871. Engine.prototype.getFps = function () {
  16872. return this._fps;
  16873. };
  16874. /**
  16875. * Gets the time spent between current and previous frame
  16876. * @returns a number representing the delta time in ms
  16877. */
  16878. Engine.prototype.getDeltaTime = function () {
  16879. return this._deltaTime;
  16880. };
  16881. Engine.prototype._measureFps = function () {
  16882. this._performanceMonitor.sampleFrame();
  16883. this._fps = this._performanceMonitor.averageFPS;
  16884. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16885. };
  16886. /** @hidden */
  16887. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16888. if (faceIndex === void 0) { faceIndex = -1; }
  16889. var gl = this._gl;
  16890. if (!this._dummyFramebuffer) {
  16891. var dummy = gl.createFramebuffer();
  16892. if (!dummy) {
  16893. throw new Error("Unable to create dummy framebuffer");
  16894. }
  16895. this._dummyFramebuffer = dummy;
  16896. }
  16897. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16898. if (faceIndex > -1) {
  16899. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16900. }
  16901. else {
  16902. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16903. }
  16904. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16905. var buffer;
  16906. switch (readType) {
  16907. case gl.UNSIGNED_BYTE:
  16908. buffer = new Uint8Array(4 * width * height);
  16909. readType = gl.UNSIGNED_BYTE;
  16910. break;
  16911. default:
  16912. buffer = new Float32Array(4 * width * height);
  16913. readType = gl.FLOAT;
  16914. break;
  16915. }
  16916. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16917. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16918. return buffer;
  16919. };
  16920. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16921. if (this._webGLVersion > 1) {
  16922. return this._caps.colorBufferFloat;
  16923. }
  16924. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16925. };
  16926. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16927. if (this._webGLVersion > 1) {
  16928. return this._caps.colorBufferFloat;
  16929. }
  16930. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16931. };
  16932. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16933. Engine.prototype._canRenderToFramebuffer = function (type) {
  16934. var gl = this._gl;
  16935. //clear existing errors
  16936. while (gl.getError() !== gl.NO_ERROR) { }
  16937. var successful = true;
  16938. var texture = gl.createTexture();
  16939. gl.bindTexture(gl.TEXTURE_2D, texture);
  16940. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16941. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16942. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16943. var fb = gl.createFramebuffer();
  16944. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16945. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16946. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16947. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16948. successful = successful && (gl.getError() === gl.NO_ERROR);
  16949. //try render by clearing frame buffer's color buffer
  16950. if (successful) {
  16951. gl.clear(gl.COLOR_BUFFER_BIT);
  16952. successful = successful && (gl.getError() === gl.NO_ERROR);
  16953. }
  16954. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16955. if (successful) {
  16956. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16957. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16958. var readFormat = gl.RGBA;
  16959. var readType = gl.UNSIGNED_BYTE;
  16960. var buffer = new Uint8Array(4);
  16961. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16962. successful = successful && (gl.getError() === gl.NO_ERROR);
  16963. }
  16964. //clean up
  16965. gl.deleteTexture(texture);
  16966. gl.deleteFramebuffer(fb);
  16967. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16968. //clear accumulated errors
  16969. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16970. return successful;
  16971. };
  16972. /** @hidden */
  16973. Engine.prototype._getWebGLTextureType = function (type) {
  16974. if (type === Engine.TEXTURETYPE_FLOAT) {
  16975. return this._gl.FLOAT;
  16976. }
  16977. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16978. // Add Half Float Constant.
  16979. return this._gl.HALF_FLOAT_OES;
  16980. }
  16981. return this._gl.UNSIGNED_BYTE;
  16982. };
  16983. ;
  16984. Engine.prototype._getInternalFormat = function (format) {
  16985. var internalFormat = this._gl.RGBA;
  16986. switch (format) {
  16987. case Engine.TEXTUREFORMAT_ALPHA:
  16988. internalFormat = this._gl.ALPHA;
  16989. break;
  16990. case Engine.TEXTUREFORMAT_LUMINANCE:
  16991. internalFormat = this._gl.LUMINANCE;
  16992. break;
  16993. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16994. internalFormat = this._gl.LUMINANCE_ALPHA;
  16995. break;
  16996. case Engine.TEXTUREFORMAT_RGB:
  16997. case Engine.TEXTUREFORMAT_RGB32F:
  16998. internalFormat = this._gl.RGB;
  16999. break;
  17000. case Engine.TEXTUREFORMAT_RGBA:
  17001. case Engine.TEXTUREFORMAT_RGBA32F:
  17002. internalFormat = this._gl.RGBA;
  17003. break;
  17004. case Engine.TEXTUREFORMAT_R32F:
  17005. internalFormat = this._gl.RED;
  17006. break;
  17007. case Engine.TEXTUREFORMAT_RG32F:
  17008. internalFormat = this._gl.RG;
  17009. break;
  17010. }
  17011. return internalFormat;
  17012. };
  17013. /** @hidden */
  17014. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17015. if (this._webGLVersion === 1) {
  17016. if (format) {
  17017. switch (format) {
  17018. case Engine.TEXTUREFORMAT_LUMINANCE:
  17019. return this._gl.LUMINANCE;
  17020. }
  17021. }
  17022. return this._gl.RGBA;
  17023. }
  17024. if (type === Engine.TEXTURETYPE_FLOAT) {
  17025. if (format) {
  17026. switch (format) {
  17027. case Engine.TEXTUREFORMAT_R32F:
  17028. return this._gl.R32F;
  17029. case Engine.TEXTUREFORMAT_RG32F:
  17030. return this._gl.RG32F;
  17031. case Engine.TEXTUREFORMAT_RGB32F:
  17032. return this._gl.RGB32F;
  17033. }
  17034. }
  17035. return this._gl.RGBA32F;
  17036. }
  17037. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17038. return this._gl.RGBA16F;
  17039. }
  17040. if (format) {
  17041. switch (format) {
  17042. case Engine.TEXTUREFORMAT_LUMINANCE:
  17043. return this._gl.LUMINANCE;
  17044. case Engine.TEXTUREFORMAT_RGB:
  17045. return this._gl.RGB;
  17046. }
  17047. }
  17048. return this._gl.RGBA;
  17049. };
  17050. ;
  17051. /** @hidden */
  17052. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17053. if (type === Engine.TEXTURETYPE_FLOAT) {
  17054. return this._gl.RGBA32F;
  17055. }
  17056. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17057. return this._gl.RGBA16F;
  17058. }
  17059. return this._gl.RGBA8;
  17060. };
  17061. ;
  17062. /**
  17063. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17064. * @return the new query
  17065. */
  17066. Engine.prototype.createQuery = function () {
  17067. return this._gl.createQuery();
  17068. };
  17069. /**
  17070. * Delete and release a webGL query
  17071. * @param query defines the query to delete
  17072. * @return the current engine
  17073. */
  17074. Engine.prototype.deleteQuery = function (query) {
  17075. this._gl.deleteQuery(query);
  17076. return this;
  17077. };
  17078. /**
  17079. * Check if a given query has resolved and got its value
  17080. * @param query defines the query to check
  17081. * @returns true if the query got its value
  17082. */
  17083. Engine.prototype.isQueryResultAvailable = function (query) {
  17084. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17085. };
  17086. /**
  17087. * Gets the value of a given query
  17088. * @param query defines the query to check
  17089. * @returns the value of the query
  17090. */
  17091. Engine.prototype.getQueryResult = function (query) {
  17092. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17093. };
  17094. /**
  17095. * Initiates an occlusion query
  17096. * @param algorithmType defines the algorithm to use
  17097. * @param query defines the query to use
  17098. * @returns the current engine
  17099. * @see http://doc.babylonjs.com/features/occlusionquery
  17100. */
  17101. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17102. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17103. this._gl.beginQuery(glAlgorithm, query);
  17104. return this;
  17105. };
  17106. /**
  17107. * Ends an occlusion query
  17108. * @see http://doc.babylonjs.com/features/occlusionquery
  17109. * @param algorithmType defines the algorithm to use
  17110. * @returns the current engine
  17111. */
  17112. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17113. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17114. this._gl.endQuery(glAlgorithm);
  17115. return this;
  17116. };
  17117. /* Time queries */
  17118. Engine.prototype._createTimeQuery = function () {
  17119. var timerQuery = this._caps.timerQuery;
  17120. if (timerQuery.createQueryEXT) {
  17121. return timerQuery.createQueryEXT();
  17122. }
  17123. return this.createQuery();
  17124. };
  17125. Engine.prototype._deleteTimeQuery = function (query) {
  17126. var timerQuery = this._caps.timerQuery;
  17127. if (timerQuery.deleteQueryEXT) {
  17128. timerQuery.deleteQueryEXT(query);
  17129. return;
  17130. }
  17131. this.deleteQuery(query);
  17132. };
  17133. Engine.prototype._getTimeQueryResult = function (query) {
  17134. var timerQuery = this._caps.timerQuery;
  17135. if (timerQuery.getQueryObjectEXT) {
  17136. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17137. }
  17138. return this.getQueryResult(query);
  17139. };
  17140. Engine.prototype._getTimeQueryAvailability = function (query) {
  17141. var timerQuery = this._caps.timerQuery;
  17142. if (timerQuery.getQueryObjectEXT) {
  17143. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17144. }
  17145. return this.isQueryResultAvailable(query);
  17146. };
  17147. /**
  17148. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17149. * Please note that only one query can be issued at a time
  17150. * @returns a time token used to track the time span
  17151. */
  17152. Engine.prototype.startTimeQuery = function () {
  17153. var timerQuery = this._caps.timerQuery;
  17154. if (!timerQuery) {
  17155. return null;
  17156. }
  17157. var token = new BABYLON._TimeToken();
  17158. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17159. if (this._caps.canUseTimestampForTimerQuery) {
  17160. token._startTimeQuery = this._createTimeQuery();
  17161. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17162. }
  17163. else {
  17164. if (this._currentNonTimestampToken) {
  17165. return this._currentNonTimestampToken;
  17166. }
  17167. token._timeElapsedQuery = this._createTimeQuery();
  17168. if (timerQuery.beginQueryEXT) {
  17169. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17170. }
  17171. else {
  17172. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17173. }
  17174. this._currentNonTimestampToken = token;
  17175. }
  17176. return token;
  17177. };
  17178. /**
  17179. * Ends a time query
  17180. * @param token defines the token used to measure the time span
  17181. * @returns the time spent (in ns)
  17182. */
  17183. Engine.prototype.endTimeQuery = function (token) {
  17184. var timerQuery = this._caps.timerQuery;
  17185. if (!timerQuery || !token) {
  17186. return -1;
  17187. }
  17188. if (this._caps.canUseTimestampForTimerQuery) {
  17189. if (!token._startTimeQuery) {
  17190. return -1;
  17191. }
  17192. if (!token._endTimeQuery) {
  17193. token._endTimeQuery = this._createTimeQuery();
  17194. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17195. }
  17196. }
  17197. else if (!token._timeElapsedQueryEnded) {
  17198. if (!token._timeElapsedQuery) {
  17199. return -1;
  17200. }
  17201. if (timerQuery.endQueryEXT) {
  17202. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17203. }
  17204. else {
  17205. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17206. }
  17207. token._timeElapsedQueryEnded = true;
  17208. }
  17209. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17210. var available = false;
  17211. if (token._endTimeQuery) {
  17212. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17213. }
  17214. else if (token._timeElapsedQuery) {
  17215. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17216. }
  17217. if (available && !disjoint) {
  17218. var result = 0;
  17219. if (this._caps.canUseTimestampForTimerQuery) {
  17220. if (!token._startTimeQuery || !token._endTimeQuery) {
  17221. return -1;
  17222. }
  17223. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17224. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17225. result = timeEnd - timeStart;
  17226. this._deleteTimeQuery(token._startTimeQuery);
  17227. this._deleteTimeQuery(token._endTimeQuery);
  17228. token._startTimeQuery = null;
  17229. token._endTimeQuery = null;
  17230. }
  17231. else {
  17232. if (!token._timeElapsedQuery) {
  17233. return -1;
  17234. }
  17235. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17236. this._deleteTimeQuery(token._timeElapsedQuery);
  17237. token._timeElapsedQuery = null;
  17238. token._timeElapsedQueryEnded = false;
  17239. this._currentNonTimestampToken = null;
  17240. }
  17241. return result;
  17242. }
  17243. return -1;
  17244. };
  17245. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17246. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17247. };
  17248. // Transform feedback
  17249. /**
  17250. * Creates a webGL transform feedback object
  17251. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17252. * @returns the webGL transform feedback object
  17253. */
  17254. Engine.prototype.createTransformFeedback = function () {
  17255. return this._gl.createTransformFeedback();
  17256. };
  17257. /**
  17258. * Delete a webGL transform feedback object
  17259. * @param value defines the webGL transform feedback object to delete
  17260. */
  17261. Engine.prototype.deleteTransformFeedback = function (value) {
  17262. this._gl.deleteTransformFeedback(value);
  17263. };
  17264. /**
  17265. * Bind a webGL transform feedback object to the webgl context
  17266. * @param value defines the webGL transform feedback object to bind
  17267. */
  17268. Engine.prototype.bindTransformFeedback = function (value) {
  17269. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17270. };
  17271. /**
  17272. * Begins a transform feedback operation
  17273. * @param usePoints defines if points or triangles must be used
  17274. */
  17275. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17276. if (usePoints === void 0) { usePoints = true; }
  17277. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17278. };
  17279. /**
  17280. * Ends a transform feedback operation
  17281. */
  17282. Engine.prototype.endTransformFeedback = function () {
  17283. this._gl.endTransformFeedback();
  17284. };
  17285. /**
  17286. * Specify the varyings to use with transform feedback
  17287. * @param program defines the associated webGL program
  17288. * @param value defines the list of strings representing the varying names
  17289. */
  17290. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17291. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17292. };
  17293. /**
  17294. * Bind a webGL buffer for a transform feedback operation
  17295. * @param value defines the webGL buffer to bind
  17296. */
  17297. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17298. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17299. };
  17300. /** @hidden */
  17301. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17302. var _this = this;
  17303. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17304. this._activeRequests.push(request);
  17305. request.onCompleteObservable.add(function (request) {
  17306. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17307. });
  17308. return request;
  17309. };
  17310. /** @hidden */
  17311. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17312. var _this = this;
  17313. return new Promise(function (resolve, reject) {
  17314. _this._loadFile(url, function (data) {
  17315. resolve(data);
  17316. }, undefined, database, useArrayBuffer, function (request, exception) {
  17317. reject(exception);
  17318. });
  17319. });
  17320. };
  17321. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17322. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17323. var onload = function (data) {
  17324. loadedFiles[index] = data;
  17325. loadedFiles._internalCount++;
  17326. if (loadedFiles._internalCount === 6) {
  17327. onfinish(loadedFiles);
  17328. }
  17329. };
  17330. var onerror = function (request, exception) {
  17331. if (onErrorCallBack && request) {
  17332. onErrorCallBack(request.status + " " + request.statusText, exception);
  17333. }
  17334. };
  17335. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17336. };
  17337. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17338. if (onError === void 0) { onError = null; }
  17339. var loadedFiles = [];
  17340. loadedFiles._internalCount = 0;
  17341. for (var index = 0; index < 6; index++) {
  17342. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17343. }
  17344. };
  17345. // Statics
  17346. /**
  17347. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17348. * @returns true if the engine can be created
  17349. * @ignorenaming
  17350. */
  17351. Engine.isSupported = function () {
  17352. try {
  17353. var tempcanvas = document.createElement("canvas");
  17354. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17355. return gl != null && !!window.WebGLRenderingContext;
  17356. }
  17357. catch (e) {
  17358. return false;
  17359. }
  17360. };
  17361. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17362. Engine.ExceptionList = [
  17363. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17364. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17365. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17366. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17367. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17368. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17369. ];
  17370. /** Gets the list of created engines */
  17371. Engine.Instances = new Array();
  17372. // Const statics
  17373. Engine._ALPHA_DISABLE = 0;
  17374. Engine._ALPHA_ADD = 1;
  17375. Engine._ALPHA_COMBINE = 2;
  17376. Engine._ALPHA_SUBTRACT = 3;
  17377. Engine._ALPHA_MULTIPLY = 4;
  17378. Engine._ALPHA_MAXIMIZED = 5;
  17379. Engine._ALPHA_ONEONE = 6;
  17380. Engine._ALPHA_PREMULTIPLIED = 7;
  17381. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17382. Engine._ALPHA_INTERPOLATE = 9;
  17383. Engine._ALPHA_SCREENMODE = 10;
  17384. Engine._DELAYLOADSTATE_NONE = 0;
  17385. Engine._DELAYLOADSTATE_LOADED = 1;
  17386. Engine._DELAYLOADSTATE_LOADING = 2;
  17387. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17388. Engine._TEXTUREFORMAT_ALPHA = 0;
  17389. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17390. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17391. Engine._TEXTUREFORMAT_RGB = 4;
  17392. Engine._TEXTUREFORMAT_RGBA = 5;
  17393. Engine._TEXTUREFORMAT_R32F = 6;
  17394. Engine._TEXTUREFORMAT_RG32F = 7;
  17395. Engine._TEXTUREFORMAT_RGB32F = 8;
  17396. Engine._TEXTUREFORMAT_RGBA32F = 9;
  17397. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17398. Engine._TEXTURETYPE_FLOAT = 1;
  17399. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17400. // Depht or Stencil test Constants.
  17401. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17402. 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.
  17403. 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.
  17404. 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.
  17405. 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.
  17406. 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.
  17407. 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.
  17408. 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.
  17409. // Stencil Actions Constants.
  17410. Engine._KEEP = 0x1E00;
  17411. Engine._REPLACE = 0x1E01;
  17412. Engine._INCR = 0x1E02;
  17413. Engine._DECR = 0x1E03;
  17414. Engine._INVERT = 0x150A;
  17415. Engine._INCR_WRAP = 0x8507;
  17416. Engine._DECR_WRAP = 0x8508;
  17417. // Texture rescaling mode
  17418. Engine._SCALEMODE_FLOOR = 1;
  17419. Engine._SCALEMODE_NEAREST = 2;
  17420. Engine._SCALEMODE_CEILING = 3;
  17421. // Updatable statics so stick with vars here
  17422. /**
  17423. * Gets or sets the epsilon value used by collision engine
  17424. */
  17425. Engine.CollisionsEpsilon = 0.001;
  17426. /**
  17427. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17428. */
  17429. Engine.CodeRepository = "src/";
  17430. /**
  17431. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17432. */
  17433. Engine.ShadersRepository = "src/Shaders/";
  17434. return Engine;
  17435. }());
  17436. BABYLON.Engine = Engine;
  17437. })(BABYLON || (BABYLON = {}));
  17438. //# sourceMappingURL=babylon.engine.js.map
  17439. var BABYLON;
  17440. (function (BABYLON) {
  17441. /**
  17442. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17443. */
  17444. var Node = /** @class */ (function () {
  17445. /**
  17446. * Creates a new Node
  17447. * @param {string} name - the name and id to be given to this node
  17448. * @param {BABYLON.Scene} the scene this node will be added to
  17449. */
  17450. function Node(name, scene) {
  17451. if (scene === void 0) { scene = null; }
  17452. /**
  17453. * Gets or sets a string used to store user defined state for the node
  17454. */
  17455. this.state = "";
  17456. /**
  17457. * Gets or sets an object used to store user defined information for the node
  17458. */
  17459. this.metadata = null;
  17460. /**
  17461. * Gets or sets a boolean used to define if the node must be serialized
  17462. */
  17463. this.doNotSerialize = false;
  17464. /** @hidden */
  17465. this._isDisposed = false;
  17466. /**
  17467. * Gets a list of Animations associated with the node
  17468. */
  17469. this.animations = new Array();
  17470. this._ranges = {};
  17471. this._isEnabled = true;
  17472. this._isReady = true;
  17473. /** @hidden */
  17474. this._currentRenderId = -1;
  17475. this._parentRenderId = -1;
  17476. this._childRenderId = -1;
  17477. this._animationPropertiesOverride = null;
  17478. /**
  17479. * An event triggered when the mesh is disposed
  17480. */
  17481. this.onDisposeObservable = new BABYLON.Observable();
  17482. // Behaviors
  17483. this._behaviors = new Array();
  17484. this.name = name;
  17485. this.id = name;
  17486. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17487. this.uniqueId = this._scene.getUniqueId();
  17488. this._initCache();
  17489. }
  17490. /**
  17491. * Gets a boolean indicating if the node has been disposed
  17492. * @returns true if the node was disposed
  17493. */
  17494. Node.prototype.isDisposed = function () {
  17495. return this._isDisposed;
  17496. };
  17497. Object.defineProperty(Node.prototype, "parent", {
  17498. get: function () {
  17499. return this._parentNode;
  17500. },
  17501. /**
  17502. * Gets or sets the parent of the node
  17503. */
  17504. set: function (parent) {
  17505. if (this._parentNode === parent) {
  17506. return;
  17507. }
  17508. // Remove self from list of children of parent
  17509. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17510. var index = this._parentNode._children.indexOf(this);
  17511. if (index !== -1) {
  17512. this._parentNode._children.splice(index, 1);
  17513. }
  17514. }
  17515. // Store new parent
  17516. this._parentNode = parent;
  17517. // Add as child to new parent
  17518. if (this._parentNode) {
  17519. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17520. this._parentNode._children = new Array();
  17521. }
  17522. this._parentNode._children.push(this);
  17523. }
  17524. },
  17525. enumerable: true,
  17526. configurable: true
  17527. });
  17528. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17529. /**
  17530. * Gets or sets the animation properties override
  17531. */
  17532. get: function () {
  17533. if (!this._animationPropertiesOverride) {
  17534. return this._scene.animationPropertiesOverride;
  17535. }
  17536. return this._animationPropertiesOverride;
  17537. },
  17538. set: function (value) {
  17539. this._animationPropertiesOverride = value;
  17540. },
  17541. enumerable: true,
  17542. configurable: true
  17543. });
  17544. /**
  17545. * Gets a string idenfifying the name of the class
  17546. * @returns "Node" string
  17547. */
  17548. Node.prototype.getClassName = function () {
  17549. return "Node";
  17550. };
  17551. Object.defineProperty(Node.prototype, "onDispose", {
  17552. /**
  17553. * Sets a callback that will be raised when the node will be disposed
  17554. */
  17555. set: function (callback) {
  17556. if (this._onDisposeObserver) {
  17557. this.onDisposeObservable.remove(this._onDisposeObserver);
  17558. }
  17559. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17560. },
  17561. enumerable: true,
  17562. configurable: true
  17563. });
  17564. /**
  17565. * Gets the scene of the node
  17566. * @returns a {BABYLON.Scene}
  17567. */
  17568. Node.prototype.getScene = function () {
  17569. return this._scene;
  17570. };
  17571. /**
  17572. * Gets the engine of the node
  17573. * @returns a {BABYLON.Engine}
  17574. */
  17575. Node.prototype.getEngine = function () {
  17576. return this._scene.getEngine();
  17577. };
  17578. /**
  17579. * Attach a behavior to the node
  17580. * @see http://doc.babylonjs.com/features/behaviour
  17581. * @param behavior defines the behavior to attach
  17582. * @returns the current Node
  17583. */
  17584. Node.prototype.addBehavior = function (behavior) {
  17585. var _this = this;
  17586. var index = this._behaviors.indexOf(behavior);
  17587. if (index !== -1) {
  17588. return this;
  17589. }
  17590. behavior.init();
  17591. if (this._scene.isLoading) {
  17592. // We defer the attach when the scene will be loaded
  17593. var observer = this._scene.onDataLoadedObservable.add(function () {
  17594. behavior.attach(_this);
  17595. setTimeout(function () {
  17596. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  17597. _this._scene.onDataLoadedObservable.remove(observer);
  17598. }, 0);
  17599. });
  17600. }
  17601. else {
  17602. behavior.attach(this);
  17603. }
  17604. this._behaviors.push(behavior);
  17605. return this;
  17606. };
  17607. /**
  17608. * Remove an attached behavior
  17609. * @see http://doc.babylonjs.com/features/behaviour
  17610. * @param behavior defines the behavior to attach
  17611. * @returns the current Node
  17612. */
  17613. Node.prototype.removeBehavior = function (behavior) {
  17614. var index = this._behaviors.indexOf(behavior);
  17615. if (index === -1) {
  17616. return this;
  17617. }
  17618. this._behaviors[index].detach();
  17619. this._behaviors.splice(index, 1);
  17620. return this;
  17621. };
  17622. Object.defineProperty(Node.prototype, "behaviors", {
  17623. /**
  17624. * Gets the list of attached behaviors
  17625. * @see http://doc.babylonjs.com/features/behaviour
  17626. */
  17627. get: function () {
  17628. return this._behaviors;
  17629. },
  17630. enumerable: true,
  17631. configurable: true
  17632. });
  17633. /**
  17634. * Gets an attached behavior by name
  17635. * @param name defines the name of the behavior to look for
  17636. * @see http://doc.babylonjs.com/features/behaviour
  17637. * @returns null if behavior was not found else the requested behavior
  17638. */
  17639. Node.prototype.getBehaviorByName = function (name) {
  17640. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17641. var behavior = _a[_i];
  17642. if (behavior.name === name) {
  17643. return behavior;
  17644. }
  17645. }
  17646. return null;
  17647. };
  17648. /**
  17649. * Returns the world matrix of the node
  17650. * @returns a matrix containing the node's world matrix
  17651. */
  17652. Node.prototype.getWorldMatrix = function () {
  17653. return BABYLON.Matrix.Identity();
  17654. };
  17655. /** @hidden */
  17656. Node.prototype._getWorldMatrixDeterminant = function () {
  17657. return 1;
  17658. };
  17659. // override it in derived class if you add new variables to the cache
  17660. // and call the parent class method
  17661. /** @hidden */
  17662. Node.prototype._initCache = function () {
  17663. this._cache = {};
  17664. this._cache.parent = undefined;
  17665. };
  17666. /** @hidden */
  17667. Node.prototype.updateCache = function (force) {
  17668. if (!force && this.isSynchronized())
  17669. return;
  17670. this._cache.parent = this.parent;
  17671. this._updateCache();
  17672. };
  17673. // override it in derived class if you add new variables to the cache
  17674. // and call the parent class method if !ignoreParentClass
  17675. /** @hidden */
  17676. Node.prototype._updateCache = function (ignoreParentClass) {
  17677. };
  17678. // override it in derived class if you add new variables to the cache
  17679. /** @hidden */
  17680. Node.prototype._isSynchronized = function () {
  17681. return true;
  17682. };
  17683. /** @hidden */
  17684. Node.prototype._markSyncedWithParent = function () {
  17685. if (this.parent) {
  17686. this._parentRenderId = this.parent._childRenderId;
  17687. }
  17688. };
  17689. /** @hidden */
  17690. Node.prototype.isSynchronizedWithParent = function () {
  17691. if (!this.parent) {
  17692. return true;
  17693. }
  17694. if (this._parentRenderId !== this.parent._childRenderId) {
  17695. return false;
  17696. }
  17697. return this.parent.isSynchronized();
  17698. };
  17699. /** @hidden */
  17700. Node.prototype.isSynchronized = function (updateCache) {
  17701. var check = this.hasNewParent();
  17702. check = check || !this.isSynchronizedWithParent();
  17703. check = check || !this._isSynchronized();
  17704. if (updateCache)
  17705. this.updateCache(true);
  17706. return !check;
  17707. };
  17708. /** @hidden */
  17709. Node.prototype.hasNewParent = function (update) {
  17710. if (this._cache.parent === this.parent)
  17711. return false;
  17712. if (update)
  17713. this._cache.parent = this.parent;
  17714. return true;
  17715. };
  17716. /**
  17717. * Is this node ready to be used/rendered
  17718. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17719. * @return true if the node is ready
  17720. */
  17721. Node.prototype.isReady = function (completeCheck) {
  17722. if (completeCheck === void 0) { completeCheck = false; }
  17723. return this._isReady;
  17724. };
  17725. /**
  17726. * Is this node enabled?
  17727. * 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
  17728. * @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
  17729. * @return whether this node (and its parent) is enabled
  17730. */
  17731. Node.prototype.isEnabled = function (checkAncestors) {
  17732. if (checkAncestors === void 0) { checkAncestors = true; }
  17733. if (checkAncestors === false) {
  17734. return this._isEnabled;
  17735. }
  17736. if (this._isEnabled === false) {
  17737. return false;
  17738. }
  17739. if (this.parent !== undefined && this.parent !== null) {
  17740. return this.parent.isEnabled(checkAncestors);
  17741. }
  17742. return true;
  17743. };
  17744. /**
  17745. * Set the enabled state of this node
  17746. * @param value defines the new enabled state
  17747. */
  17748. Node.prototype.setEnabled = function (value) {
  17749. this._isEnabled = value;
  17750. };
  17751. /**
  17752. * Is this node a descendant of the given node?
  17753. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17754. * @param ancestor defines the parent node to inspect
  17755. * @returns a boolean indicating if this node is a descendant of the given node
  17756. */
  17757. Node.prototype.isDescendantOf = function (ancestor) {
  17758. if (this.parent) {
  17759. if (this.parent === ancestor) {
  17760. return true;
  17761. }
  17762. return this.parent.isDescendantOf(ancestor);
  17763. }
  17764. return false;
  17765. };
  17766. /** @hidden */
  17767. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17768. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17769. if (!this._children) {
  17770. return;
  17771. }
  17772. for (var index = 0; index < this._children.length; index++) {
  17773. var item = this._children[index];
  17774. if (!predicate || predicate(item)) {
  17775. results.push(item);
  17776. }
  17777. if (!directDescendantsOnly) {
  17778. item._getDescendants(results, false, predicate);
  17779. }
  17780. }
  17781. };
  17782. /**
  17783. * Will return all nodes that have this node as ascendant
  17784. * @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
  17785. * @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
  17786. * @return all children nodes of all types
  17787. */
  17788. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17789. var results = new Array();
  17790. this._getDescendants(results, directDescendantsOnly, predicate);
  17791. return results;
  17792. };
  17793. /**
  17794. * Get all child-meshes of this node
  17795. * @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
  17796. * @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
  17797. * @returns an array of {BABYLON.AbstractMesh}
  17798. */
  17799. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17800. var results = [];
  17801. this._getDescendants(results, directDescendantsOnly, function (node) {
  17802. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17803. });
  17804. return results;
  17805. };
  17806. /**
  17807. * Get all child-transformNodes of this node
  17808. * @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
  17809. * @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
  17810. * @returns an array of {BABYLON.TransformNode}
  17811. */
  17812. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17813. var results = [];
  17814. this._getDescendants(results, directDescendantsOnly, function (node) {
  17815. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17816. });
  17817. return results;
  17818. };
  17819. /**
  17820. * Get all direct children of this node
  17821. * @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
  17822. * @returns an array of {BABYLON.Node}
  17823. */
  17824. Node.prototype.getChildren = function (predicate) {
  17825. return this.getDescendants(true, predicate);
  17826. };
  17827. /** @hidden */
  17828. Node.prototype._setReady = function (state) {
  17829. if (state === this._isReady) {
  17830. return;
  17831. }
  17832. if (!state) {
  17833. this._isReady = false;
  17834. return;
  17835. }
  17836. if (this.onReady) {
  17837. this.onReady(this);
  17838. }
  17839. this._isReady = true;
  17840. };
  17841. /**
  17842. * Get an animation by name
  17843. * @param name defines the name of the animation to look for
  17844. * @returns null if not found else the requested animation
  17845. */
  17846. Node.prototype.getAnimationByName = function (name) {
  17847. for (var i = 0; i < this.animations.length; i++) {
  17848. var animation = this.animations[i];
  17849. if (animation.name === name) {
  17850. return animation;
  17851. }
  17852. }
  17853. return null;
  17854. };
  17855. /**
  17856. * Creates an animation range for this node
  17857. * @param name defines the name of the range
  17858. * @param from defines the starting key
  17859. * @param to defines the end key
  17860. */
  17861. Node.prototype.createAnimationRange = function (name, from, to) {
  17862. // check name not already in use
  17863. if (!this._ranges[name]) {
  17864. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17865. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17866. if (this.animations[i]) {
  17867. this.animations[i].createRange(name, from, to);
  17868. }
  17869. }
  17870. }
  17871. };
  17872. /**
  17873. * Delete a specific animation range
  17874. * @param name defines the name of the range to delete
  17875. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17876. */
  17877. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17878. if (deleteFrames === void 0) { deleteFrames = true; }
  17879. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17880. if (this.animations[i]) {
  17881. this.animations[i].deleteRange(name, deleteFrames);
  17882. }
  17883. }
  17884. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17885. };
  17886. /**
  17887. * Get an animation range by name
  17888. * @param name defines the name of the animation range to look for
  17889. * @returns null if not found else the requested animation range
  17890. */
  17891. Node.prototype.getAnimationRange = function (name) {
  17892. return this._ranges[name];
  17893. };
  17894. /**
  17895. * Will start the animation sequence
  17896. * @param name defines the range frames for animation sequence
  17897. * @param loop defines if the animation should loop (false by default)
  17898. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17899. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17900. * @returns the object created for this animation. If range does not exist, it will return null
  17901. */
  17902. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17903. var range = this.getAnimationRange(name);
  17904. if (!range) {
  17905. return null;
  17906. }
  17907. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17908. };
  17909. /**
  17910. * Serialize animation ranges into a JSON compatible object
  17911. * @returns serialization object
  17912. */
  17913. Node.prototype.serializeAnimationRanges = function () {
  17914. var serializationRanges = [];
  17915. for (var name in this._ranges) {
  17916. var localRange = this._ranges[name];
  17917. if (!localRange) {
  17918. continue;
  17919. }
  17920. var range = {};
  17921. range.name = name;
  17922. range.from = localRange.from;
  17923. range.to = localRange.to;
  17924. serializationRanges.push(range);
  17925. }
  17926. return serializationRanges;
  17927. };
  17928. /**
  17929. * Computes the world matrix of the node
  17930. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17931. * @returns the world matrix
  17932. */
  17933. Node.prototype.computeWorldMatrix = function (force) {
  17934. return BABYLON.Matrix.Identity();
  17935. };
  17936. /**
  17937. * Releases resources associated with this node.
  17938. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17939. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17940. */
  17941. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17942. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17943. if (!doNotRecurse) {
  17944. var nodes = this.getDescendants(true);
  17945. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17946. var node = nodes_1[_i];
  17947. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17948. }
  17949. }
  17950. else {
  17951. var transformNodes = this.getChildTransformNodes(true);
  17952. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17953. var transformNode = transformNodes_1[_a];
  17954. transformNode.parent = null;
  17955. transformNode.computeWorldMatrix(true);
  17956. }
  17957. }
  17958. this.parent = null;
  17959. // Callback
  17960. this.onDisposeObservable.notifyObservers(this);
  17961. this.onDisposeObservable.clear();
  17962. // Behaviors
  17963. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17964. var behavior = _c[_b];
  17965. behavior.detach();
  17966. }
  17967. this._behaviors = [];
  17968. this._isDisposed = true;
  17969. };
  17970. /**
  17971. * Parse animation range data from a serialization object and store them into a given node
  17972. * @param node defines where to store the animation ranges
  17973. * @param parsedNode defines the serialization object to read data from
  17974. * @param scene defines the hosting scene
  17975. */
  17976. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17977. if (parsedNode.ranges) {
  17978. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17979. var data = parsedNode.ranges[index];
  17980. node.createAnimationRange(data.name, data.from, data.to);
  17981. }
  17982. }
  17983. };
  17984. __decorate([
  17985. BABYLON.serialize()
  17986. ], Node.prototype, "name", void 0);
  17987. __decorate([
  17988. BABYLON.serialize()
  17989. ], Node.prototype, "id", void 0);
  17990. __decorate([
  17991. BABYLON.serialize()
  17992. ], Node.prototype, "uniqueId", void 0);
  17993. __decorate([
  17994. BABYLON.serialize()
  17995. ], Node.prototype, "state", void 0);
  17996. __decorate([
  17997. BABYLON.serialize()
  17998. ], Node.prototype, "metadata", void 0);
  17999. return Node;
  18000. }());
  18001. BABYLON.Node = Node;
  18002. })(BABYLON || (BABYLON = {}));
  18003. //# sourceMappingURL=babylon.node.js.map
  18004. var BABYLON;
  18005. (function (BABYLON) {
  18006. var BoundingSphere = /** @class */ (function () {
  18007. /**
  18008. * Creates a new bounding sphere
  18009. * @param min defines the minimum vector (in local space)
  18010. * @param max defines the maximum vector (in local space)
  18011. */
  18012. function BoundingSphere(min, max) {
  18013. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18014. this.reConstruct(min, max);
  18015. }
  18016. /**
  18017. * Recreates the entire bounding sphere from scratch
  18018. * @param min defines the new minimum vector (in local space)
  18019. * @param max defines the new maximum vector (in local space)
  18020. */
  18021. BoundingSphere.prototype.reConstruct = function (min, max) {
  18022. this.minimum = min.clone();
  18023. this.maximum = max.clone();
  18024. var distance = BABYLON.Vector3.Distance(min, max);
  18025. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18026. this.radius = distance * 0.5;
  18027. this.centerWorld = BABYLON.Vector3.Zero();
  18028. this._update(BABYLON.Matrix.Identity());
  18029. };
  18030. // Methods
  18031. BoundingSphere.prototype._update = function (world) {
  18032. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18033. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18034. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18035. };
  18036. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18037. for (var i = 0; i < 6; i++) {
  18038. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18039. return false;
  18040. }
  18041. return true;
  18042. };
  18043. BoundingSphere.prototype.intersectsPoint = function (point) {
  18044. var x = this.centerWorld.x - point.x;
  18045. var y = this.centerWorld.y - point.y;
  18046. var z = this.centerWorld.z - point.z;
  18047. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18048. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18049. return false;
  18050. return true;
  18051. };
  18052. // Statics
  18053. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18054. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18055. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18056. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18057. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18058. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18059. return false;
  18060. return true;
  18061. };
  18062. return BoundingSphere;
  18063. }());
  18064. BABYLON.BoundingSphere = BoundingSphere;
  18065. })(BABYLON || (BABYLON = {}));
  18066. //# sourceMappingURL=babylon.boundingSphere.js.map
  18067. var BABYLON;
  18068. (function (BABYLON) {
  18069. var BoundingBox = /** @class */ (function () {
  18070. /**
  18071. * Creates a new bounding box
  18072. * @param min defines the minimum vector (in local space)
  18073. * @param max defines the maximum vector (in local space)
  18074. */
  18075. function BoundingBox(min, max) {
  18076. this.vectorsWorld = new Array();
  18077. this.reConstruct(min, max);
  18078. }
  18079. // Methods
  18080. /**
  18081. * Recreates the entire bounding box from scratch
  18082. * @param min defines the new minimum vector (in local space)
  18083. * @param max defines the new maximum vector (in local space)
  18084. */
  18085. BoundingBox.prototype.reConstruct = function (min, max) {
  18086. this.minimum = min.clone();
  18087. this.maximum = max.clone();
  18088. // Bounding vectors
  18089. this.vectors = new Array();
  18090. this.vectors.push(this.minimum.clone());
  18091. this.vectors.push(this.maximum.clone());
  18092. this.vectors.push(this.minimum.clone());
  18093. this.vectors[2].x = this.maximum.x;
  18094. this.vectors.push(this.minimum.clone());
  18095. this.vectors[3].y = this.maximum.y;
  18096. this.vectors.push(this.minimum.clone());
  18097. this.vectors[4].z = this.maximum.z;
  18098. this.vectors.push(this.maximum.clone());
  18099. this.vectors[5].z = this.minimum.z;
  18100. this.vectors.push(this.maximum.clone());
  18101. this.vectors[6].x = this.minimum.x;
  18102. this.vectors.push(this.maximum.clone());
  18103. this.vectors[7].y = this.minimum.y;
  18104. // OBB
  18105. this.center = this.maximum.add(this.minimum).scale(0.5);
  18106. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18107. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18108. // World
  18109. for (var index = 0; index < this.vectors.length; index++) {
  18110. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18111. }
  18112. this.minimumWorld = BABYLON.Vector3.Zero();
  18113. this.maximumWorld = BABYLON.Vector3.Zero();
  18114. this.centerWorld = BABYLON.Vector3.Zero();
  18115. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18116. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18117. };
  18118. BoundingBox.prototype.getWorldMatrix = function () {
  18119. return this._worldMatrix;
  18120. };
  18121. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18122. this._worldMatrix.copyFrom(matrix);
  18123. return this;
  18124. };
  18125. BoundingBox.prototype._update = function (world) {
  18126. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18127. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18128. for (var index = 0; index < this.vectors.length; index++) {
  18129. var v = this.vectorsWorld[index];
  18130. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18131. if (v.x < this.minimumWorld.x)
  18132. this.minimumWorld.x = v.x;
  18133. if (v.y < this.minimumWorld.y)
  18134. this.minimumWorld.y = v.y;
  18135. if (v.z < this.minimumWorld.z)
  18136. this.minimumWorld.z = v.z;
  18137. if (v.x > this.maximumWorld.x)
  18138. this.maximumWorld.x = v.x;
  18139. if (v.y > this.maximumWorld.y)
  18140. this.maximumWorld.y = v.y;
  18141. if (v.z > this.maximumWorld.z)
  18142. this.maximumWorld.z = v.z;
  18143. }
  18144. // Extend
  18145. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18146. this.extendSizeWorld.scaleInPlace(0.5);
  18147. // OBB
  18148. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18149. this.centerWorld.scaleInPlace(0.5);
  18150. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18151. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18152. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18153. this._worldMatrix = world;
  18154. };
  18155. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18156. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18157. };
  18158. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18159. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18160. };
  18161. BoundingBox.prototype.intersectsPoint = function (point) {
  18162. var delta = -BABYLON.Epsilon;
  18163. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18164. return false;
  18165. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18166. return false;
  18167. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18168. return false;
  18169. return true;
  18170. };
  18171. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18172. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18173. };
  18174. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18175. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18176. return false;
  18177. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18178. return false;
  18179. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18180. return false;
  18181. return true;
  18182. };
  18183. // Statics
  18184. BoundingBox.Intersects = function (box0, box1) {
  18185. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18186. return false;
  18187. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18188. return false;
  18189. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18190. return false;
  18191. return true;
  18192. };
  18193. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18194. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18195. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18196. return (num <= (sphereRadius * sphereRadius));
  18197. };
  18198. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18199. for (var p = 0; p < 6; p++) {
  18200. for (var i = 0; i < 8; i++) {
  18201. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18202. return false;
  18203. }
  18204. }
  18205. }
  18206. return true;
  18207. };
  18208. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18209. for (var p = 0; p < 6; p++) {
  18210. var inCount = 8;
  18211. for (var i = 0; i < 8; i++) {
  18212. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18213. --inCount;
  18214. }
  18215. else {
  18216. break;
  18217. }
  18218. }
  18219. if (inCount === 0)
  18220. return false;
  18221. }
  18222. return true;
  18223. };
  18224. return BoundingBox;
  18225. }());
  18226. BABYLON.BoundingBox = BoundingBox;
  18227. })(BABYLON || (BABYLON = {}));
  18228. //# sourceMappingURL=babylon.boundingBox.js.map
  18229. var BABYLON;
  18230. (function (BABYLON) {
  18231. var computeBoxExtents = function (axis, box) {
  18232. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18233. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18234. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18235. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18236. var r = r0 + r1 + r2;
  18237. return {
  18238. min: p - r,
  18239. max: p + r
  18240. };
  18241. };
  18242. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18243. var axisOverlap = function (axis, box0, box1) {
  18244. var result0 = computeBoxExtents(axis, box0);
  18245. var result1 = computeBoxExtents(axis, box1);
  18246. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18247. };
  18248. var BoundingInfo = /** @class */ (function () {
  18249. function BoundingInfo(minimum, maximum) {
  18250. this.minimum = minimum;
  18251. this.maximum = maximum;
  18252. this._isLocked = false;
  18253. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18254. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18255. }
  18256. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18257. get: function () {
  18258. return this._isLocked;
  18259. },
  18260. set: function (value) {
  18261. this._isLocked = value;
  18262. },
  18263. enumerable: true,
  18264. configurable: true
  18265. });
  18266. // Methods
  18267. BoundingInfo.prototype.update = function (world) {
  18268. if (this._isLocked) {
  18269. return;
  18270. }
  18271. this.boundingBox._update(world);
  18272. this.boundingSphere._update(world);
  18273. };
  18274. /**
  18275. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18276. * @param center New center of the bounding info
  18277. * @param extend New extend of the bounding info
  18278. */
  18279. BoundingInfo.prototype.centerOn = function (center, extend) {
  18280. this.minimum = center.subtract(extend);
  18281. this.maximum = center.add(extend);
  18282. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18283. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18284. return this;
  18285. };
  18286. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18287. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18288. return false;
  18289. return this.boundingBox.isInFrustum(frustumPlanes);
  18290. };
  18291. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18292. /**
  18293. * Gets the world distance between the min and max points of the bounding box
  18294. */
  18295. get: function () {
  18296. var boundingBox = this.boundingBox;
  18297. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18298. return size.length();
  18299. },
  18300. enumerable: true,
  18301. configurable: true
  18302. });
  18303. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18304. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18305. };
  18306. BoundingInfo.prototype._checkCollision = function (collider) {
  18307. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18308. };
  18309. BoundingInfo.prototype.intersectsPoint = function (point) {
  18310. if (!this.boundingSphere.centerWorld) {
  18311. return false;
  18312. }
  18313. if (!this.boundingSphere.intersectsPoint(point)) {
  18314. return false;
  18315. }
  18316. if (!this.boundingBox.intersectsPoint(point)) {
  18317. return false;
  18318. }
  18319. return true;
  18320. };
  18321. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18322. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18323. return false;
  18324. }
  18325. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18326. return false;
  18327. }
  18328. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18329. return false;
  18330. }
  18331. if (!precise) {
  18332. return true;
  18333. }
  18334. var box0 = this.boundingBox;
  18335. var box1 = boundingInfo.boundingBox;
  18336. if (!axisOverlap(box0.directions[0], box0, box1))
  18337. return false;
  18338. if (!axisOverlap(box0.directions[1], box0, box1))
  18339. return false;
  18340. if (!axisOverlap(box0.directions[2], box0, box1))
  18341. return false;
  18342. if (!axisOverlap(box1.directions[0], box0, box1))
  18343. return false;
  18344. if (!axisOverlap(box1.directions[1], box0, box1))
  18345. return false;
  18346. if (!axisOverlap(box1.directions[2], box0, box1))
  18347. return false;
  18348. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18349. return false;
  18350. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18351. return false;
  18352. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18353. return false;
  18354. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18355. return false;
  18356. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18357. return false;
  18358. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18359. return false;
  18360. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18361. return false;
  18362. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18363. return false;
  18364. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18365. return false;
  18366. return true;
  18367. };
  18368. return BoundingInfo;
  18369. }());
  18370. BABYLON.BoundingInfo = BoundingInfo;
  18371. })(BABYLON || (BABYLON = {}));
  18372. //# sourceMappingURL=babylon.boundingInfo.js.map
  18373. var BABYLON;
  18374. (function (BABYLON) {
  18375. var TransformNode = /** @class */ (function (_super) {
  18376. __extends(TransformNode, _super);
  18377. function TransformNode(name, scene, isPure) {
  18378. if (scene === void 0) { scene = null; }
  18379. if (isPure === void 0) { isPure = true; }
  18380. var _this = _super.call(this, name, scene) || this;
  18381. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18382. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18383. _this._up = new BABYLON.Vector3(0, 1, 0);
  18384. _this._right = new BABYLON.Vector3(1, 0, 0);
  18385. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18386. // Properties
  18387. _this._rotation = BABYLON.Vector3.Zero();
  18388. _this._scaling = BABYLON.Vector3.One();
  18389. _this._isDirty = false;
  18390. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18391. _this.scalingDeterminant = 1;
  18392. _this.infiniteDistance = false;
  18393. _this.position = BABYLON.Vector3.Zero();
  18394. _this._localWorld = BABYLON.Matrix.Zero();
  18395. _this._worldMatrix = BABYLON.Matrix.Zero();
  18396. _this._worldMatrixDeterminant = 0;
  18397. _this._absolutePosition = BABYLON.Vector3.Zero();
  18398. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18399. _this._postMultiplyPivotMatrix = false;
  18400. _this._isWorldMatrixFrozen = false;
  18401. /**
  18402. * An event triggered after the world matrix is updated
  18403. */
  18404. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18405. _this._nonUniformScaling = false;
  18406. if (isPure) {
  18407. _this.getScene().addTransformNode(_this);
  18408. }
  18409. return _this;
  18410. }
  18411. /**
  18412. * Gets a string idenfifying the name of the class
  18413. * @returns "TransformNode" string
  18414. */
  18415. TransformNode.prototype.getClassName = function () {
  18416. return "TransformNode";
  18417. };
  18418. Object.defineProperty(TransformNode.prototype, "rotation", {
  18419. /**
  18420. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18421. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18422. * Default : (0.0, 0.0, 0.0)
  18423. */
  18424. get: function () {
  18425. return this._rotation;
  18426. },
  18427. set: function (newRotation) {
  18428. this._rotation = newRotation;
  18429. },
  18430. enumerable: true,
  18431. configurable: true
  18432. });
  18433. Object.defineProperty(TransformNode.prototype, "scaling", {
  18434. /**
  18435. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18436. * Default : (1.0, 1.0, 1.0)
  18437. */
  18438. get: function () {
  18439. return this._scaling;
  18440. },
  18441. /**
  18442. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18443. * Default : (1.0, 1.0, 1.0)
  18444. */
  18445. set: function (newScaling) {
  18446. this._scaling = newScaling;
  18447. },
  18448. enumerable: true,
  18449. configurable: true
  18450. });
  18451. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18452. /**
  18453. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18454. * It's null by default.
  18455. * 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)
  18456. */
  18457. get: function () {
  18458. return this._rotationQuaternion;
  18459. },
  18460. set: function (quaternion) {
  18461. this._rotationQuaternion = quaternion;
  18462. //reset the rotation vector.
  18463. if (quaternion && this.rotation.length()) {
  18464. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18465. }
  18466. },
  18467. enumerable: true,
  18468. configurable: true
  18469. });
  18470. Object.defineProperty(TransformNode.prototype, "forward", {
  18471. /**
  18472. * The forward direction of that transform in world space.
  18473. */
  18474. get: function () {
  18475. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18476. },
  18477. enumerable: true,
  18478. configurable: true
  18479. });
  18480. Object.defineProperty(TransformNode.prototype, "up", {
  18481. /**
  18482. * The up direction of that transform in world space.
  18483. */
  18484. get: function () {
  18485. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18486. },
  18487. enumerable: true,
  18488. configurable: true
  18489. });
  18490. Object.defineProperty(TransformNode.prototype, "right", {
  18491. /**
  18492. * The right direction of that transform in world space.
  18493. */
  18494. get: function () {
  18495. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18496. },
  18497. enumerable: true,
  18498. configurable: true
  18499. });
  18500. /**
  18501. * Returns the latest update of the World matrix
  18502. * Returns a Matrix.
  18503. */
  18504. TransformNode.prototype.getWorldMatrix = function () {
  18505. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18506. this.computeWorldMatrix();
  18507. }
  18508. return this._worldMatrix;
  18509. };
  18510. /** @hidden */
  18511. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18512. return this._worldMatrixDeterminant;
  18513. };
  18514. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18515. /**
  18516. * Returns directly the latest state of the mesh World matrix.
  18517. * A Matrix is returned.
  18518. */
  18519. get: function () {
  18520. return this._worldMatrix;
  18521. },
  18522. enumerable: true,
  18523. configurable: true
  18524. });
  18525. /**
  18526. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18527. * Returns the TransformNode.
  18528. */
  18529. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18530. this._poseMatrix.copyFrom(matrix);
  18531. return this;
  18532. };
  18533. /**
  18534. * Returns the mesh Pose matrix.
  18535. * Returned object : Matrix
  18536. */
  18537. TransformNode.prototype.getPoseMatrix = function () {
  18538. return this._poseMatrix;
  18539. };
  18540. TransformNode.prototype._isSynchronized = function () {
  18541. if (this._isDirty) {
  18542. return false;
  18543. }
  18544. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18545. return false;
  18546. if (this._cache.pivotMatrixUpdated) {
  18547. return false;
  18548. }
  18549. if (this.infiniteDistance) {
  18550. return false;
  18551. }
  18552. if (!this._cache.position.equals(this.position))
  18553. return false;
  18554. if (this.rotationQuaternion) {
  18555. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18556. return false;
  18557. }
  18558. if (!this._cache.rotation.equals(this.rotation))
  18559. return false;
  18560. if (!this._cache.scaling.equals(this.scaling))
  18561. return false;
  18562. return true;
  18563. };
  18564. TransformNode.prototype._initCache = function () {
  18565. _super.prototype._initCache.call(this);
  18566. this._cache.localMatrixUpdated = false;
  18567. this._cache.position = BABYLON.Vector3.Zero();
  18568. this._cache.scaling = BABYLON.Vector3.Zero();
  18569. this._cache.rotation = BABYLON.Vector3.Zero();
  18570. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18571. this._cache.billboardMode = -1;
  18572. };
  18573. TransformNode.prototype.markAsDirty = function (property) {
  18574. if (property === "rotation") {
  18575. this.rotationQuaternion = null;
  18576. }
  18577. this._currentRenderId = Number.MAX_VALUE;
  18578. this._isDirty = true;
  18579. return this;
  18580. };
  18581. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18582. /**
  18583. * Returns the current mesh absolute position.
  18584. * Retuns a Vector3.
  18585. */
  18586. get: function () {
  18587. return this._absolutePosition;
  18588. },
  18589. enumerable: true,
  18590. configurable: true
  18591. });
  18592. /**
  18593. * Sets a new matrix to apply before all other transformation
  18594. * @param matrix defines the transform matrix
  18595. * @returns the current TransformNode
  18596. */
  18597. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18598. return this.setPivotMatrix(matrix, false);
  18599. };
  18600. /**
  18601. * Sets a new pivot matrix to the current node
  18602. * @param matrix defines the new pivot matrix to use
  18603. * @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
  18604. * @returns the current TransformNode
  18605. */
  18606. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18607. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18608. this._pivotMatrix = matrix.clone();
  18609. this._cache.pivotMatrixUpdated = true;
  18610. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18611. if (this._postMultiplyPivotMatrix) {
  18612. if (!this._pivotMatrixInverse) {
  18613. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18614. }
  18615. else {
  18616. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18617. }
  18618. }
  18619. return this;
  18620. };
  18621. /**
  18622. * Returns the mesh pivot matrix.
  18623. * Default : Identity.
  18624. * A Matrix is returned.
  18625. */
  18626. TransformNode.prototype.getPivotMatrix = function () {
  18627. return this._pivotMatrix;
  18628. };
  18629. /**
  18630. * Prevents the World matrix to be computed any longer.
  18631. * Returns the TransformNode.
  18632. */
  18633. TransformNode.prototype.freezeWorldMatrix = function () {
  18634. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18635. this.computeWorldMatrix(true);
  18636. this._isWorldMatrixFrozen = true;
  18637. return this;
  18638. };
  18639. /**
  18640. * Allows back the World matrix computation.
  18641. * Returns the TransformNode.
  18642. */
  18643. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18644. this._isWorldMatrixFrozen = false;
  18645. this.computeWorldMatrix(true);
  18646. return this;
  18647. };
  18648. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18649. /**
  18650. * True if the World matrix has been frozen.
  18651. * Returns a boolean.
  18652. */
  18653. get: function () {
  18654. return this._isWorldMatrixFrozen;
  18655. },
  18656. enumerable: true,
  18657. configurable: true
  18658. });
  18659. /**
  18660. * Retuns the mesh absolute position in the World.
  18661. * Returns a Vector3.
  18662. */
  18663. TransformNode.prototype.getAbsolutePosition = function () {
  18664. this.computeWorldMatrix();
  18665. return this._absolutePosition;
  18666. };
  18667. /**
  18668. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18669. * Returns the TransformNode.
  18670. */
  18671. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18672. if (!absolutePosition) {
  18673. return this;
  18674. }
  18675. var absolutePositionX;
  18676. var absolutePositionY;
  18677. var absolutePositionZ;
  18678. if (absolutePosition.x === undefined) {
  18679. if (arguments.length < 3) {
  18680. return this;
  18681. }
  18682. absolutePositionX = arguments[0];
  18683. absolutePositionY = arguments[1];
  18684. absolutePositionZ = arguments[2];
  18685. }
  18686. else {
  18687. absolutePositionX = absolutePosition.x;
  18688. absolutePositionY = absolutePosition.y;
  18689. absolutePositionZ = absolutePosition.z;
  18690. }
  18691. if (this.parent) {
  18692. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18693. invertParentWorldMatrix.invert();
  18694. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18695. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18696. }
  18697. else {
  18698. this.position.x = absolutePositionX;
  18699. this.position.y = absolutePositionY;
  18700. this.position.z = absolutePositionZ;
  18701. }
  18702. return this;
  18703. };
  18704. /**
  18705. * Sets the mesh position in its local space.
  18706. * Returns the TransformNode.
  18707. */
  18708. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18709. this.computeWorldMatrix();
  18710. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18711. return this;
  18712. };
  18713. /**
  18714. * Returns the mesh position in the local space from the current World matrix values.
  18715. * Returns a new Vector3.
  18716. */
  18717. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18718. this.computeWorldMatrix();
  18719. var invLocalWorldMatrix = this._localWorld.clone();
  18720. invLocalWorldMatrix.invert();
  18721. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18722. };
  18723. /**
  18724. * Translates the mesh along the passed Vector3 in its local space.
  18725. * Returns the TransformNode.
  18726. */
  18727. TransformNode.prototype.locallyTranslate = function (vector3) {
  18728. this.computeWorldMatrix(true);
  18729. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18730. return this;
  18731. };
  18732. /**
  18733. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18734. * @param targetPoint the position (must be in same space as current mesh) to look at
  18735. * @param yawCor optional yaw (y-axis) correction in radians
  18736. * @param pitchCor optional pitch (x-axis) correction in radians
  18737. * @param rollCor optional roll (z-axis) correction in radians
  18738. * @param space the choosen space of the target
  18739. * @returns the TransformNode.
  18740. */
  18741. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18742. if (yawCor === void 0) { yawCor = 0; }
  18743. if (pitchCor === void 0) { pitchCor = 0; }
  18744. if (rollCor === void 0) { rollCor = 0; }
  18745. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18746. var dv = TransformNode._lookAtVectorCache;
  18747. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18748. targetPoint.subtractToRef(pos, dv);
  18749. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18750. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18751. var pitch = Math.atan2(dv.y, len);
  18752. if (this.rotationQuaternion) {
  18753. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18754. }
  18755. else {
  18756. this.rotation.x = pitch + pitchCor;
  18757. this.rotation.y = yaw + yawCor;
  18758. this.rotation.z = rollCor;
  18759. }
  18760. return this;
  18761. };
  18762. /**
  18763. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18764. * This Vector3 is expressed in the World space.
  18765. */
  18766. TransformNode.prototype.getDirection = function (localAxis) {
  18767. var result = BABYLON.Vector3.Zero();
  18768. this.getDirectionToRef(localAxis, result);
  18769. return result;
  18770. };
  18771. /**
  18772. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18773. * localAxis is expressed in the mesh local space.
  18774. * result is computed in the Wordl space from the mesh World matrix.
  18775. * Returns the TransformNode.
  18776. */
  18777. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18778. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18779. return this;
  18780. };
  18781. /**
  18782. * Sets a new pivot point to the current node
  18783. * @param point defines the new pivot point to use
  18784. * @param space defines if the point is in world or local space (local by default)
  18785. * @returns the current TransformNode
  18786. */
  18787. TransformNode.prototype.setPivotPoint = function (point, space) {
  18788. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18789. if (this.getScene().getRenderId() == 0) {
  18790. this.computeWorldMatrix(true);
  18791. }
  18792. var wm = this.getWorldMatrix();
  18793. if (space == BABYLON.Space.WORLD) {
  18794. var tmat = BABYLON.Tmp.Matrix[0];
  18795. wm.invertToRef(tmat);
  18796. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18797. }
  18798. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18799. };
  18800. /**
  18801. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18802. */
  18803. TransformNode.prototype.getPivotPoint = function () {
  18804. var point = BABYLON.Vector3.Zero();
  18805. this.getPivotPointToRef(point);
  18806. return point;
  18807. };
  18808. /**
  18809. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18810. * Returns the TransformNode.
  18811. */
  18812. TransformNode.prototype.getPivotPointToRef = function (result) {
  18813. result.x = -this._pivotMatrix.m[12];
  18814. result.y = -this._pivotMatrix.m[13];
  18815. result.z = -this._pivotMatrix.m[14];
  18816. return this;
  18817. };
  18818. /**
  18819. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18820. */
  18821. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18822. var point = BABYLON.Vector3.Zero();
  18823. this.getAbsolutePivotPointToRef(point);
  18824. return point;
  18825. };
  18826. /**
  18827. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18828. * Returns the TransformNode.
  18829. */
  18830. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18831. result.x = this._pivotMatrix.m[12];
  18832. result.y = this._pivotMatrix.m[13];
  18833. result.z = this._pivotMatrix.m[14];
  18834. this.getPivotPointToRef(result);
  18835. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18836. return this;
  18837. };
  18838. /**
  18839. * Defines the passed node as the parent of the current node.
  18840. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18841. * Returns the TransformNode.
  18842. */
  18843. TransformNode.prototype.setParent = function (node) {
  18844. if (node === null) {
  18845. var rotation = BABYLON.Tmp.Quaternion[0];
  18846. var position = BABYLON.Tmp.Vector3[0];
  18847. var scale = BABYLON.Tmp.Vector3[1];
  18848. if (this.parent && this.parent.computeWorldMatrix) {
  18849. this.parent.computeWorldMatrix(true);
  18850. }
  18851. this.computeWorldMatrix(true);
  18852. this.getWorldMatrix().decompose(scale, rotation, position);
  18853. if (this.rotationQuaternion) {
  18854. this.rotationQuaternion.copyFrom(rotation);
  18855. }
  18856. else {
  18857. rotation.toEulerAnglesToRef(this.rotation);
  18858. }
  18859. this.scaling.x = scale.x;
  18860. this.scaling.y = scale.y;
  18861. this.scaling.z = scale.z;
  18862. this.position.x = position.x;
  18863. this.position.y = position.y;
  18864. this.position.z = position.z;
  18865. }
  18866. else {
  18867. var rotation = BABYLON.Tmp.Quaternion[0];
  18868. var position = BABYLON.Tmp.Vector3[0];
  18869. var scale = BABYLON.Tmp.Vector3[1];
  18870. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18871. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18872. this.computeWorldMatrix(true);
  18873. node.computeWorldMatrix(true);
  18874. node.getWorldMatrix().invertToRef(invParentMatrix);
  18875. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18876. diffMatrix.decompose(scale, rotation, position);
  18877. if (this.rotationQuaternion) {
  18878. this.rotationQuaternion.copyFrom(rotation);
  18879. }
  18880. else {
  18881. rotation.toEulerAnglesToRef(this.rotation);
  18882. }
  18883. this.position.x = position.x;
  18884. this.position.y = position.y;
  18885. this.position.z = position.z;
  18886. this.scaling.x = scale.x;
  18887. this.scaling.y = scale.y;
  18888. this.scaling.z = scale.z;
  18889. }
  18890. this.parent = node;
  18891. return this;
  18892. };
  18893. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18894. get: function () {
  18895. return this._nonUniformScaling;
  18896. },
  18897. enumerable: true,
  18898. configurable: true
  18899. });
  18900. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18901. if (this._nonUniformScaling === value) {
  18902. return false;
  18903. }
  18904. this._nonUniformScaling = true;
  18905. return true;
  18906. };
  18907. /**
  18908. * Attach the current TransformNode to another TransformNode associated with a bone
  18909. * @param bone Bone affecting the TransformNode
  18910. * @param affectedTransformNode TransformNode associated with the bone
  18911. */
  18912. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18913. this._transformToBoneReferal = affectedTransformNode;
  18914. this.parent = bone;
  18915. if (bone.getWorldMatrix().determinant() < 0) {
  18916. this.scalingDeterminant *= -1;
  18917. }
  18918. return this;
  18919. };
  18920. TransformNode.prototype.detachFromBone = function () {
  18921. if (!this.parent) {
  18922. return this;
  18923. }
  18924. if (this.parent.getWorldMatrix().determinant() < 0) {
  18925. this.scalingDeterminant *= -1;
  18926. }
  18927. this._transformToBoneReferal = null;
  18928. this.parent = null;
  18929. return this;
  18930. };
  18931. /**
  18932. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18933. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18934. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18935. * The passed axis is also normalized.
  18936. * Returns the TransformNode.
  18937. */
  18938. TransformNode.prototype.rotate = function (axis, amount, space) {
  18939. axis.normalize();
  18940. if (!this.rotationQuaternion) {
  18941. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18942. this.rotation = BABYLON.Vector3.Zero();
  18943. }
  18944. var rotationQuaternion;
  18945. if (!space || space === BABYLON.Space.LOCAL) {
  18946. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18947. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18948. }
  18949. else {
  18950. if (this.parent) {
  18951. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18952. invertParentWorldMatrix.invert();
  18953. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18954. }
  18955. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18956. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18957. }
  18958. return this;
  18959. };
  18960. /**
  18961. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18962. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18963. * The passed axis is also normalized.
  18964. * Returns the TransformNode.
  18965. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18966. */
  18967. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18968. axis.normalize();
  18969. if (!this.rotationQuaternion) {
  18970. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18971. this.rotation.copyFromFloats(0, 0, 0);
  18972. }
  18973. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18974. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18975. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18976. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18977. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18978. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18979. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18980. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18981. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18982. return this;
  18983. };
  18984. /**
  18985. * Translates the mesh along the axis vector for the passed distance in the given space.
  18986. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18987. * Returns the TransformNode.
  18988. */
  18989. TransformNode.prototype.translate = function (axis, distance, space) {
  18990. var displacementVector = axis.scale(distance);
  18991. if (!space || space === BABYLON.Space.LOCAL) {
  18992. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18993. this.setPositionWithLocalVector(tempV3);
  18994. }
  18995. else {
  18996. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18997. }
  18998. return this;
  18999. };
  19000. /**
  19001. * Adds a rotation step to the mesh current rotation.
  19002. * x, y, z are Euler angles expressed in radians.
  19003. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19004. * This means this rotation is made in the mesh local space only.
  19005. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19006. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19007. * ```javascript
  19008. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19009. * ```
  19010. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19011. * 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.
  19012. * Returns the TransformNode.
  19013. */
  19014. TransformNode.prototype.addRotation = function (x, y, z) {
  19015. var rotationQuaternion;
  19016. if (this.rotationQuaternion) {
  19017. rotationQuaternion = this.rotationQuaternion;
  19018. }
  19019. else {
  19020. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19021. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19022. }
  19023. var accumulation = BABYLON.Tmp.Quaternion[0];
  19024. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19025. rotationQuaternion.multiplyInPlace(accumulation);
  19026. if (!this.rotationQuaternion) {
  19027. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19028. }
  19029. return this;
  19030. };
  19031. /**
  19032. * Computes the mesh World matrix and returns it.
  19033. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19034. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19035. * If the parameter `force`is set to `true`, the actual computation is done.
  19036. * Returns the mesh World Matrix.
  19037. */
  19038. TransformNode.prototype.computeWorldMatrix = function (force) {
  19039. if (this._isWorldMatrixFrozen) {
  19040. return this._worldMatrix;
  19041. }
  19042. if (!force && this.isSynchronized(true)) {
  19043. this._currentRenderId = this.getScene().getRenderId();
  19044. return this._worldMatrix;
  19045. }
  19046. this._cache.position.copyFrom(this.position);
  19047. this._cache.scaling.copyFrom(this.scaling);
  19048. this._cache.pivotMatrixUpdated = false;
  19049. this._cache.billboardMode = this.billboardMode;
  19050. this._currentRenderId = this.getScene().getRenderId();
  19051. this._childRenderId = this.getScene().getRenderId();
  19052. this._isDirty = false;
  19053. // Scaling
  19054. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19055. // Rotation
  19056. //rotate, if quaternion is set and rotation was used
  19057. if (this.rotationQuaternion) {
  19058. var len = this.rotation.length();
  19059. if (len) {
  19060. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19061. this.rotation.copyFromFloats(0, 0, 0);
  19062. }
  19063. }
  19064. if (this.rotationQuaternion) {
  19065. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19066. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19067. }
  19068. else {
  19069. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19070. this._cache.rotation.copyFrom(this.rotation);
  19071. }
  19072. // Translation
  19073. var camera = this.getScene().activeCamera;
  19074. if (this.infiniteDistance && !this.parent && camera) {
  19075. var cameraWorldMatrix = camera.getWorldMatrix();
  19076. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19077. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19078. }
  19079. else {
  19080. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19081. }
  19082. // Composing transformations
  19083. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19084. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19085. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19086. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19087. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19088. // Need to decompose each rotation here
  19089. var currentPosition = BABYLON.Tmp.Vector3[3];
  19090. if (this.parent && this.parent.getWorldMatrix) {
  19091. if (this._transformToBoneReferal) {
  19092. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19093. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19094. }
  19095. else {
  19096. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19097. }
  19098. }
  19099. else {
  19100. currentPosition.copyFrom(this.position);
  19101. }
  19102. currentPosition.subtractInPlace(camera.globalPosition);
  19103. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19104. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19105. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19106. }
  19107. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19108. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19109. }
  19110. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19111. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19112. }
  19113. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19114. }
  19115. else {
  19116. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19117. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19118. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19119. }
  19120. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19121. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19122. }
  19123. // Local world
  19124. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19125. // Parent
  19126. if (this.parent && this.parent.getWorldMatrix) {
  19127. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19128. if (this._transformToBoneReferal) {
  19129. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19130. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19131. }
  19132. else {
  19133. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19134. }
  19135. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19136. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19137. this._worldMatrix.copyFrom(this._localWorld);
  19138. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19139. }
  19140. else {
  19141. if (this._transformToBoneReferal) {
  19142. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19143. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19144. }
  19145. else {
  19146. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19147. }
  19148. }
  19149. this._markSyncedWithParent();
  19150. }
  19151. else {
  19152. this._worldMatrix.copyFrom(this._localWorld);
  19153. }
  19154. // Post multiply inverse of pivotMatrix
  19155. if (this._postMultiplyPivotMatrix) {
  19156. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19157. }
  19158. // Normal matrix
  19159. if (this.scaling.isNonUniform) {
  19160. this._updateNonUniformScalingState(true);
  19161. }
  19162. else if (this.parent && this.parent._nonUniformScaling) {
  19163. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19164. }
  19165. else {
  19166. this._updateNonUniformScalingState(false);
  19167. }
  19168. this._afterComputeWorldMatrix();
  19169. // Absolute position
  19170. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19171. // Callbacks
  19172. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19173. if (!this._poseMatrix) {
  19174. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19175. }
  19176. // Cache the determinant
  19177. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19178. return this._worldMatrix;
  19179. };
  19180. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19181. };
  19182. /**
  19183. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19184. * @param func: callback function to add
  19185. *
  19186. * Returns the TransformNode.
  19187. */
  19188. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19189. this.onAfterWorldMatrixUpdateObservable.add(func);
  19190. return this;
  19191. };
  19192. /**
  19193. * Removes a registered callback function.
  19194. * Returns the TransformNode.
  19195. */
  19196. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19197. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19198. return this;
  19199. };
  19200. /**
  19201. * Clone the current transform node
  19202. * Returns the new transform node
  19203. * @param name Name of the new clone
  19204. * @param newParent New parent for the clone
  19205. * @param doNotCloneChildren Do not clone children hierarchy
  19206. */
  19207. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19208. var _this = this;
  19209. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19210. result.name = name;
  19211. result.id = name;
  19212. if (newParent) {
  19213. result.parent = newParent;
  19214. }
  19215. if (!doNotCloneChildren) {
  19216. // Children
  19217. var directDescendants = this.getDescendants(true);
  19218. for (var index = 0; index < directDescendants.length; index++) {
  19219. var child = directDescendants[index];
  19220. if (child.clone) {
  19221. child.clone(name + "." + child.name, result);
  19222. }
  19223. }
  19224. }
  19225. return result;
  19226. };
  19227. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19228. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19229. serializationObject.type = this.getClassName();
  19230. // Parent
  19231. if (this.parent) {
  19232. serializationObject.parentId = this.parent.id;
  19233. }
  19234. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19235. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19236. }
  19237. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19238. serializationObject.isEnabled = this.isEnabled();
  19239. // Parent
  19240. if (this.parent) {
  19241. serializationObject.parentId = this.parent.id;
  19242. }
  19243. return serializationObject;
  19244. };
  19245. // Statics
  19246. /**
  19247. * Returns a new TransformNode object parsed from the source provided.
  19248. * The parameter `parsedMesh` is the source.
  19249. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19250. */
  19251. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19252. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19253. if (BABYLON.Tags) {
  19254. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19255. }
  19256. if (parsedTransformNode.localMatrix) {
  19257. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19258. }
  19259. else if (parsedTransformNode.pivotMatrix) {
  19260. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19261. }
  19262. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19263. // Parent
  19264. if (parsedTransformNode.parentId) {
  19265. transformNode._waitingParentId = parsedTransformNode.parentId;
  19266. }
  19267. return transformNode;
  19268. };
  19269. /**
  19270. * Releases resources associated with this transform node.
  19271. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19272. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19273. */
  19274. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19275. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19276. // Animations
  19277. this.getScene().stopAnimation(this);
  19278. // Remove from scene
  19279. this.getScene().removeTransformNode(this);
  19280. this.onAfterWorldMatrixUpdateObservable.clear();
  19281. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19282. };
  19283. // Statics
  19284. TransformNode.BILLBOARDMODE_NONE = 0;
  19285. TransformNode.BILLBOARDMODE_X = 1;
  19286. TransformNode.BILLBOARDMODE_Y = 2;
  19287. TransformNode.BILLBOARDMODE_Z = 4;
  19288. TransformNode.BILLBOARDMODE_ALL = 7;
  19289. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19290. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19291. __decorate([
  19292. BABYLON.serializeAsVector3()
  19293. ], TransformNode.prototype, "_rotation", void 0);
  19294. __decorate([
  19295. BABYLON.serializeAsQuaternion()
  19296. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19297. __decorate([
  19298. BABYLON.serializeAsVector3()
  19299. ], TransformNode.prototype, "_scaling", void 0);
  19300. __decorate([
  19301. BABYLON.serialize()
  19302. ], TransformNode.prototype, "billboardMode", void 0);
  19303. __decorate([
  19304. BABYLON.serialize()
  19305. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19306. __decorate([
  19307. BABYLON.serialize()
  19308. ], TransformNode.prototype, "infiniteDistance", void 0);
  19309. __decorate([
  19310. BABYLON.serializeAsVector3()
  19311. ], TransformNode.prototype, "position", void 0);
  19312. return TransformNode;
  19313. }(BABYLON.Node));
  19314. BABYLON.TransformNode = TransformNode;
  19315. })(BABYLON || (BABYLON = {}));
  19316. //# sourceMappingURL=babylon.transformNode.js.map
  19317. var BABYLON;
  19318. (function (BABYLON) {
  19319. /**
  19320. * Class used to store all common mesh properties
  19321. */
  19322. var AbstractMesh = /** @class */ (function (_super) {
  19323. __extends(AbstractMesh, _super);
  19324. // Constructor
  19325. /**
  19326. * Creates a new AbstractMesh
  19327. * @param name defines the name of the mesh
  19328. * @param scene defines the hosting scene
  19329. */
  19330. function AbstractMesh(name, scene) {
  19331. if (scene === void 0) { scene = null; }
  19332. var _this = _super.call(this, name, scene, false) || this;
  19333. _this._facetNb = 0; // facet number
  19334. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19335. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19336. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19337. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19338. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19339. _this._subDiv = {
  19340. max: 1,
  19341. X: 1,
  19342. Y: 1,
  19343. Z: 1
  19344. };
  19345. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19346. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19347. // Events
  19348. /**
  19349. * An event triggered when this mesh collides with another one
  19350. */
  19351. _this.onCollideObservable = new BABYLON.Observable();
  19352. /**
  19353. * An event triggered when the collision's position changes
  19354. */
  19355. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19356. /**
  19357. * An event triggered when material is changed
  19358. */
  19359. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19360. // Properties
  19361. /**
  19362. * Gets or sets the orientation for POV movement & rotation
  19363. */
  19364. _this.definedFacingForward = true;
  19365. /**
  19366. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19367. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19368. * * 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.
  19369. * @see http://doc.babylonjs.com/features/occlusionquery
  19370. */
  19371. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19372. /**
  19373. * 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:
  19374. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19375. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19376. * * 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.
  19377. * @see http://doc.babylonjs.com/features/occlusionquery
  19378. */
  19379. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19380. /**
  19381. * 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.
  19382. * The default value is -1 which means don't break the query and wait till the result
  19383. * @see http://doc.babylonjs.com/features/occlusionquery
  19384. */
  19385. _this.occlusionRetryCount = -1;
  19386. _this._occlusionInternalRetryCounter = 0;
  19387. _this._isOccluded = false;
  19388. _this._isOcclusionQueryInProgress = false;
  19389. _this._visibility = 1.0;
  19390. /** Gets or sets the alpha index used to sort transparent meshes
  19391. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19392. */
  19393. _this.alphaIndex = Number.MAX_VALUE;
  19394. /**
  19395. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19396. */
  19397. _this.isVisible = true;
  19398. /**
  19399. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19400. */
  19401. _this.isPickable = true;
  19402. /**
  19403. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19404. */
  19405. _this.showBoundingBox = false;
  19406. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19407. _this.showSubMeshesBoundingBox = false;
  19408. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19409. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19410. */
  19411. _this.isBlocker = false;
  19412. /**
  19413. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19414. */
  19415. _this.enablePointerMoveEvents = false;
  19416. /**
  19417. * Specifies the rendering group id for this mesh (0 by default)
  19418. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19419. */
  19420. _this.renderingGroupId = 0;
  19421. _this._receiveShadows = false;
  19422. /**
  19423. * Gets or sets a boolean indicating if the outline must be rendered as well
  19424. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19425. */
  19426. _this.renderOutline = false;
  19427. /** Defines color to use when rendering outline */
  19428. _this.outlineColor = BABYLON.Color3.Red();
  19429. /** Define width to use when rendering outline */
  19430. _this.outlineWidth = 0.02;
  19431. /**
  19432. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19433. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19434. */
  19435. _this.renderOverlay = false;
  19436. /** Defines color to use when rendering overlay */
  19437. _this.overlayColor = BABYLON.Color3.Red();
  19438. /** Defines alpha to use when rendering overlay */
  19439. _this.overlayAlpha = 0.5;
  19440. _this._hasVertexAlpha = false;
  19441. _this._useVertexColors = true;
  19442. _this._computeBonesUsingShaders = true;
  19443. _this._numBoneInfluencers = 4;
  19444. _this._applyFog = true;
  19445. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19446. _this.useOctreeForRenderingSelection = true;
  19447. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19448. _this.useOctreeForPicking = true;
  19449. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19450. _this.useOctreeForCollisions = true;
  19451. _this._layerMask = 0x0FFFFFFF;
  19452. /**
  19453. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19454. */
  19455. _this.alwaysSelectAsActiveMesh = false;
  19456. /**
  19457. * Gets or sets the current action manager
  19458. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19459. */
  19460. _this.actionManager = null;
  19461. /**
  19462. * Gets or sets impostor used for physic simulation
  19463. * @see http://doc.babylonjs.com/features/physics_engine
  19464. */
  19465. _this.physicsImpostor = null;
  19466. // Collisions
  19467. _this._checkCollisions = false;
  19468. _this._collisionMask = -1;
  19469. _this._collisionGroup = -1;
  19470. /**
  19471. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19472. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19473. */
  19474. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19475. /**
  19476. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19477. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19478. */
  19479. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19480. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19481. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19482. // Edges
  19483. /**
  19484. * Defines edge width used when edgesRenderer is enabled
  19485. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19486. */
  19487. _this.edgesWidth = 1;
  19488. /**
  19489. * Defines edge color used when edgesRenderer is enabled
  19490. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19491. */
  19492. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19493. // Cache
  19494. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19495. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19496. /** @hidden */
  19497. _this._renderId = 0;
  19498. /** @hidden */
  19499. _this._intersectionsInProgress = new Array();
  19500. /** @hidden */
  19501. _this._unIndexed = false;
  19502. /** @hidden */
  19503. _this._lightSources = new Array();
  19504. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19505. if (collidedMesh === void 0) { collidedMesh = null; }
  19506. //TODO move this to the collision coordinator!
  19507. if (_this.getScene().workerCollisions)
  19508. newPosition.multiplyInPlace(_this._collider._radius);
  19509. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19510. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19511. _this.position.addInPlace(_this._diffPositionForCollisions);
  19512. }
  19513. if (collidedMesh) {
  19514. _this.onCollideObservable.notifyObservers(collidedMesh);
  19515. }
  19516. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19517. };
  19518. _this.getScene().addMesh(_this);
  19519. _this._resyncLightSources();
  19520. return _this;
  19521. }
  19522. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19523. /**
  19524. * No billboard
  19525. */
  19526. get: function () {
  19527. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19528. },
  19529. enumerable: true,
  19530. configurable: true
  19531. });
  19532. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19533. /** Billboard on X axis */
  19534. get: function () {
  19535. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19536. },
  19537. enumerable: true,
  19538. configurable: true
  19539. });
  19540. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19541. /** Billboard on Y axis */
  19542. get: function () {
  19543. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19544. },
  19545. enumerable: true,
  19546. configurable: true
  19547. });
  19548. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19549. /** Billboard on Z axis */
  19550. get: function () {
  19551. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19552. },
  19553. enumerable: true,
  19554. configurable: true
  19555. });
  19556. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19557. /** Billboard on all axes */
  19558. get: function () {
  19559. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19560. },
  19561. enumerable: true,
  19562. configurable: true
  19563. });
  19564. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19565. /**
  19566. * Gets the number of facets in the mesh
  19567. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19568. */
  19569. get: function () {
  19570. return this._facetNb;
  19571. },
  19572. enumerable: true,
  19573. configurable: true
  19574. });
  19575. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19576. /**
  19577. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19578. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19579. */
  19580. get: function () {
  19581. return this._partitioningSubdivisions;
  19582. },
  19583. set: function (nb) {
  19584. this._partitioningSubdivisions = nb;
  19585. },
  19586. enumerable: true,
  19587. configurable: true
  19588. });
  19589. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19590. /**
  19591. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19592. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19593. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19594. */
  19595. get: function () {
  19596. return this._partitioningBBoxRatio;
  19597. },
  19598. set: function (ratio) {
  19599. this._partitioningBBoxRatio = ratio;
  19600. },
  19601. enumerable: true,
  19602. configurable: true
  19603. });
  19604. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19605. /**
  19606. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19607. * Works only for updatable meshes.
  19608. * Doesn't work with multi-materials
  19609. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19610. */
  19611. get: function () {
  19612. return this._facetDepthSort;
  19613. },
  19614. set: function (sort) {
  19615. this._facetDepthSort = sort;
  19616. },
  19617. enumerable: true,
  19618. configurable: true
  19619. });
  19620. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19621. /**
  19622. * The location (Vector3) where the facet depth sort must be computed from.
  19623. * By default, the active camera position.
  19624. * Used only when facet depth sort is enabled
  19625. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19626. */
  19627. get: function () {
  19628. return this._facetDepthSortFrom;
  19629. },
  19630. set: function (location) {
  19631. this._facetDepthSortFrom = location;
  19632. },
  19633. enumerable: true,
  19634. configurable: true
  19635. });
  19636. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19637. /**
  19638. * gets a boolean indicating if facetData is enabled
  19639. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19640. */
  19641. get: function () {
  19642. return this._facetDataEnabled;
  19643. },
  19644. enumerable: true,
  19645. configurable: true
  19646. });
  19647. /** @hidden */
  19648. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19649. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19650. return false;
  19651. }
  19652. this._markSubMeshesAsMiscDirty();
  19653. return true;
  19654. };
  19655. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19656. /** Set a function to call when this mesh collides with another one */
  19657. set: function (callback) {
  19658. if (this._onCollideObserver) {
  19659. this.onCollideObservable.remove(this._onCollideObserver);
  19660. }
  19661. this._onCollideObserver = this.onCollideObservable.add(callback);
  19662. },
  19663. enumerable: true,
  19664. configurable: true
  19665. });
  19666. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19667. /** Set a function to call when the collision's position changes */
  19668. set: function (callback) {
  19669. if (this._onCollisionPositionChangeObserver) {
  19670. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19671. }
  19672. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19673. },
  19674. enumerable: true,
  19675. configurable: true
  19676. });
  19677. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19678. /**
  19679. * 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
  19680. * @see http://doc.babylonjs.com/features/occlusionquery
  19681. */
  19682. get: function () {
  19683. return this._isOccluded;
  19684. },
  19685. set: function (value) {
  19686. this._isOccluded = value;
  19687. },
  19688. enumerable: true,
  19689. configurable: true
  19690. });
  19691. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19692. /**
  19693. * Flag to check the progress status of the query
  19694. * @see http://doc.babylonjs.com/features/occlusionquery
  19695. */
  19696. get: function () {
  19697. return this._isOcclusionQueryInProgress;
  19698. },
  19699. enumerable: true,
  19700. configurable: true
  19701. });
  19702. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19703. /**
  19704. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19705. */
  19706. get: function () {
  19707. return this._visibility;
  19708. },
  19709. /**
  19710. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19711. */
  19712. set: function (value) {
  19713. if (this._visibility === value) {
  19714. return;
  19715. }
  19716. this._visibility = value;
  19717. this._markSubMeshesAsMiscDirty();
  19718. },
  19719. enumerable: true,
  19720. configurable: true
  19721. });
  19722. Object.defineProperty(AbstractMesh.prototype, "material", {
  19723. /** Gets or sets current material */
  19724. get: function () {
  19725. return this._material;
  19726. },
  19727. set: function (value) {
  19728. if (this._material === value) {
  19729. return;
  19730. }
  19731. this._material = value;
  19732. if (this.onMaterialChangedObservable.hasObservers) {
  19733. this.onMaterialChangedObservable.notifyObservers(this);
  19734. }
  19735. if (!this.subMeshes) {
  19736. return;
  19737. }
  19738. this._unBindEffect();
  19739. },
  19740. enumerable: true,
  19741. configurable: true
  19742. });
  19743. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19744. /**
  19745. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19746. * @see http://doc.babylonjs.com/babylon101/shadows
  19747. */
  19748. get: function () {
  19749. return this._receiveShadows;
  19750. },
  19751. set: function (value) {
  19752. if (this._receiveShadows === value) {
  19753. return;
  19754. }
  19755. this._receiveShadows = value;
  19756. this._markSubMeshesAsLightDirty();
  19757. },
  19758. enumerable: true,
  19759. configurable: true
  19760. });
  19761. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19762. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19763. get: function () {
  19764. return this._hasVertexAlpha;
  19765. },
  19766. set: function (value) {
  19767. if (this._hasVertexAlpha === value) {
  19768. return;
  19769. }
  19770. this._hasVertexAlpha = value;
  19771. this._markSubMeshesAsAttributesDirty();
  19772. this._markSubMeshesAsMiscDirty();
  19773. },
  19774. enumerable: true,
  19775. configurable: true
  19776. });
  19777. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19778. /** 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) */
  19779. get: function () {
  19780. return this._useVertexColors;
  19781. },
  19782. set: function (value) {
  19783. if (this._useVertexColors === value) {
  19784. return;
  19785. }
  19786. this._useVertexColors = value;
  19787. this._markSubMeshesAsAttributesDirty();
  19788. },
  19789. enumerable: true,
  19790. configurable: true
  19791. });
  19792. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19793. /**
  19794. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19795. */
  19796. get: function () {
  19797. return this._computeBonesUsingShaders;
  19798. },
  19799. set: function (value) {
  19800. if (this._computeBonesUsingShaders === value) {
  19801. return;
  19802. }
  19803. this._computeBonesUsingShaders = value;
  19804. this._markSubMeshesAsAttributesDirty();
  19805. },
  19806. enumerable: true,
  19807. configurable: true
  19808. });
  19809. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19810. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19811. get: function () {
  19812. return this._numBoneInfluencers;
  19813. },
  19814. set: function (value) {
  19815. if (this._numBoneInfluencers === value) {
  19816. return;
  19817. }
  19818. this._numBoneInfluencers = value;
  19819. this._markSubMeshesAsAttributesDirty();
  19820. },
  19821. enumerable: true,
  19822. configurable: true
  19823. });
  19824. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19825. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19826. get: function () {
  19827. return this._applyFog;
  19828. },
  19829. set: function (value) {
  19830. if (this._applyFog === value) {
  19831. return;
  19832. }
  19833. this._applyFog = value;
  19834. this._markSubMeshesAsMiscDirty();
  19835. },
  19836. enumerable: true,
  19837. configurable: true
  19838. });
  19839. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19840. /**
  19841. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19842. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19843. */
  19844. get: function () {
  19845. return this._layerMask;
  19846. },
  19847. set: function (value) {
  19848. if (value === this._layerMask) {
  19849. return;
  19850. }
  19851. this._layerMask = value;
  19852. this._resyncLightSources();
  19853. },
  19854. enumerable: true,
  19855. configurable: true
  19856. });
  19857. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19858. /**
  19859. * Gets or sets a collision mask used to mask collisions (default is -1).
  19860. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19861. */
  19862. get: function () {
  19863. return this._collisionMask;
  19864. },
  19865. set: function (mask) {
  19866. this._collisionMask = !isNaN(mask) ? mask : -1;
  19867. },
  19868. enumerable: true,
  19869. configurable: true
  19870. });
  19871. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19872. /**
  19873. * Gets or sets the current collision group mask (-1 by default).
  19874. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19875. */
  19876. get: function () {
  19877. return this._collisionGroup;
  19878. },
  19879. set: function (mask) {
  19880. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19881. },
  19882. enumerable: true,
  19883. configurable: true
  19884. });
  19885. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19886. /** @hidden */
  19887. get: function () {
  19888. return null;
  19889. },
  19890. enumerable: true,
  19891. configurable: true
  19892. });
  19893. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19894. get: function () {
  19895. return this._skeleton;
  19896. },
  19897. /**
  19898. * Gets or sets a skeleton to apply skining transformations
  19899. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19900. */
  19901. set: function (value) {
  19902. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19903. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19904. }
  19905. if (value && value.needInitialSkinMatrix) {
  19906. value._registerMeshWithPoseMatrix(this);
  19907. }
  19908. this._skeleton = value;
  19909. if (!this._skeleton) {
  19910. this._bonesTransformMatrices = null;
  19911. }
  19912. this._markSubMeshesAsAttributesDirty();
  19913. },
  19914. enumerable: true,
  19915. configurable: true
  19916. });
  19917. /**
  19918. * Returns the string "AbstractMesh"
  19919. * @returns "AbstractMesh"
  19920. */
  19921. AbstractMesh.prototype.getClassName = function () {
  19922. return "AbstractMesh";
  19923. };
  19924. /**
  19925. * Gets a string representation of the current mesh
  19926. * @param fullDetails defines a boolean indicating if full details must be included
  19927. * @returns a string representation of the current mesh
  19928. */
  19929. AbstractMesh.prototype.toString = function (fullDetails) {
  19930. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19931. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19932. if (this._skeleton) {
  19933. ret += ", skeleton: " + this._skeleton.name;
  19934. }
  19935. if (fullDetails) {
  19936. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19937. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19938. }
  19939. return ret;
  19940. };
  19941. /** @hidden */
  19942. AbstractMesh.prototype._rebuild = function () {
  19943. if (this._occlusionQuery) {
  19944. this._occlusionQuery = null;
  19945. }
  19946. if (this._edgesRenderer) {
  19947. this._edgesRenderer._rebuild();
  19948. }
  19949. if (!this.subMeshes) {
  19950. return;
  19951. }
  19952. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19953. var subMesh = _a[_i];
  19954. subMesh._rebuild();
  19955. }
  19956. };
  19957. /** @hidden */
  19958. AbstractMesh.prototype._resyncLightSources = function () {
  19959. this._lightSources.length = 0;
  19960. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19961. var light = _a[_i];
  19962. if (!light.isEnabled()) {
  19963. continue;
  19964. }
  19965. if (light.canAffectMesh(this)) {
  19966. this._lightSources.push(light);
  19967. }
  19968. }
  19969. this._markSubMeshesAsLightDirty();
  19970. };
  19971. /** @hidden */
  19972. AbstractMesh.prototype._resyncLighSource = function (light) {
  19973. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19974. var index = this._lightSources.indexOf(light);
  19975. if (index === -1) {
  19976. if (!isIn) {
  19977. return;
  19978. }
  19979. this._lightSources.push(light);
  19980. }
  19981. else {
  19982. if (isIn) {
  19983. return;
  19984. }
  19985. this._lightSources.splice(index, 1);
  19986. }
  19987. this._markSubMeshesAsLightDirty();
  19988. };
  19989. /** @hidden */
  19990. AbstractMesh.prototype._unBindEffect = function () {
  19991. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19992. var subMesh = _a[_i];
  19993. subMesh.setEffect(null);
  19994. }
  19995. };
  19996. /** @hidden */
  19997. AbstractMesh.prototype._removeLightSource = function (light) {
  19998. var index = this._lightSources.indexOf(light);
  19999. if (index === -1) {
  20000. return;
  20001. }
  20002. this._lightSources.splice(index, 1);
  20003. this._markSubMeshesAsLightDirty();
  20004. };
  20005. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20006. if (!this.subMeshes) {
  20007. return;
  20008. }
  20009. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20010. var subMesh = _a[_i];
  20011. if (subMesh._materialDefines) {
  20012. func(subMesh._materialDefines);
  20013. }
  20014. }
  20015. };
  20016. /** @hidden */
  20017. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20018. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20019. };
  20020. /** @hidden */
  20021. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20022. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20023. };
  20024. /** @hidden */
  20025. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20026. if (!this.subMeshes) {
  20027. return;
  20028. }
  20029. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20030. var subMesh = _a[_i];
  20031. var material = subMesh.getMaterial();
  20032. if (material) {
  20033. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20034. }
  20035. }
  20036. };
  20037. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20038. /**
  20039. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20040. */
  20041. get: function () {
  20042. return this._scaling;
  20043. },
  20044. set: function (newScaling) {
  20045. this._scaling = newScaling;
  20046. if (this.physicsImpostor) {
  20047. this.physicsImpostor.forceUpdate();
  20048. }
  20049. },
  20050. enumerable: true,
  20051. configurable: true
  20052. });
  20053. // Methods
  20054. /**
  20055. * Disables the mesh edge rendering mode
  20056. * @returns the currentAbstractMesh
  20057. */
  20058. AbstractMesh.prototype.disableEdgesRendering = function () {
  20059. if (this._edgesRenderer) {
  20060. this._edgesRenderer.dispose();
  20061. this._edgesRenderer = null;
  20062. }
  20063. return this;
  20064. };
  20065. /**
  20066. * Enables the edge rendering mode on the mesh.
  20067. * This mode makes the mesh edges visible
  20068. * @param epsilon defines the maximal distance between two angles to detect a face
  20069. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20070. * @returns the currentAbstractMesh
  20071. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20072. */
  20073. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20074. if (epsilon === void 0) { epsilon = 0.95; }
  20075. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20076. this.disableEdgesRendering();
  20077. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20078. return this;
  20079. };
  20080. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20081. /**
  20082. * Returns true if the mesh is blocked. Implemented by child classes
  20083. */
  20084. get: function () {
  20085. return false;
  20086. },
  20087. enumerable: true,
  20088. configurable: true
  20089. });
  20090. /**
  20091. * Returns the mesh itself by default. Implemented by child classes
  20092. * @param camera defines the camera to use to pick the right LOD level
  20093. * @returns the currentAbstractMesh
  20094. */
  20095. AbstractMesh.prototype.getLOD = function (camera) {
  20096. return this;
  20097. };
  20098. /**
  20099. * Returns 0 by default. Implemented by child classes
  20100. * @returns an integer
  20101. */
  20102. AbstractMesh.prototype.getTotalVertices = function () {
  20103. return 0;
  20104. };
  20105. /**
  20106. * Returns null by default. Implemented by child classes
  20107. * @returns null
  20108. */
  20109. AbstractMesh.prototype.getIndices = function () {
  20110. return null;
  20111. };
  20112. /**
  20113. * Returns the array of the requested vertex data kind. Implemented by child classes
  20114. * @param kind defines the vertex data kind to use
  20115. * @returns null
  20116. */
  20117. AbstractMesh.prototype.getVerticesData = function (kind) {
  20118. return null;
  20119. };
  20120. /**
  20121. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20122. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20123. * Note that a new underlying VertexBuffer object is created each call.
  20124. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20125. * @param kind defines vertex data kind:
  20126. * * BABYLON.VertexBuffer.PositionKind
  20127. * * BABYLON.VertexBuffer.UVKind
  20128. * * BABYLON.VertexBuffer.UV2Kind
  20129. * * BABYLON.VertexBuffer.UV3Kind
  20130. * * BABYLON.VertexBuffer.UV4Kind
  20131. * * BABYLON.VertexBuffer.UV5Kind
  20132. * * BABYLON.VertexBuffer.UV6Kind
  20133. * * BABYLON.VertexBuffer.ColorKind
  20134. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20135. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20136. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20137. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20138. * @param data defines the data source
  20139. * @param updatable defines if the data must be flagged as updatable (or static)
  20140. * @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
  20141. * @returns the current mesh
  20142. */
  20143. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20144. return this;
  20145. };
  20146. /**
  20147. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20148. * If the mesh has no geometry, it is simply returned as it is.
  20149. * @param kind defines vertex data kind:
  20150. * * BABYLON.VertexBuffer.PositionKind
  20151. * * BABYLON.VertexBuffer.UVKind
  20152. * * BABYLON.VertexBuffer.UV2Kind
  20153. * * BABYLON.VertexBuffer.UV3Kind
  20154. * * BABYLON.VertexBuffer.UV4Kind
  20155. * * BABYLON.VertexBuffer.UV5Kind
  20156. * * BABYLON.VertexBuffer.UV6Kind
  20157. * * BABYLON.VertexBuffer.ColorKind
  20158. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20159. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20160. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20161. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20162. * @param data defines the data source
  20163. * @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
  20164. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20165. * @returns the current mesh
  20166. */
  20167. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20168. return this;
  20169. };
  20170. /**
  20171. * Sets the mesh indices,
  20172. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20173. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20174. * @param totalVertices Defines the total number of vertices
  20175. * @returns the current mesh
  20176. */
  20177. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20178. return this;
  20179. };
  20180. /**
  20181. * Gets a boolean indicating if specific vertex data is present
  20182. * @param kind defines the vertex data kind to use
  20183. * @returns true is data kind is present
  20184. */
  20185. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20186. return false;
  20187. };
  20188. /**
  20189. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20190. * @returns a BoundingInfo
  20191. */
  20192. AbstractMesh.prototype.getBoundingInfo = function () {
  20193. if (this._masterMesh) {
  20194. return this._masterMesh.getBoundingInfo();
  20195. }
  20196. if (!this._boundingInfo) {
  20197. // this._boundingInfo is being created here
  20198. this._updateBoundingInfo();
  20199. }
  20200. // cannot be null.
  20201. return this._boundingInfo;
  20202. };
  20203. /**
  20204. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20205. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20206. * @returns the current mesh
  20207. */
  20208. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20209. if (includeDescendants === void 0) { includeDescendants = true; }
  20210. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20211. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20212. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20213. if (maxDimension === 0) {
  20214. return this;
  20215. }
  20216. var scale = 1 / maxDimension;
  20217. this.scaling.scaleInPlace(scale);
  20218. return this;
  20219. };
  20220. /**
  20221. * Overwrite the current bounding info
  20222. * @param boundingInfo defines the new bounding info
  20223. * @returns the current mesh
  20224. */
  20225. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20226. this._boundingInfo = boundingInfo;
  20227. return this;
  20228. };
  20229. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20230. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20231. get: function () {
  20232. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20233. },
  20234. enumerable: true,
  20235. configurable: true
  20236. });
  20237. /** @hidden */
  20238. AbstractMesh.prototype._preActivate = function () {
  20239. };
  20240. /** @hidden */
  20241. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20242. };
  20243. /** @hidden */
  20244. AbstractMesh.prototype._activate = function (renderId) {
  20245. this._renderId = renderId;
  20246. };
  20247. /**
  20248. * Gets the current world matrix
  20249. * @returns a Matrix
  20250. */
  20251. AbstractMesh.prototype.getWorldMatrix = function () {
  20252. if (this._masterMesh) {
  20253. return this._masterMesh.getWorldMatrix();
  20254. }
  20255. return _super.prototype.getWorldMatrix.call(this);
  20256. };
  20257. /** @hidden */
  20258. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20259. if (this._masterMesh) {
  20260. return this._masterMesh._getWorldMatrixDeterminant();
  20261. }
  20262. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20263. };
  20264. // ================================== Point of View Movement =================================
  20265. /**
  20266. * Perform relative position change from the point of view of behind the front of the mesh.
  20267. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20268. * Supports definition of mesh facing forward or backward
  20269. * @param amountRight defines the distance on the right axis
  20270. * @param amountUp defines the distance on the up axis
  20271. * @param amountForward defines the distance on the forward axis
  20272. * @returns the current mesh
  20273. */
  20274. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20275. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20276. return this;
  20277. };
  20278. /**
  20279. * Calculate relative position change from the point of view of behind the front of the mesh.
  20280. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20281. * Supports definition of mesh facing forward or backward
  20282. * @param amountRight defines the distance on the right axis
  20283. * @param amountUp defines the distance on the up axis
  20284. * @param amountForward defines the distance on the forward axis
  20285. * @returns the new displacement vector
  20286. */
  20287. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20288. var rotMatrix = new BABYLON.Matrix();
  20289. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20290. rotQuaternion.toRotationMatrix(rotMatrix);
  20291. var translationDelta = BABYLON.Vector3.Zero();
  20292. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20293. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20294. return translationDelta;
  20295. };
  20296. // ================================== Point of View Rotation =================================
  20297. /**
  20298. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20299. * Supports definition of mesh facing forward or backward
  20300. * @param flipBack defines the flip
  20301. * @param twirlClockwise defines the twirl
  20302. * @param tiltRight defines the tilt
  20303. * @returns the current mesh
  20304. */
  20305. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20306. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20307. return this;
  20308. };
  20309. /**
  20310. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20311. * Supports definition of mesh facing forward or backward.
  20312. * @param flipBack defines the flip
  20313. * @param twirlClockwise defines the twirl
  20314. * @param tiltRight defines the tilt
  20315. * @returns the new rotation vector
  20316. */
  20317. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20318. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20319. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20320. };
  20321. /**
  20322. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20323. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20324. * @returns the new bounding vectors
  20325. */
  20326. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  20327. if (includeDescendants === void 0) { includeDescendants = true; }
  20328. this.computeWorldMatrix(true);
  20329. var min;
  20330. var max;
  20331. var boundingInfo = this.getBoundingInfo();
  20332. if (!this.subMeshes) {
  20333. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20334. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20335. }
  20336. else {
  20337. min = boundingInfo.boundingBox.minimumWorld;
  20338. max = boundingInfo.boundingBox.maximumWorld;
  20339. }
  20340. if (includeDescendants) {
  20341. var descendants = this.getDescendants(false);
  20342. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20343. var descendant = descendants_1[_i];
  20344. var childMesh = descendant;
  20345. childMesh.computeWorldMatrix(true);
  20346. //make sure we have the needed params to get mix and max
  20347. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20348. continue;
  20349. }
  20350. var childBoundingInfo = childMesh.getBoundingInfo();
  20351. var boundingBox = childBoundingInfo.boundingBox;
  20352. var minBox = boundingBox.minimumWorld;
  20353. var maxBox = boundingBox.maximumWorld;
  20354. BABYLON.Tools.CheckExtends(minBox, min, max);
  20355. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20356. }
  20357. }
  20358. return {
  20359. min: min,
  20360. max: max
  20361. };
  20362. };
  20363. /** @hidden */
  20364. AbstractMesh.prototype._updateBoundingInfo = function () {
  20365. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20366. this._boundingInfo.update(this.worldMatrixFromCache);
  20367. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20368. return this;
  20369. };
  20370. /** @hidden */
  20371. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20372. if (!this.subMeshes) {
  20373. return this;
  20374. }
  20375. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20376. var subMesh = this.subMeshes[subIndex];
  20377. if (!subMesh.IsGlobal) {
  20378. subMesh.updateBoundingInfo(matrix);
  20379. }
  20380. }
  20381. return this;
  20382. };
  20383. /** @hidden */
  20384. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20385. // Bounding info
  20386. this._updateBoundingInfo();
  20387. };
  20388. /**
  20389. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20390. * A mesh is in the frustum if its bounding box intersects the frustum
  20391. * @param frustumPlanes defines the frustum to test
  20392. * @returns true if the mesh is in the frustum planes
  20393. */
  20394. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20395. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20396. };
  20397. /**
  20398. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20399. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20400. * @param frustumPlanes defines the frustum to test
  20401. * @returns true if the mesh is completely in the frustum planes
  20402. */
  20403. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20404. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20405. ;
  20406. };
  20407. /**
  20408. * True if the mesh intersects another mesh or a SolidParticle object
  20409. * @param mesh defines a target mesh or SolidParticle to test
  20410. * @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)
  20411. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20412. * @returns true if there is an intersection
  20413. */
  20414. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20415. if (precise === void 0) { precise = false; }
  20416. if (!this._boundingInfo || !mesh._boundingInfo) {
  20417. return false;
  20418. }
  20419. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20420. return true;
  20421. }
  20422. if (includeDescendants) {
  20423. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20424. var child = _a[_i];
  20425. if (child.intersectsMesh(mesh, precise, true)) {
  20426. return true;
  20427. }
  20428. }
  20429. }
  20430. return false;
  20431. };
  20432. /**
  20433. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20434. * @param point defines the point to test
  20435. * @returns true if there is an intersection
  20436. */
  20437. AbstractMesh.prototype.intersectsPoint = function (point) {
  20438. if (!this._boundingInfo) {
  20439. return false;
  20440. }
  20441. return this._boundingInfo.intersectsPoint(point);
  20442. };
  20443. /**
  20444. * Gets the current physics impostor
  20445. * @see http://doc.babylonjs.com/features/physics_engine
  20446. * @returns a physics impostor or null
  20447. */
  20448. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20449. return this.physicsImpostor;
  20450. };
  20451. /**
  20452. * Gets the position of the current mesh in camera space
  20453. * @param camera defines the camera to use
  20454. * @returns a position
  20455. */
  20456. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20457. if (camera === void 0) { camera = null; }
  20458. if (!camera) {
  20459. camera = this.getScene().activeCamera;
  20460. }
  20461. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20462. };
  20463. /**
  20464. * Returns the distance from the mesh to the active camera
  20465. * @param camera defines the camera to use
  20466. * @returns the distance
  20467. */
  20468. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20469. if (camera === void 0) { camera = null; }
  20470. if (!camera) {
  20471. camera = this.getScene().activeCamera;
  20472. }
  20473. return this.absolutePosition.subtract(camera.position).length();
  20474. };
  20475. /**
  20476. * Apply a physic impulse to the mesh
  20477. * @param force defines the force to apply
  20478. * @param contactPoint defines where to apply the force
  20479. * @returns the current mesh
  20480. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20481. */
  20482. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20483. if (!this.physicsImpostor) {
  20484. return this;
  20485. }
  20486. this.physicsImpostor.applyImpulse(force, contactPoint);
  20487. return this;
  20488. };
  20489. /**
  20490. * Creates a physic joint between two meshes
  20491. * @param otherMesh defines the other mesh to use
  20492. * @param pivot1 defines the pivot to use on this mesh
  20493. * @param pivot2 defines the pivot to use on the other mesh
  20494. * @param options defines additional options (can be plugin dependent)
  20495. * @returns the current mesh
  20496. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20497. */
  20498. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20499. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20500. return this;
  20501. }
  20502. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20503. mainPivot: pivot1,
  20504. connectedPivot: pivot2,
  20505. nativeParams: options
  20506. });
  20507. return this;
  20508. };
  20509. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20510. // Collisions
  20511. /**
  20512. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20513. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20514. */
  20515. get: function () {
  20516. return this._checkCollisions;
  20517. },
  20518. set: function (collisionEnabled) {
  20519. this._checkCollisions = collisionEnabled;
  20520. if (this.getScene().workerCollisions) {
  20521. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20522. }
  20523. },
  20524. enumerable: true,
  20525. configurable: true
  20526. });
  20527. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20528. /**
  20529. * Gets Collider object used to compute collisions (not physics)
  20530. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20531. */
  20532. get: function () {
  20533. return this._collider;
  20534. },
  20535. enumerable: true,
  20536. configurable: true
  20537. });
  20538. /**
  20539. * Move the mesh using collision engine
  20540. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20541. * @param displacement defines the requested displacement vector
  20542. * @returns the current mesh
  20543. */
  20544. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20545. var globalPosition = this.getAbsolutePosition();
  20546. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20547. if (!this._collider) {
  20548. this._collider = new BABYLON.Collider();
  20549. }
  20550. this._collider._radius = this.ellipsoid;
  20551. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20552. return this;
  20553. };
  20554. // Submeshes octree
  20555. /**
  20556. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20557. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20558. * @param maxCapacity defines the maximum size of each block (64 by default)
  20559. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20560. * @returns the new octree
  20561. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20562. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20563. */
  20564. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20565. if (maxCapacity === void 0) { maxCapacity = 64; }
  20566. if (maxDepth === void 0) { maxDepth = 2; }
  20567. if (!this._submeshesOctree) {
  20568. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20569. }
  20570. this.computeWorldMatrix(true);
  20571. var boundingInfo = this.getBoundingInfo();
  20572. // Update octree
  20573. var bbox = boundingInfo.boundingBox;
  20574. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20575. return this._submeshesOctree;
  20576. };
  20577. // Collisions
  20578. /** @hidden */
  20579. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20580. this._generatePointsArray();
  20581. if (!this._positions) {
  20582. return this;
  20583. }
  20584. // Transformation
  20585. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20586. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20587. subMesh._lastColliderWorldVertices = [];
  20588. subMesh._trianglePlanes = [];
  20589. var start = subMesh.verticesStart;
  20590. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20591. for (var i = start; i < end; i++) {
  20592. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20593. }
  20594. }
  20595. // Collide
  20596. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20597. if (collider.collisionFound) {
  20598. collider.collidedMesh = this;
  20599. }
  20600. return this;
  20601. };
  20602. /** @hidden */
  20603. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20604. var subMeshes;
  20605. var len;
  20606. // Octrees
  20607. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20608. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20609. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20610. len = intersections.length;
  20611. subMeshes = intersections.data;
  20612. }
  20613. else {
  20614. subMeshes = this.subMeshes;
  20615. len = subMeshes.length;
  20616. }
  20617. for (var index = 0; index < len; index++) {
  20618. var subMesh = subMeshes[index];
  20619. // Bounding test
  20620. if (len > 1 && !subMesh._checkCollision(collider))
  20621. continue;
  20622. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20623. }
  20624. return this;
  20625. };
  20626. /** @hidden */
  20627. AbstractMesh.prototype._checkCollision = function (collider) {
  20628. // Bounding box test
  20629. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20630. return this;
  20631. // Transformation matrix
  20632. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20633. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20634. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20635. return this;
  20636. };
  20637. // Picking
  20638. /** @hidden */
  20639. AbstractMesh.prototype._generatePointsArray = function () {
  20640. return false;
  20641. };
  20642. /**
  20643. * Checks if the passed Ray intersects with the mesh
  20644. * @param ray defines the ray to use
  20645. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20646. * @returns the picking info
  20647. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20648. */
  20649. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20650. var pickingInfo = new BABYLON.PickingInfo();
  20651. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20652. return pickingInfo;
  20653. }
  20654. if (!this._generatePointsArray()) {
  20655. return pickingInfo;
  20656. }
  20657. var intersectInfo = null;
  20658. // Octrees
  20659. var subMeshes;
  20660. var len;
  20661. if (this._submeshesOctree && this.useOctreeForPicking) {
  20662. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20663. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20664. len = intersections.length;
  20665. subMeshes = intersections.data;
  20666. }
  20667. else {
  20668. subMeshes = this.subMeshes;
  20669. len = subMeshes.length;
  20670. }
  20671. for (var index = 0; index < len; index++) {
  20672. var subMesh = subMeshes[index];
  20673. // Bounding test
  20674. if (len > 1 && !subMesh.canIntersects(ray))
  20675. continue;
  20676. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20677. if (currentIntersectInfo) {
  20678. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20679. intersectInfo = currentIntersectInfo;
  20680. intersectInfo.subMeshId = index;
  20681. if (fastCheck) {
  20682. break;
  20683. }
  20684. }
  20685. }
  20686. }
  20687. if (intersectInfo) {
  20688. // Get picked point
  20689. var world = this.getWorldMatrix();
  20690. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20691. var direction = ray.direction.clone();
  20692. direction = direction.scale(intersectInfo.distance);
  20693. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20694. var pickedPoint = worldOrigin.add(worldDirection);
  20695. // Return result
  20696. pickingInfo.hit = true;
  20697. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20698. pickingInfo.pickedPoint = pickedPoint;
  20699. pickingInfo.pickedMesh = this;
  20700. pickingInfo.bu = intersectInfo.bu || 0;
  20701. pickingInfo.bv = intersectInfo.bv || 0;
  20702. pickingInfo.faceId = intersectInfo.faceId;
  20703. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20704. return pickingInfo;
  20705. }
  20706. return pickingInfo;
  20707. };
  20708. /**
  20709. * Clones the current mesh
  20710. * @param name defines the mesh name
  20711. * @param newParent defines the new mesh parent
  20712. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20713. * @returns the new mesh
  20714. */
  20715. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20716. return null;
  20717. };
  20718. /**
  20719. * Disposes all the submeshes of the current meshnp
  20720. * @returns the current mesh
  20721. */
  20722. AbstractMesh.prototype.releaseSubMeshes = function () {
  20723. if (this.subMeshes) {
  20724. while (this.subMeshes.length) {
  20725. this.subMeshes[0].dispose();
  20726. }
  20727. }
  20728. else {
  20729. this.subMeshes = new Array();
  20730. }
  20731. return this;
  20732. };
  20733. /**
  20734. * Releases resources associated with this abstract mesh.
  20735. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20736. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20737. */
  20738. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20739. var _this = this;
  20740. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20741. var index;
  20742. // Smart Array Retainers.
  20743. this.getScene().freeActiveMeshes();
  20744. this.getScene().freeRenderingGroups();
  20745. // Action manager
  20746. if (this.actionManager !== undefined && this.actionManager !== null) {
  20747. this.actionManager.dispose();
  20748. this.actionManager = null;
  20749. }
  20750. // Skeleton
  20751. this._skeleton = null;
  20752. // Physics
  20753. if (this.physicsImpostor) {
  20754. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20755. }
  20756. // Intersections in progress
  20757. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20758. var other = this._intersectionsInProgress[index];
  20759. var pos = other._intersectionsInProgress.indexOf(this);
  20760. other._intersectionsInProgress.splice(pos, 1);
  20761. }
  20762. this._intersectionsInProgress = [];
  20763. // Lights
  20764. var lights = this.getScene().lights;
  20765. lights.forEach(function (light) {
  20766. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20767. if (meshIndex !== -1) {
  20768. light.includedOnlyMeshes.splice(meshIndex, 1);
  20769. }
  20770. meshIndex = light.excludedMeshes.indexOf(_this);
  20771. if (meshIndex !== -1) {
  20772. light.excludedMeshes.splice(meshIndex, 1);
  20773. }
  20774. // Shadow generators
  20775. var generator = light.getShadowGenerator();
  20776. if (generator) {
  20777. var shadowMap = generator.getShadowMap();
  20778. if (shadowMap && shadowMap.renderList) {
  20779. meshIndex = shadowMap.renderList.indexOf(_this);
  20780. if (meshIndex !== -1) {
  20781. shadowMap.renderList.splice(meshIndex, 1);
  20782. }
  20783. }
  20784. }
  20785. });
  20786. // Edges
  20787. if (this._edgesRenderer) {
  20788. this._edgesRenderer.dispose();
  20789. this._edgesRenderer = null;
  20790. }
  20791. // SubMeshes
  20792. if (this.getClassName() !== "InstancedMesh") {
  20793. this.releaseSubMeshes();
  20794. }
  20795. // Octree
  20796. var sceneOctree = this.getScene().selectionOctree;
  20797. if (sceneOctree !== undefined && sceneOctree !== null) {
  20798. var index = sceneOctree.dynamicContent.indexOf(this);
  20799. if (index !== -1) {
  20800. sceneOctree.dynamicContent.splice(index, 1);
  20801. }
  20802. }
  20803. // Query
  20804. var engine = this.getScene().getEngine();
  20805. if (this._occlusionQuery) {
  20806. this._isOcclusionQueryInProgress = false;
  20807. engine.deleteQuery(this._occlusionQuery);
  20808. this._occlusionQuery = null;
  20809. }
  20810. // Engine
  20811. engine.wipeCaches();
  20812. // Remove from scene
  20813. this.getScene().removeMesh(this);
  20814. if (disposeMaterialAndTextures) {
  20815. if (this.material) {
  20816. this.material.dispose(false, true);
  20817. }
  20818. }
  20819. if (!doNotRecurse) {
  20820. // Particles
  20821. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20822. if (this.getScene().particleSystems[index].emitter === this) {
  20823. this.getScene().particleSystems[index].dispose();
  20824. index--;
  20825. }
  20826. }
  20827. }
  20828. // facet data
  20829. if (this._facetDataEnabled) {
  20830. this.disableFacetData();
  20831. }
  20832. this.onAfterWorldMatrixUpdateObservable.clear();
  20833. this.onCollideObservable.clear();
  20834. this.onCollisionPositionChangeObservable.clear();
  20835. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20836. };
  20837. /**
  20838. * Adds the passed mesh as a child to the current mesh
  20839. * @param mesh defines the child mesh
  20840. * @returns the current mesh
  20841. */
  20842. AbstractMesh.prototype.addChild = function (mesh) {
  20843. mesh.setParent(this);
  20844. return this;
  20845. };
  20846. /**
  20847. * Removes the passed mesh from the current mesh children list
  20848. * @param mesh defines the child mesh
  20849. * @returns the current mesh
  20850. */
  20851. AbstractMesh.prototype.removeChild = function (mesh) {
  20852. mesh.setParent(null);
  20853. return this;
  20854. };
  20855. // Facet data
  20856. /** @hidden */
  20857. AbstractMesh.prototype._initFacetData = function () {
  20858. if (!this._facetNormals) {
  20859. this._facetNormals = new Array();
  20860. }
  20861. if (!this._facetPositions) {
  20862. this._facetPositions = new Array();
  20863. }
  20864. if (!this._facetPartitioning) {
  20865. this._facetPartitioning = new Array();
  20866. }
  20867. this._facetNb = (this.getIndices().length / 3) | 0;
  20868. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20869. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20870. for (var f = 0; f < this._facetNb; f++) {
  20871. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20872. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20873. }
  20874. this._facetDataEnabled = true;
  20875. return this;
  20876. };
  20877. /**
  20878. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20879. * This method can be called within the render loop.
  20880. * 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
  20881. * @returns the current mesh
  20882. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20883. */
  20884. AbstractMesh.prototype.updateFacetData = function () {
  20885. if (!this._facetDataEnabled) {
  20886. this._initFacetData();
  20887. }
  20888. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20889. var indices = this.getIndices();
  20890. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20891. var bInfo = this.getBoundingInfo();
  20892. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20893. // init arrays, matrix and sort function on first call
  20894. this._facetDepthSortEnabled = true;
  20895. if (indices instanceof Uint16Array) {
  20896. this._depthSortedIndices = new Uint16Array(indices);
  20897. }
  20898. else if (indices instanceof Uint32Array) {
  20899. this._depthSortedIndices = new Uint32Array(indices);
  20900. }
  20901. else {
  20902. var needs32bits = false;
  20903. for (var i = 0; i < indices.length; i++) {
  20904. if (indices[i] > 65535) {
  20905. needs32bits = true;
  20906. break;
  20907. }
  20908. }
  20909. if (needs32bits) {
  20910. this._depthSortedIndices = new Uint32Array(indices);
  20911. }
  20912. else {
  20913. this._depthSortedIndices = new Uint16Array(indices);
  20914. }
  20915. }
  20916. this._facetDepthSortFunction = function (f1, f2) {
  20917. return (f2.sqDistance - f1.sqDistance);
  20918. };
  20919. if (!this._facetDepthSortFrom) {
  20920. var camera = this.getScene().activeCamera;
  20921. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20922. }
  20923. this._depthSortedFacets = [];
  20924. for (var f = 0; f < this._facetNb; f++) {
  20925. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20926. this._depthSortedFacets.push(depthSortedFacet);
  20927. }
  20928. this._invertedMatrix = BABYLON.Matrix.Identity();
  20929. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20930. }
  20931. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20932. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20933. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20934. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20935. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20936. this._subDiv.max = this._partitioningSubdivisions;
  20937. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20938. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20939. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20940. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20941. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20942. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20943. // set the parameters for ComputeNormals()
  20944. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20945. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20946. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20947. this._facetParameters.bInfo = bInfo;
  20948. this._facetParameters.bbSize = this._bbSize;
  20949. this._facetParameters.subDiv = this._subDiv;
  20950. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20951. this._facetParameters.depthSort = this._facetDepthSort;
  20952. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20953. this.computeWorldMatrix(true);
  20954. this._worldMatrix.invertToRef(this._invertedMatrix);
  20955. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20956. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20957. }
  20958. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20959. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20960. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20961. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20962. var l = (this._depthSortedIndices.length / 3) | 0;
  20963. for (var f = 0; f < l; f++) {
  20964. var sind = this._depthSortedFacets[f].ind;
  20965. this._depthSortedIndices[f * 3] = indices[sind];
  20966. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20967. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20968. }
  20969. this.updateIndices(this._depthSortedIndices);
  20970. }
  20971. return this;
  20972. };
  20973. /**
  20974. * Returns the facetLocalNormals array.
  20975. * The normals are expressed in the mesh local spac
  20976. * @returns an array of Vector3
  20977. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20978. */
  20979. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20980. if (!this._facetNormals) {
  20981. this.updateFacetData();
  20982. }
  20983. return this._facetNormals;
  20984. };
  20985. /**
  20986. * Returns the facetLocalPositions array.
  20987. * The facet positions are expressed in the mesh local space
  20988. * @returns an array of Vector3
  20989. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20990. */
  20991. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20992. if (!this._facetPositions) {
  20993. this.updateFacetData();
  20994. }
  20995. return this._facetPositions;
  20996. };
  20997. /**
  20998. * Returns the facetLocalPartioning array
  20999. * @returns an array of array of numbers
  21000. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21001. */
  21002. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21003. if (!this._facetPartitioning) {
  21004. this.updateFacetData();
  21005. }
  21006. return this._facetPartitioning;
  21007. };
  21008. /**
  21009. * Returns the i-th facet position in the world system.
  21010. * This method allocates a new Vector3 per call
  21011. * @param i defines the facet index
  21012. * @returns a new Vector3
  21013. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21014. */
  21015. AbstractMesh.prototype.getFacetPosition = function (i) {
  21016. var pos = BABYLON.Vector3.Zero();
  21017. this.getFacetPositionToRef(i, pos);
  21018. return pos;
  21019. };
  21020. /**
  21021. * Sets the reference Vector3 with the i-th facet position in the world system
  21022. * @param i defines the facet index
  21023. * @param ref defines the target vector
  21024. * @returns the current mesh
  21025. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21026. */
  21027. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21028. var localPos = (this.getFacetLocalPositions())[i];
  21029. var world = this.getWorldMatrix();
  21030. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21031. return this;
  21032. };
  21033. /**
  21034. * Returns the i-th facet normal in the world system.
  21035. * This method allocates a new Vector3 per call
  21036. * @param i defines the facet index
  21037. * @returns a new Vector3
  21038. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21039. */
  21040. AbstractMesh.prototype.getFacetNormal = function (i) {
  21041. var norm = BABYLON.Vector3.Zero();
  21042. this.getFacetNormalToRef(i, norm);
  21043. return norm;
  21044. };
  21045. /**
  21046. * Sets the reference Vector3 with the i-th facet normal in the world system
  21047. * @param i defines the facet index
  21048. * @param ref defines the target vector
  21049. * @returns the current mesh
  21050. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21051. */
  21052. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21053. var localNorm = (this.getFacetLocalNormals())[i];
  21054. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21055. return this;
  21056. };
  21057. /**
  21058. * 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)
  21059. * @param x defines x coordinate
  21060. * @param y defines y coordinate
  21061. * @param z defines z coordinate
  21062. * @returns the array of facet indexes
  21063. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21064. */
  21065. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21066. var bInfo = this.getBoundingInfo();
  21067. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21068. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21069. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21070. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21071. return null;
  21072. }
  21073. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21074. };
  21075. /**
  21076. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21077. * @param projected sets as the (x,y,z) world projection on the facet
  21078. * @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
  21079. * @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
  21080. * @param x defines x coordinate
  21081. * @param y defines y coordinate
  21082. * @param z defines z coordinate
  21083. * @returns the face index if found (or null instead)
  21084. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21085. */
  21086. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21087. if (checkFace === void 0) { checkFace = false; }
  21088. if (facing === void 0) { facing = true; }
  21089. var world = this.getWorldMatrix();
  21090. var invMat = BABYLON.Tmp.Matrix[5];
  21091. world.invertToRef(invMat);
  21092. var invVect = BABYLON.Tmp.Vector3[8];
  21093. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21094. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21095. if (projected) {
  21096. // tranform the local computed projected vector to world coordinates
  21097. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21098. }
  21099. return closest;
  21100. };
  21101. /**
  21102. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21103. * @param projected sets as the (x,y,z) local projection on the facet
  21104. * @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
  21105. * @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
  21106. * @param x defines x coordinate
  21107. * @param y defines y coordinate
  21108. * @param z defines z coordinate
  21109. * @returns the face index if found (or null instead)
  21110. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21111. */
  21112. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21113. if (checkFace === void 0) { checkFace = false; }
  21114. if (facing === void 0) { facing = true; }
  21115. var closest = null;
  21116. var tmpx = 0.0;
  21117. var tmpy = 0.0;
  21118. var tmpz = 0.0;
  21119. var d = 0.0; // tmp dot facet normal * facet position
  21120. var t0 = 0.0;
  21121. var projx = 0.0;
  21122. var projy = 0.0;
  21123. var projz = 0.0;
  21124. // Get all the facets in the same partitioning block than (x, y, z)
  21125. var facetPositions = this.getFacetLocalPositions();
  21126. var facetNormals = this.getFacetLocalNormals();
  21127. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21128. if (!facetsInBlock) {
  21129. return null;
  21130. }
  21131. // Get the closest facet to (x, y, z)
  21132. var shortest = Number.MAX_VALUE; // init distance vars
  21133. var tmpDistance = shortest;
  21134. var fib; // current facet in the block
  21135. var norm; // current facet normal
  21136. var p0; // current facet barycenter position
  21137. // loop on all the facets in the current partitioning block
  21138. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21139. fib = facetsInBlock[idx];
  21140. norm = facetNormals[fib];
  21141. p0 = facetPositions[fib];
  21142. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21143. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21144. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21145. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21146. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21147. projx = x + norm.x * t0;
  21148. projy = y + norm.y * t0;
  21149. projz = z + norm.z * t0;
  21150. tmpx = projx - x;
  21151. tmpy = projy - y;
  21152. tmpz = projz - z;
  21153. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21154. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21155. shortest = tmpDistance;
  21156. closest = fib;
  21157. if (projected) {
  21158. projected.x = projx;
  21159. projected.y = projy;
  21160. projected.z = projz;
  21161. }
  21162. }
  21163. }
  21164. }
  21165. return closest;
  21166. };
  21167. /**
  21168. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21169. * @returns the parameters
  21170. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21171. */
  21172. AbstractMesh.prototype.getFacetDataParameters = function () {
  21173. return this._facetParameters;
  21174. };
  21175. /**
  21176. * Disables the feature FacetData and frees the related memory
  21177. * @returns the current mesh
  21178. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21179. */
  21180. AbstractMesh.prototype.disableFacetData = function () {
  21181. if (this._facetDataEnabled) {
  21182. this._facetDataEnabled = false;
  21183. this._facetPositions = new Array();
  21184. this._facetNormals = new Array();
  21185. this._facetPartitioning = new Array();
  21186. this._facetParameters = null;
  21187. this._depthSortedIndices = new Uint32Array(0);
  21188. }
  21189. return this;
  21190. };
  21191. /**
  21192. * Updates the AbstractMesh indices array
  21193. * @param indices defines the data source
  21194. * @returns the current mesh
  21195. */
  21196. AbstractMesh.prototype.updateIndices = function (indices) {
  21197. return this;
  21198. };
  21199. /**
  21200. * Creates new normals data for the mesh
  21201. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21202. * @returns the current mesh
  21203. */
  21204. AbstractMesh.prototype.createNormals = function (updatable) {
  21205. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21206. var indices = this.getIndices();
  21207. var normals;
  21208. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21209. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21210. }
  21211. else {
  21212. normals = [];
  21213. }
  21214. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21215. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21216. return this;
  21217. };
  21218. /**
  21219. * Align the mesh with a normal
  21220. * @param normal defines the normal to use
  21221. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21222. * @returns the current mesh
  21223. */
  21224. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21225. if (!upDirection) {
  21226. upDirection = BABYLON.Axis.Y;
  21227. }
  21228. var axisX = BABYLON.Tmp.Vector3[0];
  21229. var axisZ = BABYLON.Tmp.Vector3[1];
  21230. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21231. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21232. if (this.rotationQuaternion) {
  21233. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21234. }
  21235. else {
  21236. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21237. }
  21238. return this;
  21239. };
  21240. /** @hidden */
  21241. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21242. var engine = this.getEngine();
  21243. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21244. this._isOccluded = false;
  21245. return;
  21246. }
  21247. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21248. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21249. if (isOcclusionQueryAvailable) {
  21250. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21251. this._isOcclusionQueryInProgress = false;
  21252. this._occlusionInternalRetryCounter = 0;
  21253. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21254. }
  21255. else {
  21256. this._occlusionInternalRetryCounter++;
  21257. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21258. this._isOcclusionQueryInProgress = false;
  21259. this._occlusionInternalRetryCounter = 0;
  21260. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21261. // if strict continue the last state of the object.
  21262. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21263. }
  21264. else {
  21265. return;
  21266. }
  21267. }
  21268. }
  21269. var scene = this.getScene();
  21270. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21271. if (!this._occlusionQuery) {
  21272. this._occlusionQuery = engine.createQuery();
  21273. }
  21274. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21275. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21276. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21277. this._isOcclusionQueryInProgress = true;
  21278. };
  21279. /** No occlusion */
  21280. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21281. /** Occlusion set to optimisitic */
  21282. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21283. /** Occlusion set to strict */
  21284. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21285. /** Use an accurante occlusion algorithm */
  21286. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21287. /** Use a conservative occlusion algorithm */
  21288. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21289. return AbstractMesh;
  21290. }(BABYLON.TransformNode));
  21291. BABYLON.AbstractMesh = AbstractMesh;
  21292. })(BABYLON || (BABYLON = {}));
  21293. //# sourceMappingURL=babylon.abstractMesh.js.map
  21294. var BABYLON;
  21295. (function (BABYLON) {
  21296. /**
  21297. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21298. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21299. * 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.
  21300. */
  21301. var Light = /** @class */ (function (_super) {
  21302. __extends(Light, _super);
  21303. /**
  21304. * Creates a Light object in the scene.
  21305. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21306. * @param name The firendly name of the light
  21307. * @param scene The scene the light belongs too
  21308. */
  21309. function Light(name, scene) {
  21310. var _this = _super.call(this, name, scene) || this;
  21311. /**
  21312. * Diffuse gives the basic color to an object.
  21313. */
  21314. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21315. /**
  21316. * Specular produces a highlight color on an object.
  21317. * Note: This is note affecting PBR materials.
  21318. */
  21319. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21320. /**
  21321. * Strength of the light.
  21322. * Note: By default it is define in the framework own unit.
  21323. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21324. */
  21325. _this.intensity = 1.0;
  21326. /**
  21327. * Defines how far from the source the light is impacting in scene units.
  21328. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21329. */
  21330. _this.range = Number.MAX_VALUE;
  21331. /**
  21332. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21333. * of light.
  21334. */
  21335. _this._photometricScale = 1.0;
  21336. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21337. _this._radius = 0.00001;
  21338. /**
  21339. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21340. * exceeding the number allowed of the materials.
  21341. */
  21342. _this.renderPriority = 0;
  21343. /**
  21344. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21345. * the current shadow generator.
  21346. */
  21347. _this.shadowEnabled = true;
  21348. _this._excludeWithLayerMask = 0;
  21349. _this._includeOnlyWithLayerMask = 0;
  21350. _this._lightmapMode = 0;
  21351. /**
  21352. * @hidden Internal use only.
  21353. */
  21354. _this._excludedMeshesIds = new Array();
  21355. /**
  21356. * @hidden Internal use only.
  21357. */
  21358. _this._includedOnlyMeshesIds = new Array();
  21359. _this.getScene().addLight(_this);
  21360. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21361. _this._buildUniformLayout();
  21362. _this.includedOnlyMeshes = new Array();
  21363. _this.excludedMeshes = new Array();
  21364. _this._resyncMeshes();
  21365. return _this;
  21366. }
  21367. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21368. /**
  21369. * If every light affecting the material is in this lightmapMode,
  21370. * material.lightmapTexture adds or multiplies
  21371. * (depends on material.useLightmapAsShadowmap)
  21372. * after every other light calculations.
  21373. */
  21374. get: function () {
  21375. return Light._LIGHTMAP_DEFAULT;
  21376. },
  21377. enumerable: true,
  21378. configurable: true
  21379. });
  21380. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21381. /**
  21382. * material.lightmapTexture as only diffuse lighting from this light
  21383. * adds only specular lighting from this light
  21384. * adds dynamic shadows
  21385. */
  21386. get: function () {
  21387. return Light._LIGHTMAP_SPECULAR;
  21388. },
  21389. enumerable: true,
  21390. configurable: true
  21391. });
  21392. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21393. /**
  21394. * material.lightmapTexture as only lighting
  21395. * no light calculation from this light
  21396. * only adds dynamic shadows from this light
  21397. */
  21398. get: function () {
  21399. return Light._LIGHTMAP_SHADOWSONLY;
  21400. },
  21401. enumerable: true,
  21402. configurable: true
  21403. });
  21404. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21405. /**
  21406. * Each light type uses the default quantity according to its type:
  21407. * point/spot lights use luminous intensity
  21408. * directional lights use illuminance
  21409. */
  21410. get: function () {
  21411. return Light._INTENSITYMODE_AUTOMATIC;
  21412. },
  21413. enumerable: true,
  21414. configurable: true
  21415. });
  21416. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21417. /**
  21418. * lumen (lm)
  21419. */
  21420. get: function () {
  21421. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21422. },
  21423. enumerable: true,
  21424. configurable: true
  21425. });
  21426. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21427. /**
  21428. * candela (lm/sr)
  21429. */
  21430. get: function () {
  21431. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21432. },
  21433. enumerable: true,
  21434. configurable: true
  21435. });
  21436. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21437. /**
  21438. * lux (lm/m^2)
  21439. */
  21440. get: function () {
  21441. return Light._INTENSITYMODE_ILLUMINANCE;
  21442. },
  21443. enumerable: true,
  21444. configurable: true
  21445. });
  21446. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21447. /**
  21448. * nit (cd/m^2)
  21449. */
  21450. get: function () {
  21451. return Light._INTENSITYMODE_LUMINANCE;
  21452. },
  21453. enumerable: true,
  21454. configurable: true
  21455. });
  21456. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21457. /**
  21458. * Light type const id of the point light.
  21459. */
  21460. get: function () {
  21461. return Light._LIGHTTYPEID_POINTLIGHT;
  21462. },
  21463. enumerable: true,
  21464. configurable: true
  21465. });
  21466. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21467. /**
  21468. * Light type const id of the directional light.
  21469. */
  21470. get: function () {
  21471. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21472. },
  21473. enumerable: true,
  21474. configurable: true
  21475. });
  21476. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21477. /**
  21478. * Light type const id of the spot light.
  21479. */
  21480. get: function () {
  21481. return Light._LIGHTTYPEID_SPOTLIGHT;
  21482. },
  21483. enumerable: true,
  21484. configurable: true
  21485. });
  21486. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21487. /**
  21488. * Light type const id of the hemispheric light.
  21489. */
  21490. get: function () {
  21491. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21492. },
  21493. enumerable: true,
  21494. configurable: true
  21495. });
  21496. Object.defineProperty(Light.prototype, "intensityMode", {
  21497. /**
  21498. * Gets the photometric scale used to interpret the intensity.
  21499. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21500. */
  21501. get: function () {
  21502. return this._intensityMode;
  21503. },
  21504. /**
  21505. * Sets the photometric scale used to interpret the intensity.
  21506. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21507. */
  21508. set: function (value) {
  21509. this._intensityMode = value;
  21510. this._computePhotometricScale();
  21511. },
  21512. enumerable: true,
  21513. configurable: true
  21514. });
  21515. ;
  21516. ;
  21517. Object.defineProperty(Light.prototype, "radius", {
  21518. /**
  21519. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21520. */
  21521. get: function () {
  21522. return this._radius;
  21523. },
  21524. /**
  21525. * sets the light radius used by PBR Materials to simulate soft area lights.
  21526. */
  21527. set: function (value) {
  21528. this._radius = value;
  21529. this._computePhotometricScale();
  21530. },
  21531. enumerable: true,
  21532. configurable: true
  21533. });
  21534. ;
  21535. ;
  21536. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21537. /**
  21538. * Gets the only meshes impacted by this light.
  21539. */
  21540. get: function () {
  21541. return this._includedOnlyMeshes;
  21542. },
  21543. /**
  21544. * Sets the only meshes impacted by this light.
  21545. */
  21546. set: function (value) {
  21547. this._includedOnlyMeshes = value;
  21548. this._hookArrayForIncludedOnly(value);
  21549. },
  21550. enumerable: true,
  21551. configurable: true
  21552. });
  21553. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21554. /**
  21555. * Gets the meshes not impacted by this light.
  21556. */
  21557. get: function () {
  21558. return this._excludedMeshes;
  21559. },
  21560. /**
  21561. * Sets the meshes not impacted by this light.
  21562. */
  21563. set: function (value) {
  21564. this._excludedMeshes = value;
  21565. this._hookArrayForExcluded(value);
  21566. },
  21567. enumerable: true,
  21568. configurable: true
  21569. });
  21570. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21571. /**
  21572. * Gets the layer id use to find what meshes are not impacted by the light.
  21573. * Inactive if 0
  21574. */
  21575. get: function () {
  21576. return this._excludeWithLayerMask;
  21577. },
  21578. /**
  21579. * Sets the layer id use to find what meshes are not impacted by the light.
  21580. * Inactive if 0
  21581. */
  21582. set: function (value) {
  21583. this._excludeWithLayerMask = value;
  21584. this._resyncMeshes();
  21585. },
  21586. enumerable: true,
  21587. configurable: true
  21588. });
  21589. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21590. /**
  21591. * Gets the layer id use to find what meshes are impacted by the light.
  21592. * Inactive if 0
  21593. */
  21594. get: function () {
  21595. return this._includeOnlyWithLayerMask;
  21596. },
  21597. /**
  21598. * Sets the layer id use to find what meshes are impacted by the light.
  21599. * Inactive if 0
  21600. */
  21601. set: function (value) {
  21602. this._includeOnlyWithLayerMask = value;
  21603. this._resyncMeshes();
  21604. },
  21605. enumerable: true,
  21606. configurable: true
  21607. });
  21608. Object.defineProperty(Light.prototype, "lightmapMode", {
  21609. /**
  21610. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21611. */
  21612. get: function () {
  21613. return this._lightmapMode;
  21614. },
  21615. /**
  21616. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21617. */
  21618. set: function (value) {
  21619. if (this._lightmapMode === value) {
  21620. return;
  21621. }
  21622. this._lightmapMode = value;
  21623. this._markMeshesAsLightDirty();
  21624. },
  21625. enumerable: true,
  21626. configurable: true
  21627. });
  21628. /**
  21629. * Returns the string "Light".
  21630. * @returns the class name
  21631. */
  21632. Light.prototype.getClassName = function () {
  21633. return "Light";
  21634. };
  21635. /**
  21636. * Converts the light information to a readable string for debug purpose.
  21637. * @param fullDetails Supports for multiple levels of logging within scene loading
  21638. * @returns the human readable light info
  21639. */
  21640. Light.prototype.toString = function (fullDetails) {
  21641. var ret = "Name: " + this.name;
  21642. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21643. if (this.animations) {
  21644. for (var i = 0; i < this.animations.length; i++) {
  21645. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21646. }
  21647. }
  21648. if (fullDetails) {
  21649. }
  21650. return ret;
  21651. };
  21652. /**
  21653. * Set the enabled state of this node.
  21654. * @param value - the new enabled state
  21655. */
  21656. Light.prototype.setEnabled = function (value) {
  21657. _super.prototype.setEnabled.call(this, value);
  21658. this._resyncMeshes();
  21659. };
  21660. /**
  21661. * Returns the Light associated shadow generator if any.
  21662. * @return the associated shadow generator.
  21663. */
  21664. Light.prototype.getShadowGenerator = function () {
  21665. return this._shadowGenerator;
  21666. };
  21667. /**
  21668. * Returns a Vector3, the absolute light position in the World.
  21669. * @returns the world space position of the light
  21670. */
  21671. Light.prototype.getAbsolutePosition = function () {
  21672. return BABYLON.Vector3.Zero();
  21673. };
  21674. /**
  21675. * Specifies if the light will affect the passed mesh.
  21676. * @param mesh The mesh to test against the light
  21677. * @return true the mesh is affected otherwise, false.
  21678. */
  21679. Light.prototype.canAffectMesh = function (mesh) {
  21680. if (!mesh) {
  21681. return true;
  21682. }
  21683. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21684. return false;
  21685. }
  21686. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21687. return false;
  21688. }
  21689. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21690. return false;
  21691. }
  21692. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21693. return false;
  21694. }
  21695. return true;
  21696. };
  21697. /**
  21698. * Computes and Returns the light World matrix.
  21699. * @returns the world matrix
  21700. */
  21701. Light.prototype.getWorldMatrix = function () {
  21702. this._currentRenderId = this.getScene().getRenderId();
  21703. this._childRenderId = this._currentRenderId;
  21704. var worldMatrix = this._getWorldMatrix();
  21705. if (this.parent && this.parent.getWorldMatrix) {
  21706. if (!this._parentedWorldMatrix) {
  21707. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21708. }
  21709. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21710. this._markSyncedWithParent();
  21711. return this._parentedWorldMatrix;
  21712. }
  21713. return worldMatrix;
  21714. };
  21715. /**
  21716. * Sort function to order lights for rendering.
  21717. * @param a First Light object to compare to second.
  21718. * @param b Second Light object to compare first.
  21719. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21720. */
  21721. Light.CompareLightsPriority = function (a, b) {
  21722. //shadow-casting lights have priority over non-shadow-casting lights
  21723. //the renderPrioirty is a secondary sort criterion
  21724. if (a.shadowEnabled !== b.shadowEnabled) {
  21725. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21726. }
  21727. return b.renderPriority - a.renderPriority;
  21728. };
  21729. /**
  21730. * Releases resources associated with this node.
  21731. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21732. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21733. */
  21734. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21735. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21736. if (this._shadowGenerator) {
  21737. this._shadowGenerator.dispose();
  21738. this._shadowGenerator = null;
  21739. }
  21740. // Animations
  21741. this.getScene().stopAnimation(this);
  21742. // Remove from meshes
  21743. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21744. var mesh = _a[_i];
  21745. mesh._removeLightSource(this);
  21746. }
  21747. this._uniformBuffer.dispose();
  21748. // Remove from scene
  21749. this.getScene().removeLight(this);
  21750. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21751. };
  21752. /**
  21753. * Returns the light type ID (integer).
  21754. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21755. */
  21756. Light.prototype.getTypeID = function () {
  21757. return 0;
  21758. };
  21759. /**
  21760. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21761. * @returns the scaled intensity in intensity mode unit
  21762. */
  21763. Light.prototype.getScaledIntensity = function () {
  21764. return this._photometricScale * this.intensity;
  21765. };
  21766. /**
  21767. * Returns a new Light object, named "name", from the current one.
  21768. * @param name The name of the cloned light
  21769. * @returns the new created light
  21770. */
  21771. Light.prototype.clone = function (name) {
  21772. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21773. if (!constructor) {
  21774. return null;
  21775. }
  21776. return BABYLON.SerializationHelper.Clone(constructor, this);
  21777. };
  21778. /**
  21779. * Serializes the current light into a Serialization object.
  21780. * @returns the serialized object.
  21781. */
  21782. Light.prototype.serialize = function () {
  21783. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21784. // Type
  21785. serializationObject.type = this.getTypeID();
  21786. // Parent
  21787. if (this.parent) {
  21788. serializationObject.parentId = this.parent.id;
  21789. }
  21790. // Inclusion / exclusions
  21791. if (this.excludedMeshes.length > 0) {
  21792. serializationObject.excludedMeshesIds = [];
  21793. this.excludedMeshes.forEach(function (mesh) {
  21794. serializationObject.excludedMeshesIds.push(mesh.id);
  21795. });
  21796. }
  21797. if (this.includedOnlyMeshes.length > 0) {
  21798. serializationObject.includedOnlyMeshesIds = [];
  21799. this.includedOnlyMeshes.forEach(function (mesh) {
  21800. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21801. });
  21802. }
  21803. // Animations
  21804. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21805. serializationObject.ranges = this.serializeAnimationRanges();
  21806. return serializationObject;
  21807. };
  21808. /**
  21809. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21810. * This new light is named "name" and added to the passed scene.
  21811. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21812. * @param name The friendly name of the light
  21813. * @param scene The scene the new light will belong to
  21814. * @returns the constructor function
  21815. */
  21816. Light.GetConstructorFromName = function (type, name, scene) {
  21817. switch (type) {
  21818. case 0:
  21819. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21820. case 1:
  21821. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21822. case 2:
  21823. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21824. case 3:
  21825. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21826. }
  21827. return null;
  21828. };
  21829. /**
  21830. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21831. * @param parsedLight The JSON representation of the light
  21832. * @param scene The scene to create the parsed light in
  21833. * @returns the created light after parsing
  21834. */
  21835. Light.Parse = function (parsedLight, scene) {
  21836. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21837. if (!constructor) {
  21838. return null;
  21839. }
  21840. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21841. // Inclusion / exclusions
  21842. if (parsedLight.excludedMeshesIds) {
  21843. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21844. }
  21845. if (parsedLight.includedOnlyMeshesIds) {
  21846. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21847. }
  21848. // Parent
  21849. if (parsedLight.parentId) {
  21850. light._waitingParentId = parsedLight.parentId;
  21851. }
  21852. // Animations
  21853. if (parsedLight.animations) {
  21854. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21855. var parsedAnimation = parsedLight.animations[animationIndex];
  21856. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21857. }
  21858. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21859. }
  21860. if (parsedLight.autoAnimate) {
  21861. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21862. }
  21863. return light;
  21864. };
  21865. Light.prototype._hookArrayForExcluded = function (array) {
  21866. var _this = this;
  21867. var oldPush = array.push;
  21868. array.push = function () {
  21869. var items = [];
  21870. for (var _i = 0; _i < arguments.length; _i++) {
  21871. items[_i] = arguments[_i];
  21872. }
  21873. var result = oldPush.apply(array, items);
  21874. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21875. var item = items_1[_a];
  21876. item._resyncLighSource(_this);
  21877. }
  21878. return result;
  21879. };
  21880. var oldSplice = array.splice;
  21881. array.splice = function (index, deleteCount) {
  21882. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21883. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21884. var item = deleted_1[_i];
  21885. item._resyncLighSource(_this);
  21886. }
  21887. return deleted;
  21888. };
  21889. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21890. var item = array_1[_i];
  21891. item._resyncLighSource(this);
  21892. }
  21893. };
  21894. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21895. var _this = this;
  21896. var oldPush = array.push;
  21897. array.push = function () {
  21898. var items = [];
  21899. for (var _i = 0; _i < arguments.length; _i++) {
  21900. items[_i] = arguments[_i];
  21901. }
  21902. var result = oldPush.apply(array, items);
  21903. _this._resyncMeshes();
  21904. return result;
  21905. };
  21906. var oldSplice = array.splice;
  21907. array.splice = function (index, deleteCount) {
  21908. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21909. _this._resyncMeshes();
  21910. return deleted;
  21911. };
  21912. this._resyncMeshes();
  21913. };
  21914. Light.prototype._resyncMeshes = function () {
  21915. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21916. var mesh = _a[_i];
  21917. mesh._resyncLighSource(this);
  21918. }
  21919. };
  21920. /**
  21921. * Forces the meshes to update their light related information in their rendering used effects
  21922. * @hidden Internal Use Only
  21923. */
  21924. Light.prototype._markMeshesAsLightDirty = function () {
  21925. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21926. var mesh = _a[_i];
  21927. if (mesh._lightSources.indexOf(this) !== -1) {
  21928. mesh._markSubMeshesAsLightDirty();
  21929. }
  21930. }
  21931. };
  21932. /**
  21933. * Recomputes the cached photometric scale if needed.
  21934. */
  21935. Light.prototype._computePhotometricScale = function () {
  21936. this._photometricScale = this._getPhotometricScale();
  21937. this.getScene().resetCachedMaterial();
  21938. };
  21939. /**
  21940. * Returns the Photometric Scale according to the light type and intensity mode.
  21941. */
  21942. Light.prototype._getPhotometricScale = function () {
  21943. var photometricScale = 0.0;
  21944. var lightTypeID = this.getTypeID();
  21945. //get photometric mode
  21946. var photometricMode = this.intensityMode;
  21947. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21948. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21949. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21950. }
  21951. else {
  21952. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21953. }
  21954. }
  21955. //compute photometric scale
  21956. switch (lightTypeID) {
  21957. case Light.LIGHTTYPEID_POINTLIGHT:
  21958. case Light.LIGHTTYPEID_SPOTLIGHT:
  21959. switch (photometricMode) {
  21960. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21961. photometricScale = 1.0 / (4.0 * Math.PI);
  21962. break;
  21963. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21964. photometricScale = 1.0;
  21965. break;
  21966. case Light.INTENSITYMODE_LUMINANCE:
  21967. photometricScale = this.radius * this.radius;
  21968. break;
  21969. }
  21970. break;
  21971. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21972. switch (photometricMode) {
  21973. case Light.INTENSITYMODE_ILLUMINANCE:
  21974. photometricScale = 1.0;
  21975. break;
  21976. case Light.INTENSITYMODE_LUMINANCE:
  21977. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21978. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21979. var apexAngleRadians = this.radius;
  21980. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21981. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21982. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21983. photometricScale = solidAngle;
  21984. break;
  21985. }
  21986. break;
  21987. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21988. // No fall off in hemisperic light.
  21989. photometricScale = 1.0;
  21990. break;
  21991. }
  21992. return photometricScale;
  21993. };
  21994. /**
  21995. * Reorder the light in the scene according to their defined priority.
  21996. * @hidden Internal Use Only
  21997. */
  21998. Light.prototype._reorderLightsInScene = function () {
  21999. var scene = this.getScene();
  22000. if (this._renderPriority != 0) {
  22001. scene.requireLightSorting = true;
  22002. }
  22003. this.getScene().sortLightsByPriority();
  22004. };
  22005. //lightmapMode Consts
  22006. Light._LIGHTMAP_DEFAULT = 0;
  22007. Light._LIGHTMAP_SPECULAR = 1;
  22008. Light._LIGHTMAP_SHADOWSONLY = 2;
  22009. // Intensity Mode Consts
  22010. Light._INTENSITYMODE_AUTOMATIC = 0;
  22011. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22012. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22013. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22014. Light._INTENSITYMODE_LUMINANCE = 4;
  22015. // Light types ids const.
  22016. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22017. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22018. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22019. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22020. __decorate([
  22021. BABYLON.serializeAsColor3()
  22022. ], Light.prototype, "diffuse", void 0);
  22023. __decorate([
  22024. BABYLON.serializeAsColor3()
  22025. ], Light.prototype, "specular", void 0);
  22026. __decorate([
  22027. BABYLON.serialize()
  22028. ], Light.prototype, "intensity", void 0);
  22029. __decorate([
  22030. BABYLON.serialize()
  22031. ], Light.prototype, "range", void 0);
  22032. __decorate([
  22033. BABYLON.serialize()
  22034. ], Light.prototype, "intensityMode", null);
  22035. __decorate([
  22036. BABYLON.serialize()
  22037. ], Light.prototype, "radius", null);
  22038. __decorate([
  22039. BABYLON.serialize()
  22040. ], Light.prototype, "_renderPriority", void 0);
  22041. __decorate([
  22042. BABYLON.expandToProperty("_reorderLightsInScene")
  22043. ], Light.prototype, "renderPriority", void 0);
  22044. __decorate([
  22045. BABYLON.serialize()
  22046. ], Light.prototype, "shadowEnabled", void 0);
  22047. __decorate([
  22048. BABYLON.serialize("excludeWithLayerMask")
  22049. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22050. __decorate([
  22051. BABYLON.serialize("includeOnlyWithLayerMask")
  22052. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22053. __decorate([
  22054. BABYLON.serialize("lightmapMode")
  22055. ], Light.prototype, "_lightmapMode", void 0);
  22056. return Light;
  22057. }(BABYLON.Node));
  22058. BABYLON.Light = Light;
  22059. })(BABYLON || (BABYLON = {}));
  22060. //# sourceMappingURL=babylon.light.js.map
  22061. var BABYLON;
  22062. (function (BABYLON) {
  22063. var Camera = /** @class */ (function (_super) {
  22064. __extends(Camera, _super);
  22065. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22066. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22067. var _this = _super.call(this, name, scene) || this;
  22068. /**
  22069. * The vector the camera should consider as up.
  22070. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22071. */
  22072. _this.upVector = BABYLON.Vector3.Up();
  22073. _this.orthoLeft = null;
  22074. _this.orthoRight = null;
  22075. _this.orthoBottom = null;
  22076. _this.orthoTop = null;
  22077. /**
  22078. * FOV is set in Radians. (default is 0.8)
  22079. */
  22080. _this.fov = 0.8;
  22081. _this.minZ = 1;
  22082. _this.maxZ = 10000.0;
  22083. _this.inertia = 0.9;
  22084. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22085. _this.isIntermediate = false;
  22086. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22087. /**
  22088. * Restricts the camera to viewing objects with the same layerMask.
  22089. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22090. */
  22091. _this.layerMask = 0x0FFFFFFF;
  22092. /**
  22093. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22094. */
  22095. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22096. // Camera rig members
  22097. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22098. _this._rigCameras = new Array();
  22099. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22100. _this._skipRendering = false;
  22101. _this.customRenderTargets = new Array();
  22102. // Observables
  22103. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22104. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22105. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22106. _this.onRestoreStateObservable = new BABYLON.Observable();
  22107. // Cache
  22108. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22109. _this._projectionMatrix = new BABYLON.Matrix();
  22110. _this._doNotComputeProjectionMatrix = false;
  22111. _this._worldMatrix = BABYLON.Matrix.Identity();
  22112. _this._postProcesses = new Array();
  22113. _this._transformMatrix = BABYLON.Matrix.Zero();
  22114. _this._activeMeshes = new BABYLON.SmartArray(256);
  22115. _this._globalPosition = BABYLON.Vector3.Zero();
  22116. _this._refreshFrustumPlanes = true;
  22117. _this.getScene().addCamera(_this);
  22118. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22119. _this.getScene().activeCamera = _this;
  22120. }
  22121. _this.position = position;
  22122. return _this;
  22123. }
  22124. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22125. get: function () {
  22126. return Camera._PERSPECTIVE_CAMERA;
  22127. },
  22128. enumerable: true,
  22129. configurable: true
  22130. });
  22131. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22132. get: function () {
  22133. return Camera._ORTHOGRAPHIC_CAMERA;
  22134. },
  22135. enumerable: true,
  22136. configurable: true
  22137. });
  22138. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22139. /**
  22140. * This is the default FOV mode for perspective cameras.
  22141. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22142. *
  22143. */
  22144. get: function () {
  22145. return Camera._FOVMODE_VERTICAL_FIXED;
  22146. },
  22147. enumerable: true,
  22148. configurable: true
  22149. });
  22150. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22151. /**
  22152. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22153. *
  22154. */
  22155. get: function () {
  22156. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22157. },
  22158. enumerable: true,
  22159. configurable: true
  22160. });
  22161. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22162. get: function () {
  22163. return Camera._RIG_MODE_NONE;
  22164. },
  22165. enumerable: true,
  22166. configurable: true
  22167. });
  22168. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22169. get: function () {
  22170. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22171. },
  22172. enumerable: true,
  22173. configurable: true
  22174. });
  22175. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22176. get: function () {
  22177. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22178. },
  22179. enumerable: true,
  22180. configurable: true
  22181. });
  22182. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22183. get: function () {
  22184. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22185. },
  22186. enumerable: true,
  22187. configurable: true
  22188. });
  22189. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22190. get: function () {
  22191. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22192. },
  22193. enumerable: true,
  22194. configurable: true
  22195. });
  22196. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22197. get: function () {
  22198. return Camera._RIG_MODE_VR;
  22199. },
  22200. enumerable: true,
  22201. configurable: true
  22202. });
  22203. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22204. get: function () {
  22205. return Camera._RIG_MODE_WEBVR;
  22206. },
  22207. enumerable: true,
  22208. configurable: true
  22209. });
  22210. /**
  22211. * Store current camera state (fov, position, etc..)
  22212. */
  22213. Camera.prototype.storeState = function () {
  22214. this._stateStored = true;
  22215. this._storedFov = this.fov;
  22216. return this;
  22217. };
  22218. /**
  22219. * Restores the camera state values if it has been stored. You must call storeState() first
  22220. */
  22221. Camera.prototype._restoreStateValues = function () {
  22222. if (!this._stateStored) {
  22223. return false;
  22224. }
  22225. this.fov = this._storedFov;
  22226. return true;
  22227. };
  22228. /**
  22229. * Restored camera state. You must call storeState() first
  22230. */
  22231. Camera.prototype.restoreState = function () {
  22232. if (this._restoreStateValues()) {
  22233. this.onRestoreStateObservable.notifyObservers(this);
  22234. return true;
  22235. }
  22236. return false;
  22237. };
  22238. Camera.prototype.getClassName = function () {
  22239. return "Camera";
  22240. };
  22241. /**
  22242. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22243. */
  22244. Camera.prototype.toString = function (fullDetails) {
  22245. var ret = "Name: " + this.name;
  22246. ret += ", type: " + this.getClassName();
  22247. if (this.animations) {
  22248. for (var i = 0; i < this.animations.length; i++) {
  22249. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22250. }
  22251. }
  22252. if (fullDetails) {
  22253. }
  22254. return ret;
  22255. };
  22256. Object.defineProperty(Camera.prototype, "globalPosition", {
  22257. get: function () {
  22258. return this._globalPosition;
  22259. },
  22260. enumerable: true,
  22261. configurable: true
  22262. });
  22263. Camera.prototype.getActiveMeshes = function () {
  22264. return this._activeMeshes;
  22265. };
  22266. Camera.prototype.isActiveMesh = function (mesh) {
  22267. return (this._activeMeshes.indexOf(mesh) !== -1);
  22268. };
  22269. /**
  22270. * Is this camera ready to be used/rendered
  22271. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22272. * @return true if the camera is ready
  22273. */
  22274. Camera.prototype.isReady = function (completeCheck) {
  22275. if (completeCheck === void 0) { completeCheck = false; }
  22276. if (completeCheck) {
  22277. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22278. var pp = _a[_i];
  22279. if (pp && !pp.isReady()) {
  22280. return false;
  22281. }
  22282. }
  22283. }
  22284. return _super.prototype.isReady.call(this, completeCheck);
  22285. };
  22286. //Cache
  22287. Camera.prototype._initCache = function () {
  22288. _super.prototype._initCache.call(this);
  22289. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22290. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22291. this._cache.mode = undefined;
  22292. this._cache.minZ = undefined;
  22293. this._cache.maxZ = undefined;
  22294. this._cache.fov = undefined;
  22295. this._cache.fovMode = undefined;
  22296. this._cache.aspectRatio = undefined;
  22297. this._cache.orthoLeft = undefined;
  22298. this._cache.orthoRight = undefined;
  22299. this._cache.orthoBottom = undefined;
  22300. this._cache.orthoTop = undefined;
  22301. this._cache.renderWidth = undefined;
  22302. this._cache.renderHeight = undefined;
  22303. };
  22304. Camera.prototype._updateCache = function (ignoreParentClass) {
  22305. if (!ignoreParentClass) {
  22306. _super.prototype._updateCache.call(this);
  22307. }
  22308. this._cache.position.copyFrom(this.position);
  22309. this._cache.upVector.copyFrom(this.upVector);
  22310. };
  22311. // Synchronized
  22312. Camera.prototype._isSynchronized = function () {
  22313. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22314. };
  22315. Camera.prototype._isSynchronizedViewMatrix = function () {
  22316. if (!_super.prototype._isSynchronized.call(this))
  22317. return false;
  22318. return this._cache.position.equals(this.position)
  22319. && this._cache.upVector.equals(this.upVector)
  22320. && this.isSynchronizedWithParent();
  22321. };
  22322. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22323. var check = this._cache.mode === this.mode
  22324. && this._cache.minZ === this.minZ
  22325. && this._cache.maxZ === this.maxZ;
  22326. if (!check) {
  22327. return false;
  22328. }
  22329. var engine = this.getEngine();
  22330. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22331. check = this._cache.fov === this.fov
  22332. && this._cache.fovMode === this.fovMode
  22333. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22334. }
  22335. else {
  22336. check = this._cache.orthoLeft === this.orthoLeft
  22337. && this._cache.orthoRight === this.orthoRight
  22338. && this._cache.orthoBottom === this.orthoBottom
  22339. && this._cache.orthoTop === this.orthoTop
  22340. && this._cache.renderWidth === engine.getRenderWidth()
  22341. && this._cache.renderHeight === engine.getRenderHeight();
  22342. }
  22343. return check;
  22344. };
  22345. // Controls
  22346. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22347. };
  22348. Camera.prototype.detachControl = function (element) {
  22349. };
  22350. Camera.prototype.update = function () {
  22351. this._checkInputs();
  22352. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22353. this._updateRigCameras();
  22354. }
  22355. };
  22356. Camera.prototype._checkInputs = function () {
  22357. this.onAfterCheckInputsObservable.notifyObservers(this);
  22358. };
  22359. Object.defineProperty(Camera.prototype, "rigCameras", {
  22360. get: function () {
  22361. return this._rigCameras;
  22362. },
  22363. enumerable: true,
  22364. configurable: true
  22365. });
  22366. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22367. get: function () {
  22368. return this._rigPostProcess;
  22369. },
  22370. enumerable: true,
  22371. configurable: true
  22372. });
  22373. /**
  22374. * Internal, gets the first post proces.
  22375. * @returns the first post process to be run on this camera.
  22376. */
  22377. Camera.prototype._getFirstPostProcess = function () {
  22378. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22379. if (this._postProcesses[ppIndex] !== null) {
  22380. return this._postProcesses[ppIndex];
  22381. }
  22382. }
  22383. return null;
  22384. };
  22385. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22386. // invalidate framebuffer
  22387. var firstPostProcess = this._getFirstPostProcess();
  22388. if (firstPostProcess) {
  22389. firstPostProcess.markTextureDirty();
  22390. }
  22391. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22392. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22393. var cam = this._rigCameras[i];
  22394. var rigPostProcess = cam._rigPostProcess;
  22395. // for VR rig, there does not have to be a post process
  22396. if (rigPostProcess) {
  22397. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22398. if (isPass) {
  22399. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22400. cam.isIntermediate = this._postProcesses.length === 0;
  22401. }
  22402. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22403. rigPostProcess.markTextureDirty();
  22404. }
  22405. else {
  22406. cam._postProcesses = this._postProcesses.slice(0);
  22407. }
  22408. }
  22409. };
  22410. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22411. if (insertAt === void 0) { insertAt = null; }
  22412. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22413. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22414. return 0;
  22415. }
  22416. if (insertAt == null || insertAt < 0) {
  22417. this._postProcesses.push(postProcess);
  22418. }
  22419. else if (this._postProcesses[insertAt] === null) {
  22420. this._postProcesses[insertAt] = postProcess;
  22421. }
  22422. else {
  22423. this._postProcesses.splice(insertAt, 0, postProcess);
  22424. }
  22425. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22426. return this._postProcesses.indexOf(postProcess);
  22427. };
  22428. Camera.prototype.detachPostProcess = function (postProcess) {
  22429. var idx = this._postProcesses.indexOf(postProcess);
  22430. if (idx !== -1) {
  22431. this._postProcesses[idx] = null;
  22432. }
  22433. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22434. };
  22435. Camera.prototype.getWorldMatrix = function () {
  22436. if (this._isSynchronizedViewMatrix()) {
  22437. return this._worldMatrix;
  22438. }
  22439. // Getting the the view matrix will also compute the world matrix.
  22440. this.getViewMatrix();
  22441. return this._worldMatrix;
  22442. };
  22443. Camera.prototype._getViewMatrix = function () {
  22444. return BABYLON.Matrix.Identity();
  22445. };
  22446. Camera.prototype.getViewMatrix = function (force) {
  22447. if (!force && this._isSynchronizedViewMatrix()) {
  22448. return this._computedViewMatrix;
  22449. }
  22450. this.updateCache();
  22451. this._computedViewMatrix = this._getViewMatrix();
  22452. this._currentRenderId = this.getScene().getRenderId();
  22453. this._childRenderId = this._currentRenderId;
  22454. this._refreshFrustumPlanes = true;
  22455. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22456. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22457. }
  22458. this.onViewMatrixChangedObservable.notifyObservers(this);
  22459. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22460. return this._computedViewMatrix;
  22461. };
  22462. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22463. this._doNotComputeProjectionMatrix = true;
  22464. if (projection !== undefined) {
  22465. this._projectionMatrix = projection;
  22466. }
  22467. };
  22468. ;
  22469. Camera.prototype.unfreezeProjectionMatrix = function () {
  22470. this._doNotComputeProjectionMatrix = false;
  22471. };
  22472. ;
  22473. Camera.prototype.getProjectionMatrix = function (force) {
  22474. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22475. return this._projectionMatrix;
  22476. }
  22477. // Cache
  22478. this._cache.mode = this.mode;
  22479. this._cache.minZ = this.minZ;
  22480. this._cache.maxZ = this.maxZ;
  22481. // Matrix
  22482. this._refreshFrustumPlanes = true;
  22483. var engine = this.getEngine();
  22484. var scene = this.getScene();
  22485. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22486. this._cache.fov = this.fov;
  22487. this._cache.fovMode = this.fovMode;
  22488. this._cache.aspectRatio = engine.getAspectRatio(this);
  22489. if (this.minZ <= 0) {
  22490. this.minZ = 0.1;
  22491. }
  22492. if (scene.useRightHandedSystem) {
  22493. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22494. }
  22495. else {
  22496. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22497. }
  22498. }
  22499. else {
  22500. var halfWidth = engine.getRenderWidth() / 2.0;
  22501. var halfHeight = engine.getRenderHeight() / 2.0;
  22502. if (scene.useRightHandedSystem) {
  22503. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22504. }
  22505. else {
  22506. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22507. }
  22508. this._cache.orthoLeft = this.orthoLeft;
  22509. this._cache.orthoRight = this.orthoRight;
  22510. this._cache.orthoBottom = this.orthoBottom;
  22511. this._cache.orthoTop = this.orthoTop;
  22512. this._cache.renderWidth = engine.getRenderWidth();
  22513. this._cache.renderHeight = engine.getRenderHeight();
  22514. }
  22515. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22516. return this._projectionMatrix;
  22517. };
  22518. Camera.prototype.getTranformationMatrix = function () {
  22519. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22520. return this._transformMatrix;
  22521. };
  22522. Camera.prototype.updateFrustumPlanes = function () {
  22523. if (!this._refreshFrustumPlanes) {
  22524. return;
  22525. }
  22526. this.getTranformationMatrix();
  22527. if (!this._frustumPlanes) {
  22528. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22529. }
  22530. else {
  22531. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22532. }
  22533. this._refreshFrustumPlanes = false;
  22534. };
  22535. Camera.prototype.isInFrustum = function (target) {
  22536. this.updateFrustumPlanes();
  22537. return target.isInFrustum(this._frustumPlanes);
  22538. };
  22539. Camera.prototype.isCompletelyInFrustum = function (target) {
  22540. this.updateFrustumPlanes();
  22541. return target.isCompletelyInFrustum(this._frustumPlanes);
  22542. };
  22543. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22544. if (length === void 0) { length = 100; }
  22545. if (!transform) {
  22546. transform = this.getWorldMatrix();
  22547. }
  22548. if (!origin) {
  22549. origin = this.position;
  22550. }
  22551. var forward = new BABYLON.Vector3(0, 0, 1);
  22552. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22553. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22554. return new BABYLON.Ray(origin, direction, length);
  22555. };
  22556. /**
  22557. * Releases resources associated with this node.
  22558. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22559. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22560. */
  22561. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22562. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22563. // Observables
  22564. this.onViewMatrixChangedObservable.clear();
  22565. this.onProjectionMatrixChangedObservable.clear();
  22566. this.onAfterCheckInputsObservable.clear();
  22567. this.onRestoreStateObservable.clear();
  22568. // Inputs
  22569. if (this.inputs) {
  22570. this.inputs.clear();
  22571. }
  22572. // Animations
  22573. this.getScene().stopAnimation(this);
  22574. // Remove from scene
  22575. this.getScene().removeCamera(this);
  22576. while (this._rigCameras.length > 0) {
  22577. var camera = this._rigCameras.pop();
  22578. if (camera) {
  22579. camera.dispose();
  22580. }
  22581. }
  22582. // Postprocesses
  22583. if (this._rigPostProcess) {
  22584. this._rigPostProcess.dispose(this);
  22585. this._rigPostProcess = null;
  22586. this._postProcesses = [];
  22587. }
  22588. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22589. this._rigPostProcess = null;
  22590. this._postProcesses = [];
  22591. }
  22592. else {
  22593. var i = this._postProcesses.length;
  22594. while (--i >= 0) {
  22595. var postProcess = this._postProcesses[i];
  22596. if (postProcess) {
  22597. postProcess.dispose(this);
  22598. }
  22599. }
  22600. }
  22601. // Render targets
  22602. var i = this.customRenderTargets.length;
  22603. while (--i >= 0) {
  22604. this.customRenderTargets[i].dispose();
  22605. }
  22606. this.customRenderTargets = [];
  22607. // Active Meshes
  22608. this._activeMeshes.dispose();
  22609. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22610. };
  22611. Object.defineProperty(Camera.prototype, "leftCamera", {
  22612. // ---- Camera rigs section ----
  22613. get: function () {
  22614. if (this._rigCameras.length < 1) {
  22615. return null;
  22616. }
  22617. return this._rigCameras[0];
  22618. },
  22619. enumerable: true,
  22620. configurable: true
  22621. });
  22622. Object.defineProperty(Camera.prototype, "rightCamera", {
  22623. get: function () {
  22624. if (this._rigCameras.length < 2) {
  22625. return null;
  22626. }
  22627. return this._rigCameras[1];
  22628. },
  22629. enumerable: true,
  22630. configurable: true
  22631. });
  22632. Camera.prototype.getLeftTarget = function () {
  22633. if (this._rigCameras.length < 1) {
  22634. return null;
  22635. }
  22636. return this._rigCameras[0].getTarget();
  22637. };
  22638. Camera.prototype.getRightTarget = function () {
  22639. if (this._rigCameras.length < 2) {
  22640. return null;
  22641. }
  22642. return this._rigCameras[1].getTarget();
  22643. };
  22644. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22645. if (this.cameraRigMode === mode) {
  22646. return;
  22647. }
  22648. while (this._rigCameras.length > 0) {
  22649. var camera = this._rigCameras.pop();
  22650. if (camera) {
  22651. camera.dispose();
  22652. }
  22653. }
  22654. this.cameraRigMode = mode;
  22655. this._cameraRigParams = {};
  22656. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22657. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22658. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22659. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22660. // create the rig cameras, unless none
  22661. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22662. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22663. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22664. if (leftCamera && rightCamera) {
  22665. this._rigCameras.push(leftCamera);
  22666. this._rigCameras.push(rightCamera);
  22667. }
  22668. }
  22669. switch (this.cameraRigMode) {
  22670. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22671. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22672. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22673. break;
  22674. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22675. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22676. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22677. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22678. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22679. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22680. break;
  22681. case Camera.RIG_MODE_VR:
  22682. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22683. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22684. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22685. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22686. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22687. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22688. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22689. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22690. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22691. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22692. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22693. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22694. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22695. if (metrics.compensateDistortion) {
  22696. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22697. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22698. }
  22699. break;
  22700. case Camera.RIG_MODE_WEBVR:
  22701. if (rigParams.vrDisplay) {
  22702. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22703. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22704. //Left eye
  22705. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22706. this._rigCameras[0].setCameraRigParameter("left", true);
  22707. //leaving this for future reference
  22708. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22709. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22710. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22711. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22712. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22713. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22714. this._rigCameras[0].parent = this;
  22715. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22716. //Right eye
  22717. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22718. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22719. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22720. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22721. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22722. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22723. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22724. this._rigCameras[1].parent = this;
  22725. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22726. if (Camera.UseAlternateWebVRRendering) {
  22727. this._rigCameras[1]._skipRendering = true;
  22728. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22729. }
  22730. }
  22731. break;
  22732. }
  22733. this._cascadePostProcessesToRigCams();
  22734. this.update();
  22735. };
  22736. Camera.prototype._getVRProjectionMatrix = function () {
  22737. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22738. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22739. return this._projectionMatrix;
  22740. };
  22741. Camera.prototype._updateCameraRotationMatrix = function () {
  22742. //Here for WebVR
  22743. };
  22744. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22745. //Here for WebVR
  22746. };
  22747. /**
  22748. * This function MUST be overwritten by the different WebVR cameras available.
  22749. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22750. */
  22751. Camera.prototype._getWebVRProjectionMatrix = function () {
  22752. return BABYLON.Matrix.Identity();
  22753. };
  22754. /**
  22755. * This function MUST be overwritten by the different WebVR cameras available.
  22756. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22757. */
  22758. Camera.prototype._getWebVRViewMatrix = function () {
  22759. return BABYLON.Matrix.Identity();
  22760. };
  22761. Camera.prototype.setCameraRigParameter = function (name, value) {
  22762. if (!this._cameraRigParams) {
  22763. this._cameraRigParams = {};
  22764. }
  22765. this._cameraRigParams[name] = value;
  22766. //provisionnally:
  22767. if (name === "interaxialDistance") {
  22768. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22769. }
  22770. };
  22771. /**
  22772. * needs to be overridden by children so sub has required properties to be copied
  22773. */
  22774. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22775. return null;
  22776. };
  22777. /**
  22778. * May need to be overridden by children
  22779. */
  22780. Camera.prototype._updateRigCameras = function () {
  22781. for (var i = 0; i < this._rigCameras.length; i++) {
  22782. this._rigCameras[i].minZ = this.minZ;
  22783. this._rigCameras[i].maxZ = this.maxZ;
  22784. this._rigCameras[i].fov = this.fov;
  22785. }
  22786. // only update viewport when ANAGLYPH
  22787. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22788. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22789. }
  22790. };
  22791. Camera.prototype._setupInputs = function () {
  22792. };
  22793. Camera.prototype.serialize = function () {
  22794. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22795. // Type
  22796. serializationObject.type = this.getClassName();
  22797. // Parent
  22798. if (this.parent) {
  22799. serializationObject.parentId = this.parent.id;
  22800. }
  22801. if (this.inputs) {
  22802. this.inputs.serialize(serializationObject);
  22803. }
  22804. // Animations
  22805. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22806. serializationObject.ranges = this.serializeAnimationRanges();
  22807. return serializationObject;
  22808. };
  22809. Camera.prototype.clone = function (name) {
  22810. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22811. };
  22812. Camera.prototype.getDirection = function (localAxis) {
  22813. var result = BABYLON.Vector3.Zero();
  22814. this.getDirectionToRef(localAxis, result);
  22815. return result;
  22816. };
  22817. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22818. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22819. };
  22820. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22821. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22822. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22823. switch (type) {
  22824. case "ArcRotateCamera":
  22825. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22826. case "DeviceOrientationCamera":
  22827. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22828. case "FollowCamera":
  22829. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22830. case "ArcFollowCamera":
  22831. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22832. case "GamepadCamera":
  22833. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22834. case "TouchCamera":
  22835. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22836. case "VirtualJoysticksCamera":
  22837. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22838. case "WebVRFreeCamera":
  22839. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22840. case "WebVRGamepadCamera":
  22841. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22842. case "VRDeviceOrientationFreeCamera":
  22843. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22844. case "VRDeviceOrientationGamepadCamera":
  22845. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22846. case "AnaglyphArcRotateCamera":
  22847. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22848. case "AnaglyphFreeCamera":
  22849. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22850. case "AnaglyphGamepadCamera":
  22851. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22852. case "AnaglyphUniversalCamera":
  22853. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22854. case "StereoscopicArcRotateCamera":
  22855. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22856. case "StereoscopicFreeCamera":
  22857. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22858. case "StereoscopicGamepadCamera":
  22859. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22860. case "StereoscopicUniversalCamera":
  22861. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22862. case "FreeCamera": // Forcing Universal here
  22863. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22864. default: // Universal Camera is the default value
  22865. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22866. }
  22867. };
  22868. Camera.prototype.computeWorldMatrix = function () {
  22869. return this.getWorldMatrix();
  22870. };
  22871. Camera.Parse = function (parsedCamera, scene) {
  22872. var type = parsedCamera.type;
  22873. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22874. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22875. // Parent
  22876. if (parsedCamera.parentId) {
  22877. camera._waitingParentId = parsedCamera.parentId;
  22878. }
  22879. //If camera has an input manager, let it parse inputs settings
  22880. if (camera.inputs) {
  22881. camera.inputs.parse(parsedCamera);
  22882. camera._setupInputs();
  22883. }
  22884. if (camera.setPosition) { // need to force position
  22885. camera.position.copyFromFloats(0, 0, 0);
  22886. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22887. }
  22888. // Target
  22889. if (parsedCamera.target) {
  22890. if (camera.setTarget) {
  22891. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22892. }
  22893. }
  22894. // Apply 3d rig, when found
  22895. if (parsedCamera.cameraRigMode) {
  22896. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22897. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22898. }
  22899. // Animations
  22900. if (parsedCamera.animations) {
  22901. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22902. var parsedAnimation = parsedCamera.animations[animationIndex];
  22903. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22904. }
  22905. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22906. }
  22907. if (parsedCamera.autoAnimate) {
  22908. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22909. }
  22910. return camera;
  22911. };
  22912. // Statics
  22913. Camera._PERSPECTIVE_CAMERA = 0;
  22914. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22915. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22916. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22917. Camera._RIG_MODE_NONE = 0;
  22918. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22919. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22920. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22921. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22922. Camera._RIG_MODE_VR = 20;
  22923. Camera._RIG_MODE_WEBVR = 21;
  22924. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22925. Camera.UseAlternateWebVRRendering = false;
  22926. __decorate([
  22927. BABYLON.serializeAsVector3()
  22928. ], Camera.prototype, "position", void 0);
  22929. __decorate([
  22930. BABYLON.serializeAsVector3()
  22931. ], Camera.prototype, "upVector", void 0);
  22932. __decorate([
  22933. BABYLON.serialize()
  22934. ], Camera.prototype, "orthoLeft", void 0);
  22935. __decorate([
  22936. BABYLON.serialize()
  22937. ], Camera.prototype, "orthoRight", void 0);
  22938. __decorate([
  22939. BABYLON.serialize()
  22940. ], Camera.prototype, "orthoBottom", void 0);
  22941. __decorate([
  22942. BABYLON.serialize()
  22943. ], Camera.prototype, "orthoTop", void 0);
  22944. __decorate([
  22945. BABYLON.serialize()
  22946. ], Camera.prototype, "fov", void 0);
  22947. __decorate([
  22948. BABYLON.serialize()
  22949. ], Camera.prototype, "minZ", void 0);
  22950. __decorate([
  22951. BABYLON.serialize()
  22952. ], Camera.prototype, "maxZ", void 0);
  22953. __decorate([
  22954. BABYLON.serialize()
  22955. ], Camera.prototype, "inertia", void 0);
  22956. __decorate([
  22957. BABYLON.serialize()
  22958. ], Camera.prototype, "mode", void 0);
  22959. __decorate([
  22960. BABYLON.serialize()
  22961. ], Camera.prototype, "layerMask", void 0);
  22962. __decorate([
  22963. BABYLON.serialize()
  22964. ], Camera.prototype, "fovMode", void 0);
  22965. __decorate([
  22966. BABYLON.serialize()
  22967. ], Camera.prototype, "cameraRigMode", void 0);
  22968. __decorate([
  22969. BABYLON.serialize()
  22970. ], Camera.prototype, "interaxialDistance", void 0);
  22971. __decorate([
  22972. BABYLON.serialize()
  22973. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22974. return Camera;
  22975. }(BABYLON.Node));
  22976. BABYLON.Camera = Camera;
  22977. })(BABYLON || (BABYLON = {}));
  22978. //# sourceMappingURL=babylon.camera.js.map
  22979. var BABYLON;
  22980. (function (BABYLON) {
  22981. var RenderingManager = /** @class */ (function () {
  22982. function RenderingManager(scene) {
  22983. this._renderingGroups = new Array();
  22984. this._autoClearDepthStencil = {};
  22985. this._customOpaqueSortCompareFn = {};
  22986. this._customAlphaTestSortCompareFn = {};
  22987. this._customTransparentSortCompareFn = {};
  22988. this._renderinGroupInfo = null;
  22989. this._scene = scene;
  22990. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22991. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22992. }
  22993. }
  22994. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22995. if (depth === void 0) { depth = true; }
  22996. if (stencil === void 0) { stencil = true; }
  22997. if (this._depthStencilBufferAlreadyCleaned) {
  22998. return;
  22999. }
  23000. this._scene.getEngine().clear(null, false, depth, stencil);
  23001. this._depthStencilBufferAlreadyCleaned = true;
  23002. };
  23003. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23004. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23005. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23006. var info = null;
  23007. if (observable) {
  23008. if (!this._renderinGroupInfo) {
  23009. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23010. }
  23011. info = this._renderinGroupInfo;
  23012. info.scene = this._scene;
  23013. info.camera = this._scene.activeCamera;
  23014. }
  23015. // Dispatch sprites
  23016. if (renderSprites) {
  23017. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23018. var manager = this._scene.spriteManagers[index];
  23019. this.dispatchSprites(manager);
  23020. }
  23021. }
  23022. // Render
  23023. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23024. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23025. var renderingGroup = this._renderingGroups[index];
  23026. if (!renderingGroup && !observable)
  23027. continue;
  23028. var renderingGroupMask = 0;
  23029. // Fire PRECLEAR stage
  23030. if (observable && info) {
  23031. renderingGroupMask = Math.pow(2, index);
  23032. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23033. info.renderingGroupId = index;
  23034. observable.notifyObservers(info, renderingGroupMask);
  23035. }
  23036. // Clear depth/stencil if needed
  23037. if (RenderingManager.AUTOCLEAR) {
  23038. var autoClear = this._autoClearDepthStencil[index];
  23039. if (autoClear && autoClear.autoClear) {
  23040. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23041. }
  23042. }
  23043. if (observable && info) {
  23044. // Fire PREOPAQUE stage
  23045. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23046. observable.notifyObservers(info, renderingGroupMask);
  23047. // Fire PRETRANSPARENT stage
  23048. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23049. observable.notifyObservers(info, renderingGroupMask);
  23050. }
  23051. if (renderingGroup)
  23052. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23053. // Fire POSTTRANSPARENT stage
  23054. if (observable && info) {
  23055. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23056. observable.notifyObservers(info, renderingGroupMask);
  23057. }
  23058. }
  23059. };
  23060. RenderingManager.prototype.reset = function () {
  23061. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23062. var renderingGroup = this._renderingGroups[index];
  23063. if (renderingGroup) {
  23064. renderingGroup.prepare();
  23065. }
  23066. }
  23067. };
  23068. RenderingManager.prototype.dispose = function () {
  23069. this.freeRenderingGroups();
  23070. this._renderingGroups.length = 0;
  23071. };
  23072. /**
  23073. * Clear the info related to rendering groups preventing retention points during dispose.
  23074. */
  23075. RenderingManager.prototype.freeRenderingGroups = function () {
  23076. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23077. var renderingGroup = this._renderingGroups[index];
  23078. if (renderingGroup) {
  23079. renderingGroup.dispose();
  23080. }
  23081. }
  23082. };
  23083. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23084. if (this._renderingGroups[renderingGroupId] === undefined) {
  23085. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23086. }
  23087. };
  23088. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23089. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23090. this._prepareRenderingGroup(renderingGroupId);
  23091. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23092. };
  23093. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23094. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23095. this._prepareRenderingGroup(renderingGroupId);
  23096. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23097. };
  23098. /**
  23099. * @param subMesh The submesh to dispatch
  23100. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23101. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23102. */
  23103. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23104. if (mesh === undefined) {
  23105. mesh = subMesh.getMesh();
  23106. }
  23107. var renderingGroupId = mesh.renderingGroupId || 0;
  23108. this._prepareRenderingGroup(renderingGroupId);
  23109. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23110. };
  23111. /**
  23112. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23113. * This allowed control for front to back rendering or reversly depending of the special needs.
  23114. *
  23115. * @param renderingGroupId The rendering group id corresponding to its index
  23116. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23117. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23118. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23119. */
  23120. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23121. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23122. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23123. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23124. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23125. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23126. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23127. if (this._renderingGroups[renderingGroupId]) {
  23128. var group = this._renderingGroups[renderingGroupId];
  23129. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23130. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23131. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23132. }
  23133. };
  23134. /**
  23135. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23136. *
  23137. * @param renderingGroupId The rendering group id corresponding to its index
  23138. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23139. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23140. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23141. */
  23142. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23143. if (depth === void 0) { depth = true; }
  23144. if (stencil === void 0) { stencil = true; }
  23145. this._autoClearDepthStencil[renderingGroupId] = {
  23146. autoClear: autoClearDepthStencil,
  23147. depth: depth,
  23148. stencil: stencil
  23149. };
  23150. };
  23151. /**
  23152. * The max id used for rendering groups (not included)
  23153. */
  23154. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23155. /**
  23156. * The min id used for rendering groups (included)
  23157. */
  23158. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23159. /**
  23160. * Used to globally prevent autoclearing scenes.
  23161. */
  23162. RenderingManager.AUTOCLEAR = true;
  23163. return RenderingManager;
  23164. }());
  23165. BABYLON.RenderingManager = RenderingManager;
  23166. })(BABYLON || (BABYLON = {}));
  23167. //# sourceMappingURL=babylon.renderingManager.js.map
  23168. var BABYLON;
  23169. (function (BABYLON) {
  23170. var RenderingGroup = /** @class */ (function () {
  23171. /**
  23172. * Creates a new rendering group.
  23173. * @param index The rendering group index
  23174. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23175. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23176. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23177. */
  23178. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23179. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23180. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23181. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23182. this.index = index;
  23183. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23184. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23185. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23186. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23187. this._particleSystems = new BABYLON.SmartArray(256);
  23188. this._spriteManagers = new BABYLON.SmartArray(256);
  23189. this._edgesRenderers = new BABYLON.SmartArray(16);
  23190. this._scene = scene;
  23191. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23192. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23193. this.transparentSortCompareFn = transparentSortCompareFn;
  23194. }
  23195. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23196. /**
  23197. * Set the opaque sort comparison function.
  23198. * If null the sub meshes will be render in the order they were created
  23199. */
  23200. set: function (value) {
  23201. this._opaqueSortCompareFn = value;
  23202. if (value) {
  23203. this._renderOpaque = this.renderOpaqueSorted;
  23204. }
  23205. else {
  23206. this._renderOpaque = RenderingGroup.renderUnsorted;
  23207. }
  23208. },
  23209. enumerable: true,
  23210. configurable: true
  23211. });
  23212. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23213. /**
  23214. * Set the alpha test sort comparison function.
  23215. * If null the sub meshes will be render in the order they were created
  23216. */
  23217. set: function (value) {
  23218. this._alphaTestSortCompareFn = value;
  23219. if (value) {
  23220. this._renderAlphaTest = this.renderAlphaTestSorted;
  23221. }
  23222. else {
  23223. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23224. }
  23225. },
  23226. enumerable: true,
  23227. configurable: true
  23228. });
  23229. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23230. /**
  23231. * Set the transparent sort comparison function.
  23232. * If null the sub meshes will be render in the order they were created
  23233. */
  23234. set: function (value) {
  23235. if (value) {
  23236. this._transparentSortCompareFn = value;
  23237. }
  23238. else {
  23239. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23240. }
  23241. this._renderTransparent = this.renderTransparentSorted;
  23242. },
  23243. enumerable: true,
  23244. configurable: true
  23245. });
  23246. /**
  23247. * Render all the sub meshes contained in the group.
  23248. * @param customRenderFunction Used to override the default render behaviour of the group.
  23249. * @returns true if rendered some submeshes.
  23250. */
  23251. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23252. if (customRenderFunction) {
  23253. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23254. return;
  23255. }
  23256. var engine = this._scene.getEngine();
  23257. // Depth only
  23258. if (this._depthOnlySubMeshes.length !== 0) {
  23259. engine.setColorWrite(false);
  23260. this._renderAlphaTest(this._depthOnlySubMeshes);
  23261. engine.setColorWrite(true);
  23262. }
  23263. // Opaque
  23264. if (this._opaqueSubMeshes.length !== 0) {
  23265. this._renderOpaque(this._opaqueSubMeshes);
  23266. }
  23267. // Alpha test
  23268. if (this._alphaTestSubMeshes.length !== 0) {
  23269. this._renderAlphaTest(this._alphaTestSubMeshes);
  23270. }
  23271. var stencilState = engine.getStencilBuffer();
  23272. engine.setStencilBuffer(false);
  23273. // Sprites
  23274. if (renderSprites) {
  23275. this._renderSprites();
  23276. }
  23277. // Particles
  23278. if (renderParticles) {
  23279. this._renderParticles(activeMeshes);
  23280. }
  23281. if (this.onBeforeTransparentRendering) {
  23282. this.onBeforeTransparentRendering();
  23283. }
  23284. // Transparent
  23285. if (this._transparentSubMeshes.length !== 0) {
  23286. this._renderTransparent(this._transparentSubMeshes);
  23287. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23288. }
  23289. // Set back stencil to false in case it changes before the edge renderer.
  23290. engine.setStencilBuffer(false);
  23291. // Edges
  23292. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23293. this._edgesRenderers.data[edgesRendererIndex].render();
  23294. }
  23295. // Restore Stencil state.
  23296. engine.setStencilBuffer(stencilState);
  23297. };
  23298. /**
  23299. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23300. * @param subMeshes The submeshes to render
  23301. */
  23302. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23303. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23304. };
  23305. /**
  23306. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23307. * @param subMeshes The submeshes to render
  23308. */
  23309. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23310. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23311. };
  23312. /**
  23313. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23314. * @param subMeshes The submeshes to render
  23315. */
  23316. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23317. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23318. };
  23319. /**
  23320. * Renders the submeshes in a specified order.
  23321. * @param subMeshes The submeshes to sort before render
  23322. * @param sortCompareFn The comparison function use to sort
  23323. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23324. * @param transparent Specifies to activate blending if true
  23325. */
  23326. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23327. var subIndex = 0;
  23328. var subMesh;
  23329. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23330. for (; subIndex < subMeshes.length; subIndex++) {
  23331. subMesh = subMeshes.data[subIndex];
  23332. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23333. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23334. }
  23335. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23336. if (sortCompareFn) {
  23337. sortedArray.sort(sortCompareFn);
  23338. }
  23339. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23340. subMesh = sortedArray[subIndex];
  23341. if (transparent) {
  23342. var material = subMesh.getMaterial();
  23343. if (material && material.needDepthPrePass) {
  23344. var engine = material.getScene().getEngine();
  23345. engine.setColorWrite(false);
  23346. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23347. subMesh.render(false);
  23348. engine.setColorWrite(true);
  23349. }
  23350. }
  23351. subMesh.render(transparent);
  23352. }
  23353. };
  23354. /**
  23355. * Renders the submeshes in the order they were dispatched (no sort applied).
  23356. * @param subMeshes The submeshes to render
  23357. */
  23358. RenderingGroup.renderUnsorted = function (subMeshes) {
  23359. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23360. var submesh = subMeshes.data[subIndex];
  23361. submesh.render(false);
  23362. }
  23363. };
  23364. /**
  23365. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23366. * are rendered back to front if in the same alpha index.
  23367. *
  23368. * @param a The first submesh
  23369. * @param b The second submesh
  23370. * @returns The result of the comparison
  23371. */
  23372. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23373. // Alpha index first
  23374. if (a._alphaIndex > b._alphaIndex) {
  23375. return 1;
  23376. }
  23377. if (a._alphaIndex < b._alphaIndex) {
  23378. return -1;
  23379. }
  23380. // Then distance to camera
  23381. return RenderingGroup.backToFrontSortCompare(a, b);
  23382. };
  23383. /**
  23384. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23385. * are rendered back to front.
  23386. *
  23387. * @param a The first submesh
  23388. * @param b The second submesh
  23389. * @returns The result of the comparison
  23390. */
  23391. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23392. // Then distance to camera
  23393. if (a._distanceToCamera < b._distanceToCamera) {
  23394. return 1;
  23395. }
  23396. if (a._distanceToCamera > b._distanceToCamera) {
  23397. return -1;
  23398. }
  23399. return 0;
  23400. };
  23401. /**
  23402. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23403. * are rendered front to back (prevent overdraw).
  23404. *
  23405. * @param a The first submesh
  23406. * @param b The second submesh
  23407. * @returns The result of the comparison
  23408. */
  23409. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23410. // Then distance to camera
  23411. if (a._distanceToCamera < b._distanceToCamera) {
  23412. return -1;
  23413. }
  23414. if (a._distanceToCamera > b._distanceToCamera) {
  23415. return 1;
  23416. }
  23417. return 0;
  23418. };
  23419. /**
  23420. * Resets the different lists of submeshes to prepare a new frame.
  23421. */
  23422. RenderingGroup.prototype.prepare = function () {
  23423. this._opaqueSubMeshes.reset();
  23424. this._transparentSubMeshes.reset();
  23425. this._alphaTestSubMeshes.reset();
  23426. this._depthOnlySubMeshes.reset();
  23427. this._particleSystems.reset();
  23428. this._spriteManagers.reset();
  23429. this._edgesRenderers.reset();
  23430. };
  23431. RenderingGroup.prototype.dispose = function () {
  23432. this._opaqueSubMeshes.dispose();
  23433. this._transparentSubMeshes.dispose();
  23434. this._alphaTestSubMeshes.dispose();
  23435. this._depthOnlySubMeshes.dispose();
  23436. this._particleSystems.dispose();
  23437. this._spriteManagers.dispose();
  23438. this._edgesRenderers.dispose();
  23439. };
  23440. /**
  23441. * Inserts the submesh in its correct queue depending on its material.
  23442. * @param subMesh The submesh to dispatch
  23443. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23444. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23445. */
  23446. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23447. // Get mesh and materials if not provided
  23448. if (mesh === undefined) {
  23449. mesh = subMesh.getMesh();
  23450. }
  23451. if (material === undefined) {
  23452. material = subMesh.getMaterial();
  23453. }
  23454. if (material === null || material === undefined) {
  23455. return;
  23456. }
  23457. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23458. this._transparentSubMeshes.push(subMesh);
  23459. }
  23460. else if (material.needAlphaTesting()) { // Alpha test
  23461. if (material.needDepthPrePass) {
  23462. this._depthOnlySubMeshes.push(subMesh);
  23463. }
  23464. this._alphaTestSubMeshes.push(subMesh);
  23465. }
  23466. else {
  23467. if (material.needDepthPrePass) {
  23468. this._depthOnlySubMeshes.push(subMesh);
  23469. }
  23470. this._opaqueSubMeshes.push(subMesh); // Opaque
  23471. }
  23472. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  23473. this._edgesRenderers.push(mesh._edgesRenderer);
  23474. }
  23475. };
  23476. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23477. this._spriteManagers.push(spriteManager);
  23478. };
  23479. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23480. this._particleSystems.push(particleSystem);
  23481. };
  23482. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23483. if (this._particleSystems.length === 0) {
  23484. return;
  23485. }
  23486. // Particles
  23487. var activeCamera = this._scene.activeCamera;
  23488. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23489. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23490. var particleSystem = this._particleSystems.data[particleIndex];
  23491. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23492. continue;
  23493. }
  23494. var emitter = particleSystem.emitter;
  23495. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23496. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23497. }
  23498. }
  23499. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23500. };
  23501. RenderingGroup.prototype._renderSprites = function () {
  23502. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23503. return;
  23504. }
  23505. // Sprites
  23506. var activeCamera = this._scene.activeCamera;
  23507. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23508. for (var id = 0; id < this._spriteManagers.length; id++) {
  23509. var spriteManager = this._spriteManagers.data[id];
  23510. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23511. spriteManager.render();
  23512. }
  23513. }
  23514. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23515. };
  23516. return RenderingGroup;
  23517. }());
  23518. BABYLON.RenderingGroup = RenderingGroup;
  23519. })(BABYLON || (BABYLON = {}));
  23520. //# sourceMappingURL=babylon.renderingGroup.js.map
  23521. var BABYLON;
  23522. (function (BABYLON) {
  23523. /** @hidden */
  23524. var ClickInfo = /** @class */ (function () {
  23525. function ClickInfo() {
  23526. this._singleClick = false;
  23527. this._doubleClick = false;
  23528. this._hasSwiped = false;
  23529. this._ignore = false;
  23530. }
  23531. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23532. get: function () {
  23533. return this._singleClick;
  23534. },
  23535. set: function (b) {
  23536. this._singleClick = b;
  23537. },
  23538. enumerable: true,
  23539. configurable: true
  23540. });
  23541. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23542. get: function () {
  23543. return this._doubleClick;
  23544. },
  23545. set: function (b) {
  23546. this._doubleClick = b;
  23547. },
  23548. enumerable: true,
  23549. configurable: true
  23550. });
  23551. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23552. get: function () {
  23553. return this._hasSwiped;
  23554. },
  23555. set: function (b) {
  23556. this._hasSwiped = b;
  23557. },
  23558. enumerable: true,
  23559. configurable: true
  23560. });
  23561. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23562. get: function () {
  23563. return this._ignore;
  23564. },
  23565. set: function (b) {
  23566. this._ignore = b;
  23567. },
  23568. enumerable: true,
  23569. configurable: true
  23570. });
  23571. return ClickInfo;
  23572. }());
  23573. /**
  23574. * This class is used by the onRenderingGroupObservable
  23575. */
  23576. var RenderingGroupInfo = /** @class */ (function () {
  23577. function RenderingGroupInfo() {
  23578. }
  23579. /**
  23580. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23581. * This stage will be fired no matter what
  23582. */
  23583. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23584. /**
  23585. * Called before opaque object are rendered.
  23586. * This stage will be fired only if there's 3D Opaque content to render
  23587. */
  23588. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23589. /**
  23590. * Called after the opaque objects are rendered and before the transparent ones
  23591. * This stage will be fired only if there's 3D transparent content to render
  23592. */
  23593. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23594. /**
  23595. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23596. * This stage will be fired no matter what
  23597. */
  23598. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23599. return RenderingGroupInfo;
  23600. }());
  23601. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23602. /**
  23603. * Represents a scene to be rendered by the engine.
  23604. * @see http://doc.babylonjs.com/features/scene
  23605. */
  23606. var Scene = /** @class */ (function () {
  23607. /**
  23608. * Creates a new Scene
  23609. * @param engine defines the engine to use to render this scene
  23610. */
  23611. function Scene(engine) {
  23612. // Members
  23613. /**
  23614. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23615. */
  23616. this.autoClear = true;
  23617. /**
  23618. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23619. */
  23620. this.autoClearDepthAndStencil = true;
  23621. /**
  23622. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23623. */
  23624. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23625. /**
  23626. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23627. */
  23628. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23629. this._forceWireframe = false;
  23630. this._forcePointsCloud = false;
  23631. /**
  23632. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23633. */
  23634. this.forceShowBoundingBoxes = false;
  23635. /**
  23636. * Gets or sets a boolean indicating if animations are enabled
  23637. */
  23638. this.animationsEnabled = true;
  23639. this._animationPropertiesOverride = null;
  23640. /**
  23641. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23642. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23643. */
  23644. this.useConstantAnimationDeltaTime = false;
  23645. /**
  23646. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23647. * Please note that it requires to run a ray cast through the scene on every frame
  23648. */
  23649. this.constantlyUpdateMeshUnderPointer = false;
  23650. /**
  23651. * Defines the HTML cursor to use when hovering over interactive elements
  23652. */
  23653. this.hoverCursor = "pointer";
  23654. /**
  23655. * Defines the HTML default cursor to use (empty by default)
  23656. */
  23657. this.defaultCursor = "";
  23658. /**
  23659. * This is used to call preventDefault() on pointer down
  23660. * in order to block unwanted artifacts like system double clicks
  23661. */
  23662. this.preventDefaultOnPointerDown = true;
  23663. // Metadata
  23664. /**
  23665. * Gets or sets user defined metadata
  23666. */
  23667. this.metadata = null;
  23668. /**
  23669. * Use this array to add regular expressions used to disable offline support for specific urls
  23670. */
  23671. this.disableOfflineSupportExceptionRules = new Array();
  23672. /**
  23673. * An event triggered when the scene is disposed.
  23674. */
  23675. this.onDisposeObservable = new BABYLON.Observable();
  23676. this._onDisposeObserver = null;
  23677. /**
  23678. * An event triggered before rendering the scene (right after animations and physics)
  23679. */
  23680. this.onBeforeRenderObservable = new BABYLON.Observable();
  23681. this._onBeforeRenderObserver = null;
  23682. /**
  23683. * An event triggered after rendering the scene
  23684. */
  23685. this.onAfterRenderObservable = new BABYLON.Observable();
  23686. this._onAfterRenderObserver = null;
  23687. /**
  23688. * An event triggered before animating the scene
  23689. */
  23690. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23691. /**
  23692. * An event triggered after animations processing
  23693. */
  23694. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23695. /**
  23696. * An event triggered before draw calls are ready to be sent
  23697. */
  23698. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23699. /**
  23700. * An event triggered after draw calls have been sent
  23701. */
  23702. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23703. /**
  23704. * An event triggered when physic simulation is about to be run
  23705. */
  23706. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23707. /**
  23708. * An event triggered when physic simulation has been done
  23709. */
  23710. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23711. /**
  23712. * An event triggered when the scene is ready
  23713. */
  23714. this.onReadyObservable = new BABYLON.Observable();
  23715. /**
  23716. * An event triggered before rendering a camera
  23717. */
  23718. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23719. this._onBeforeCameraRenderObserver = null;
  23720. /**
  23721. * An event triggered after rendering a camera
  23722. */
  23723. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23724. this._onAfterCameraRenderObserver = null;
  23725. /**
  23726. * An event triggered when active meshes evaluation is about to start
  23727. */
  23728. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23729. /**
  23730. * An event triggered when active meshes evaluation is done
  23731. */
  23732. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23733. /**
  23734. * An event triggered when particles rendering is about to start
  23735. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23736. */
  23737. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23738. /**
  23739. * An event triggered when particles rendering is done
  23740. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23741. */
  23742. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23743. /**
  23744. * An event triggered when sprites rendering is about to start
  23745. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23746. */
  23747. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23748. /**
  23749. * An event triggered when sprites rendering is done
  23750. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23751. */
  23752. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23753. /**
  23754. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23755. */
  23756. this.onDataLoadedObservable = new BABYLON.Observable();
  23757. /**
  23758. * An event triggered when a camera is created
  23759. */
  23760. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23761. /**
  23762. * An event triggered when a camera is removed
  23763. */
  23764. this.onCameraRemovedObservable = new BABYLON.Observable();
  23765. /**
  23766. * An event triggered when a light is created
  23767. */
  23768. this.onNewLightAddedObservable = new BABYLON.Observable();
  23769. /**
  23770. * An event triggered when a light is removed
  23771. */
  23772. this.onLightRemovedObservable = new BABYLON.Observable();
  23773. /**
  23774. * An event triggered when a geometry is created
  23775. */
  23776. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23777. /**
  23778. * An event triggered when a geometry is removed
  23779. */
  23780. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23781. /**
  23782. * An event triggered when a transform node is created
  23783. */
  23784. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23785. /**
  23786. * An event triggered when a transform node is removed
  23787. */
  23788. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23789. /**
  23790. * An event triggered when a mesh is created
  23791. */
  23792. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23793. /**
  23794. * An event triggered when a mesh is removed
  23795. */
  23796. this.onMeshRemovedObservable = new BABYLON.Observable();
  23797. /**
  23798. * An event triggered when render targets are about to be rendered
  23799. * Can happen multiple times per frame.
  23800. */
  23801. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23802. /**
  23803. * An event triggered when render targets were rendered.
  23804. * Can happen multiple times per frame.
  23805. */
  23806. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23807. /**
  23808. * An event triggered before calculating deterministic simulation step
  23809. */
  23810. this.onBeforeStepObservable = new BABYLON.Observable();
  23811. /**
  23812. * An event triggered after calculating deterministic simulation step
  23813. */
  23814. this.onAfterStepObservable = new BABYLON.Observable();
  23815. /**
  23816. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23817. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23818. * 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)
  23819. */
  23820. this.onRenderingGroupObservable = new BABYLON.Observable();
  23821. // Animations
  23822. /**
  23823. * Gets a list of Animations associated with the scene
  23824. */
  23825. this.animations = [];
  23826. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23827. /**
  23828. * 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).
  23829. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23830. */
  23831. this.onPrePointerObservable = new BABYLON.Observable();
  23832. /**
  23833. * Observable event triggered each time an input event is received from the rendering canvas
  23834. */
  23835. this.onPointerObservable = new BABYLON.Observable();
  23836. this._meshPickProceed = false;
  23837. this._currentPickResult = null;
  23838. this._previousPickResult = null;
  23839. this._totalPointersPressed = 0;
  23840. this._doubleClickOccured = false;
  23841. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23842. this.cameraToUseForPointers = null;
  23843. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23844. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23845. this._startingPointerTime = 0;
  23846. this._previousStartingPointerTime = 0;
  23847. // Deterministic lockstep
  23848. this._timeAccumulator = 0;
  23849. this._currentStepId = 0;
  23850. this._currentInternalStep = 0;
  23851. // Keyboard
  23852. /**
  23853. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23854. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23855. */
  23856. this.onPreKeyboardObservable = new BABYLON.Observable();
  23857. /**
  23858. * Observable event triggered each time an keyboard event is received from the hosting window
  23859. */
  23860. this.onKeyboardObservable = new BABYLON.Observable();
  23861. // Coordinates system
  23862. this._useRightHandedSystem = false;
  23863. // Fog
  23864. this._fogEnabled = true;
  23865. this._fogMode = Scene.FOGMODE_NONE;
  23866. /**
  23867. * Gets or sets the fog color to use
  23868. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23869. */
  23870. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23871. /**
  23872. * Gets or sets the fog density to use
  23873. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23874. */
  23875. this.fogDensity = 0.1;
  23876. /**
  23877. * Gets or sets the fog start distance to use
  23878. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23879. */
  23880. this.fogStart = 0;
  23881. /**
  23882. * Gets or sets the fog end distance to use
  23883. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23884. */
  23885. this.fogEnd = 1000.0;
  23886. // Lights
  23887. this._shadowsEnabled = true;
  23888. this._lightsEnabled = true;
  23889. /**
  23890. * All of the lights added to this scene
  23891. * @see http://doc.babylonjs.com/babylon101/lights
  23892. */
  23893. this.lights = new Array();
  23894. // Cameras
  23895. /** All of the cameras added to this scene.
  23896. * @see http://doc.babylonjs.com/babylon101/cameras
  23897. */
  23898. this.cameras = new Array();
  23899. /** All of the active cameras added to this scene. */
  23900. this.activeCameras = new Array();
  23901. // Meshes
  23902. /**
  23903. * All of the tranform nodes added to this scene
  23904. * @see http://doc.babylonjs.com/how_to/transformnode
  23905. */
  23906. this.transformNodes = new Array();
  23907. /**
  23908. * All of the (abstract) meshes added to this scene
  23909. */
  23910. this.meshes = new Array();
  23911. /**
  23912. * All of the animation groups added to this scene
  23913. * @see http://doc.babylonjs.com/how_to/group
  23914. */
  23915. this.animationGroups = new Array();
  23916. // Geometries
  23917. this._geometries = new Array();
  23918. /**
  23919. * All of the materials added to this scene
  23920. * @see http://doc.babylonjs.com/babylon101/materials
  23921. */
  23922. this.materials = new Array();
  23923. /**
  23924. * All of the multi-materials added to this scene
  23925. * @see http://doc.babylonjs.com/how_to/multi_materials
  23926. */
  23927. this.multiMaterials = new Array();
  23928. // Textures
  23929. this._texturesEnabled = true;
  23930. /**
  23931. * All of the textures added to this scene
  23932. */
  23933. this.textures = new Array();
  23934. // Particles
  23935. /**
  23936. * Gets or sets a boolean indicating if particles are enabled on this scene
  23937. */
  23938. this.particlesEnabled = true;
  23939. /**
  23940. * All of the particle systems added to this scene
  23941. * @see http://doc.babylonjs.com/babylon101/particles
  23942. */
  23943. this.particleSystems = new Array();
  23944. // Sprites
  23945. /**
  23946. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23947. */
  23948. this.spritesEnabled = true;
  23949. /**
  23950. * All of the sprite managers added to this scene
  23951. * @see http://doc.babylonjs.com/babylon101/sprites
  23952. */
  23953. this.spriteManagers = new Array();
  23954. /**
  23955. * The list of layers (background and foreground) of the scene
  23956. */
  23957. this.layers = new Array();
  23958. /**
  23959. * The list of effect layers (highlights/glow) added to the scene
  23960. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23961. * @see http://doc.babylonjs.com/how_to/glow_layer
  23962. */
  23963. this.effectLayers = new Array();
  23964. // Skeletons
  23965. this._skeletonsEnabled = true;
  23966. /**
  23967. * The list of skeletons added to the scene
  23968. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23969. */
  23970. this.skeletons = new Array();
  23971. // Morph targets
  23972. /**
  23973. * The list of morph target managers added to the scene
  23974. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23975. */
  23976. this.morphTargetManagers = new Array();
  23977. // Lens flares
  23978. /**
  23979. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23980. */
  23981. this.lensFlaresEnabled = true;
  23982. /**
  23983. * The list of lens flare system added to the scene
  23984. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  23985. */
  23986. this.lensFlareSystems = new Array();
  23987. // Collisions
  23988. /**
  23989. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23990. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23991. */
  23992. this.collisionsEnabled = true;
  23993. /**
  23994. * Defines the gravity applied to this scene (used only for collisions)
  23995. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23996. */
  23997. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23998. // Postprocesses
  23999. /**
  24000. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24001. */
  24002. this.postProcessesEnabled = true;
  24003. /**
  24004. * The list of postprocesses added to the scene
  24005. */
  24006. this.postProcesses = new Array();
  24007. // Customs render targets
  24008. /**
  24009. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24010. */
  24011. this.renderTargetsEnabled = true;
  24012. /**
  24013. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24014. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24015. */
  24016. this.dumpNextRenderTargets = false;
  24017. /**
  24018. * The list of user defined render targets added to the scene
  24019. */
  24020. this.customRenderTargets = new Array();
  24021. /**
  24022. * Gets the list of meshes imported to the scene through SceneLoader
  24023. */
  24024. this.importedMeshesFiles = new Array();
  24025. // Probes
  24026. /**
  24027. * Gets or sets a boolean indicating if probes are enabled on this scene
  24028. */
  24029. this.probesEnabled = true;
  24030. /**
  24031. * The list of reflection probes added to the scene
  24032. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24033. */
  24034. this.reflectionProbes = new Array();
  24035. /** @hidden */
  24036. this._actionManagers = new Array();
  24037. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24038. // Procedural textures
  24039. /**
  24040. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24041. */
  24042. this.proceduralTexturesEnabled = true;
  24043. /**
  24044. * The list of procedural textures added to the scene
  24045. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24046. */
  24047. this.proceduralTextures = new Array();
  24048. /**
  24049. * The list of sound tracks added to the scene
  24050. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24051. */
  24052. this.soundTracks = new Array();
  24053. this._audioEnabled = true;
  24054. this._headphone = false;
  24055. // Performance counters
  24056. this._totalVertices = new BABYLON.PerfCounter();
  24057. /** @hidden */
  24058. this._activeIndices = new BABYLON.PerfCounter();
  24059. /** @hidden */
  24060. this._activeParticles = new BABYLON.PerfCounter();
  24061. /** @hidden */
  24062. this._activeBones = new BABYLON.PerfCounter();
  24063. this._animationTime = 0;
  24064. /**
  24065. * Gets or sets a general scale for animation speed
  24066. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24067. */
  24068. this.animationTimeScale = 1;
  24069. this._renderId = 0;
  24070. this._executeWhenReadyTimeoutId = -1;
  24071. this._intermediateRendering = false;
  24072. this._viewUpdateFlag = -1;
  24073. this._projectionUpdateFlag = -1;
  24074. this._alternateViewUpdateFlag = -1;
  24075. this._alternateProjectionUpdateFlag = -1;
  24076. /** @hidden */
  24077. this._toBeDisposed = new BABYLON.SmartArray(256);
  24078. this._activeRequests = new Array();
  24079. this._pendingData = new Array();
  24080. this._isDisposed = false;
  24081. /**
  24082. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24083. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24084. */
  24085. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24086. this._activeMeshes = new BABYLON.SmartArray(256);
  24087. this._processedMaterials = new BABYLON.SmartArray(256);
  24088. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24089. /** @hidden */
  24090. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24091. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24092. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24093. /** @hidden */
  24094. this._activeAnimatables = new Array();
  24095. this._transformMatrix = BABYLON.Matrix.Zero();
  24096. this._useAlternateCameraConfiguration = false;
  24097. this._alternateRendering = false;
  24098. /**
  24099. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24100. * This is useful if there are more lights that the maximum simulteanous authorized
  24101. */
  24102. this.requireLightSorting = false;
  24103. this._depthRenderer = {};
  24104. this._activeMeshesFrozen = false;
  24105. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24106. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24107. this._engine.scenes.push(this);
  24108. this._uid = null;
  24109. this._renderingManager = new BABYLON.RenderingManager(this);
  24110. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24111. if (BABYLON.OutlineRenderer) {
  24112. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24113. }
  24114. if (BABYLON.Tools.IsWindowObjectExist()) {
  24115. this.attachControl();
  24116. }
  24117. //simplification queue
  24118. if (BABYLON.SimplificationQueue) {
  24119. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24120. }
  24121. //collision coordinator initialization. For now legacy per default.
  24122. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24123. // Uniform Buffer
  24124. this._createUbo();
  24125. // Default Image processing definition.
  24126. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24127. }
  24128. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24129. /** The fog is deactivated */
  24130. get: function () {
  24131. return Scene._FOGMODE_NONE;
  24132. },
  24133. enumerable: true,
  24134. configurable: true
  24135. });
  24136. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24137. /** The fog density is following an exponential function */
  24138. get: function () {
  24139. return Scene._FOGMODE_EXP;
  24140. },
  24141. enumerable: true,
  24142. configurable: true
  24143. });
  24144. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24145. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24146. get: function () {
  24147. return Scene._FOGMODE_EXP2;
  24148. },
  24149. enumerable: true,
  24150. configurable: true
  24151. });
  24152. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24153. /** The fog density is following a linear function. */
  24154. get: function () {
  24155. return Scene._FOGMODE_LINEAR;
  24156. },
  24157. enumerable: true,
  24158. configurable: true
  24159. });
  24160. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24161. /**
  24162. * Texture used in all pbr material as the reflection texture.
  24163. * As in the majority of the scene they are the same (exception for multi room and so on),
  24164. * this is easier to reference from here than from all the materials.
  24165. */
  24166. get: function () {
  24167. return this._environmentTexture;
  24168. },
  24169. /**
  24170. * Texture used in all pbr material as the reflection texture.
  24171. * As in the majority of the scene they are the same (exception for multi room and so on),
  24172. * this is easier to set here than in all the materials.
  24173. */
  24174. set: function (value) {
  24175. if (this._environmentTexture === value) {
  24176. return;
  24177. }
  24178. this._environmentTexture = value;
  24179. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24180. },
  24181. enumerable: true,
  24182. configurable: true
  24183. });
  24184. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24185. /**
  24186. * Default image processing configuration used either in the rendering
  24187. * Forward main pass or through the imageProcessingPostProcess if present.
  24188. * As in the majority of the scene they are the same (exception for multi camera),
  24189. * this is easier to reference from here than from all the materials and post process.
  24190. *
  24191. * No setter as we it is a shared configuration, you can set the values instead.
  24192. */
  24193. get: function () {
  24194. return this._imageProcessingConfiguration;
  24195. },
  24196. enumerable: true,
  24197. configurable: true
  24198. });
  24199. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24200. get: function () {
  24201. return this._forceWireframe;
  24202. },
  24203. /**
  24204. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24205. */
  24206. set: function (value) {
  24207. if (this._forceWireframe === value) {
  24208. return;
  24209. }
  24210. this._forceWireframe = value;
  24211. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24212. },
  24213. enumerable: true,
  24214. configurable: true
  24215. });
  24216. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24217. get: function () {
  24218. return this._forcePointsCloud;
  24219. },
  24220. /**
  24221. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24222. */
  24223. set: function (value) {
  24224. if (this._forcePointsCloud === value) {
  24225. return;
  24226. }
  24227. this._forcePointsCloud = value;
  24228. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24229. },
  24230. enumerable: true,
  24231. configurable: true
  24232. });
  24233. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24234. /**
  24235. * Gets or sets the animation properties override
  24236. */
  24237. get: function () {
  24238. return this._animationPropertiesOverride;
  24239. },
  24240. set: function (value) {
  24241. this._animationPropertiesOverride = value;
  24242. },
  24243. enumerable: true,
  24244. configurable: true
  24245. });
  24246. Object.defineProperty(Scene.prototype, "onDispose", {
  24247. /** Sets a function to be executed when this scene is disposed. */
  24248. set: function (callback) {
  24249. if (this._onDisposeObserver) {
  24250. this.onDisposeObservable.remove(this._onDisposeObserver);
  24251. }
  24252. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24253. },
  24254. enumerable: true,
  24255. configurable: true
  24256. });
  24257. Object.defineProperty(Scene.prototype, "beforeRender", {
  24258. /** Sets a function to be executed before rendering this scene */
  24259. set: function (callback) {
  24260. if (this._onBeforeRenderObserver) {
  24261. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24262. }
  24263. if (callback) {
  24264. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24265. }
  24266. },
  24267. enumerable: true,
  24268. configurable: true
  24269. });
  24270. Object.defineProperty(Scene.prototype, "afterRender", {
  24271. /** Sets a function to be executed after rendering this scene */
  24272. set: function (callback) {
  24273. if (this._onAfterRenderObserver) {
  24274. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24275. }
  24276. if (callback) {
  24277. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24278. }
  24279. },
  24280. enumerable: true,
  24281. configurable: true
  24282. });
  24283. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24284. /** Sets a function to be executed before rendering a camera*/
  24285. set: function (callback) {
  24286. if (this._onBeforeCameraRenderObserver) {
  24287. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24288. }
  24289. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24290. },
  24291. enumerable: true,
  24292. configurable: true
  24293. });
  24294. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24295. /** Sets a function to be executed after rendering a camera*/
  24296. set: function (callback) {
  24297. if (this._onAfterCameraRenderObserver) {
  24298. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24299. }
  24300. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24301. },
  24302. enumerable: true,
  24303. configurable: true
  24304. });
  24305. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24306. /**
  24307. * Gets the gamepad manager associated with the scene
  24308. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24309. */
  24310. get: function () {
  24311. if (!this._gamepadManager) {
  24312. this._gamepadManager = new BABYLON.GamepadManager(this);
  24313. }
  24314. return this._gamepadManager;
  24315. },
  24316. enumerable: true,
  24317. configurable: true
  24318. });
  24319. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24320. /**
  24321. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24322. */
  24323. get: function () {
  24324. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24325. },
  24326. enumerable: true,
  24327. configurable: true
  24328. });
  24329. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24330. get: function () {
  24331. return this._useRightHandedSystem;
  24332. },
  24333. /**
  24334. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24335. */
  24336. set: function (value) {
  24337. if (this._useRightHandedSystem === value) {
  24338. return;
  24339. }
  24340. this._useRightHandedSystem = value;
  24341. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24342. },
  24343. enumerable: true,
  24344. configurable: true
  24345. });
  24346. /**
  24347. * Sets the step Id used by deterministic lock step
  24348. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24349. * @param newStepId defines the step Id
  24350. */
  24351. Scene.prototype.setStepId = function (newStepId) {
  24352. this._currentStepId = newStepId;
  24353. };
  24354. ;
  24355. /**
  24356. * Gets the step Id used by deterministic lock step
  24357. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24358. * @returns the step Id
  24359. */
  24360. Scene.prototype.getStepId = function () {
  24361. return this._currentStepId;
  24362. };
  24363. ;
  24364. /**
  24365. * Gets the internal step used by deterministic lock step
  24366. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24367. * @returns the internal step
  24368. */
  24369. Scene.prototype.getInternalStep = function () {
  24370. return this._currentInternalStep;
  24371. };
  24372. ;
  24373. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24374. get: function () {
  24375. return this._fogEnabled;
  24376. },
  24377. /**
  24378. * Gets or sets a boolean indicating if fog is enabled on this scene
  24379. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24380. */
  24381. set: function (value) {
  24382. if (this._fogEnabled === value) {
  24383. return;
  24384. }
  24385. this._fogEnabled = value;
  24386. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24387. },
  24388. enumerable: true,
  24389. configurable: true
  24390. });
  24391. Object.defineProperty(Scene.prototype, "fogMode", {
  24392. get: function () {
  24393. return this._fogMode;
  24394. },
  24395. /**
  24396. * Gets or sets the fog mode to use
  24397. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24398. */
  24399. set: function (value) {
  24400. if (this._fogMode === value) {
  24401. return;
  24402. }
  24403. this._fogMode = value;
  24404. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24405. },
  24406. enumerable: true,
  24407. configurable: true
  24408. });
  24409. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24410. get: function () {
  24411. return this._shadowsEnabled;
  24412. },
  24413. /**
  24414. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24415. */
  24416. set: function (value) {
  24417. if (this._shadowsEnabled === value) {
  24418. return;
  24419. }
  24420. this._shadowsEnabled = value;
  24421. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24422. },
  24423. enumerable: true,
  24424. configurable: true
  24425. });
  24426. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24427. get: function () {
  24428. return this._lightsEnabled;
  24429. },
  24430. /**
  24431. * Gets or sets a boolean indicating if lights are enabled on this scene
  24432. */
  24433. set: function (value) {
  24434. if (this._lightsEnabled === value) {
  24435. return;
  24436. }
  24437. this._lightsEnabled = value;
  24438. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24439. },
  24440. enumerable: true,
  24441. configurable: true
  24442. });
  24443. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24444. /** The default material used on meshes when no material is affected */
  24445. get: function () {
  24446. if (!this._defaultMaterial) {
  24447. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24448. }
  24449. return this._defaultMaterial;
  24450. },
  24451. /** The default material used on meshes when no material is affected */
  24452. set: function (value) {
  24453. this._defaultMaterial = value;
  24454. },
  24455. enumerable: true,
  24456. configurable: true
  24457. });
  24458. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24459. get: function () {
  24460. return this._texturesEnabled;
  24461. },
  24462. /**
  24463. * Gets or sets a boolean indicating if textures are enabled on this scene
  24464. */
  24465. set: function (value) {
  24466. if (this._texturesEnabled === value) {
  24467. return;
  24468. }
  24469. this._texturesEnabled = value;
  24470. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24471. },
  24472. enumerable: true,
  24473. configurable: true
  24474. });
  24475. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24476. get: function () {
  24477. return this._skeletonsEnabled;
  24478. },
  24479. /**
  24480. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24481. */
  24482. set: function (value) {
  24483. if (this._skeletonsEnabled === value) {
  24484. return;
  24485. }
  24486. this._skeletonsEnabled = value;
  24487. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24488. },
  24489. enumerable: true,
  24490. configurable: true
  24491. });
  24492. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24493. /**
  24494. * Gets the postprocess render pipeline manager
  24495. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24496. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24497. */
  24498. get: function () {
  24499. if (!this._postProcessRenderPipelineManager) {
  24500. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24501. }
  24502. return this._postProcessRenderPipelineManager;
  24503. },
  24504. enumerable: true,
  24505. configurable: true
  24506. });
  24507. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24508. /**
  24509. * Gets the main soundtrack associated with the scene
  24510. */
  24511. get: function () {
  24512. if (!this._mainSoundTrack) {
  24513. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24514. }
  24515. return this._mainSoundTrack;
  24516. },
  24517. enumerable: true,
  24518. configurable: true
  24519. });
  24520. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24521. /** @hidden */
  24522. get: function () {
  24523. return this._alternateRendering;
  24524. },
  24525. enumerable: true,
  24526. configurable: true
  24527. });
  24528. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24529. /**
  24530. * Gets the list of frustum planes (built from the active camera)
  24531. */
  24532. get: function () {
  24533. return this._frustumPlanes;
  24534. },
  24535. enumerable: true,
  24536. configurable: true
  24537. });
  24538. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24539. /**
  24540. * Gets the current geometry buffer associated to the scene.
  24541. */
  24542. get: function () {
  24543. return this._geometryBufferRenderer;
  24544. },
  24545. /**
  24546. * Sets the current geometry buffer for the scene.
  24547. */
  24548. set: function (geometryBufferRenderer) {
  24549. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24550. this._geometryBufferRenderer = geometryBufferRenderer;
  24551. }
  24552. },
  24553. enumerable: true,
  24554. configurable: true
  24555. });
  24556. Object.defineProperty(Scene.prototype, "debugLayer", {
  24557. /**
  24558. * Gets the debug layer associated with the scene
  24559. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24560. */
  24561. get: function () {
  24562. if (!this._debugLayer) {
  24563. this._debugLayer = new BABYLON.DebugLayer(this);
  24564. }
  24565. return this._debugLayer;
  24566. },
  24567. enumerable: true,
  24568. configurable: true
  24569. });
  24570. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24571. /**
  24572. * Gets a boolean indicating if collisions are processed on a web worker
  24573. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24574. */
  24575. get: function () {
  24576. return this._workerCollisions;
  24577. },
  24578. set: function (enabled) {
  24579. if (!BABYLON.CollisionCoordinatorLegacy) {
  24580. return;
  24581. }
  24582. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24583. this._workerCollisions = enabled;
  24584. if (this.collisionCoordinator) {
  24585. this.collisionCoordinator.destroy();
  24586. }
  24587. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24588. this.collisionCoordinator.init(this);
  24589. },
  24590. enumerable: true,
  24591. configurable: true
  24592. });
  24593. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24594. /**
  24595. * Gets the octree used to boost mesh selection (picking)
  24596. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24597. */
  24598. get: function () {
  24599. return this._selectionOctree;
  24600. },
  24601. enumerable: true,
  24602. configurable: true
  24603. });
  24604. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24605. /**
  24606. * Gets the mesh that is currently under the pointer
  24607. */
  24608. get: function () {
  24609. return this._pointerOverMesh;
  24610. },
  24611. enumerable: true,
  24612. configurable: true
  24613. });
  24614. Object.defineProperty(Scene.prototype, "pointerX", {
  24615. /**
  24616. * Gets the current on-screen X position of the pointer
  24617. */
  24618. get: function () {
  24619. return this._pointerX;
  24620. },
  24621. enumerable: true,
  24622. configurable: true
  24623. });
  24624. Object.defineProperty(Scene.prototype, "pointerY", {
  24625. /**
  24626. * Gets the current on-screen Y position of the pointer
  24627. */
  24628. get: function () {
  24629. return this._pointerY;
  24630. },
  24631. enumerable: true,
  24632. configurable: true
  24633. });
  24634. /**
  24635. * Gets the cached material (ie. the latest rendered one)
  24636. * @returns the cached material
  24637. */
  24638. Scene.prototype.getCachedMaterial = function () {
  24639. return this._cachedMaterial;
  24640. };
  24641. /**
  24642. * Gets the cached effect (ie. the latest rendered one)
  24643. * @returns the cached effect
  24644. */
  24645. Scene.prototype.getCachedEffect = function () {
  24646. return this._cachedEffect;
  24647. };
  24648. /**
  24649. * Gets the cached visibility state (ie. the latest rendered one)
  24650. * @returns the cached visibility state
  24651. */
  24652. Scene.prototype.getCachedVisibility = function () {
  24653. return this._cachedVisibility;
  24654. };
  24655. /**
  24656. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24657. * @param material defines the current material
  24658. * @param effect defines the current effect
  24659. * @param visibility defines the current visibility state
  24660. * @returns true if one parameter is not cached
  24661. */
  24662. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24663. if (visibility === void 0) { visibility = 1; }
  24664. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24665. };
  24666. /**
  24667. * Gets the bounding box renderer associated with the scene
  24668. * @returns a BoundingBoxRenderer
  24669. */
  24670. Scene.prototype.getBoundingBoxRenderer = function () {
  24671. if (!this._boundingBoxRenderer) {
  24672. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24673. }
  24674. return this._boundingBoxRenderer;
  24675. };
  24676. /**
  24677. * Gets the outline renderer associated with the scene
  24678. * @returns a OutlineRenderer
  24679. */
  24680. Scene.prototype.getOutlineRenderer = function () {
  24681. return this._outlineRenderer;
  24682. };
  24683. /**
  24684. * Gets the engine associated with the scene
  24685. * @returns an Engine
  24686. */
  24687. Scene.prototype.getEngine = function () {
  24688. return this._engine;
  24689. };
  24690. /**
  24691. * Gets the total number of vertices rendered per frame
  24692. * @returns the total number of vertices rendered per frame
  24693. */
  24694. Scene.prototype.getTotalVertices = function () {
  24695. return this._totalVertices.current;
  24696. };
  24697. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24698. /**
  24699. * Gets the performance counter for total vertices
  24700. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24701. */
  24702. get: function () {
  24703. return this._totalVertices;
  24704. },
  24705. enumerable: true,
  24706. configurable: true
  24707. });
  24708. /**
  24709. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24710. * @returns the total number of active indices rendered per frame
  24711. */
  24712. Scene.prototype.getActiveIndices = function () {
  24713. return this._activeIndices.current;
  24714. };
  24715. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24716. /**
  24717. * Gets the performance counter for active indices
  24718. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24719. */
  24720. get: function () {
  24721. return this._activeIndices;
  24722. },
  24723. enumerable: true,
  24724. configurable: true
  24725. });
  24726. /**
  24727. * Gets the total number of active particles rendered per frame
  24728. * @returns the total number of active particles rendered per frame
  24729. */
  24730. Scene.prototype.getActiveParticles = function () {
  24731. return this._activeParticles.current;
  24732. };
  24733. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24734. /**
  24735. * Gets the performance counter for active particles
  24736. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24737. */
  24738. get: function () {
  24739. return this._activeParticles;
  24740. },
  24741. enumerable: true,
  24742. configurable: true
  24743. });
  24744. /**
  24745. * Gets the total number of active bones rendered per frame
  24746. * @returns the total number of active bones rendered per frame
  24747. */
  24748. Scene.prototype.getActiveBones = function () {
  24749. return this._activeBones.current;
  24750. };
  24751. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24752. /**
  24753. * Gets the performance counter for active bones
  24754. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24755. */
  24756. get: function () {
  24757. return this._activeBones;
  24758. },
  24759. enumerable: true,
  24760. configurable: true
  24761. });
  24762. /** @hidden */
  24763. Scene.prototype.getInterFramePerfCounter = function () {
  24764. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24765. return 0;
  24766. };
  24767. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24768. /** @hidden */
  24769. get: function () {
  24770. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24771. return null;
  24772. },
  24773. enumerable: true,
  24774. configurable: true
  24775. });
  24776. /** @hidden */
  24777. Scene.prototype.getLastFrameDuration = function () {
  24778. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24779. return 0;
  24780. };
  24781. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24782. /** @hidden */
  24783. get: function () {
  24784. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24785. return null;
  24786. },
  24787. enumerable: true,
  24788. configurable: true
  24789. });
  24790. /** @hidden */
  24791. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24792. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24793. return 0;
  24794. };
  24795. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24796. /** @hidden */
  24797. get: function () {
  24798. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24799. return null;
  24800. },
  24801. enumerable: true,
  24802. configurable: true
  24803. });
  24804. /**
  24805. * Gets the array of active meshes
  24806. * @returns an array of AbstractMesh
  24807. */
  24808. Scene.prototype.getActiveMeshes = function () {
  24809. return this._activeMeshes;
  24810. };
  24811. /** @hidden */
  24812. Scene.prototype.getRenderTargetsDuration = function () {
  24813. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24814. return 0;
  24815. };
  24816. /** @hidden */
  24817. Scene.prototype.getRenderDuration = function () {
  24818. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24819. return 0;
  24820. };
  24821. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24822. /** @hidden */
  24823. get: function () {
  24824. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24825. return null;
  24826. },
  24827. enumerable: true,
  24828. configurable: true
  24829. });
  24830. /** @hidden */
  24831. Scene.prototype.getParticlesDuration = function () {
  24832. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24833. return 0;
  24834. };
  24835. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24836. /** @hidden */
  24837. get: function () {
  24838. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24839. return null;
  24840. },
  24841. enumerable: true,
  24842. configurable: true
  24843. });
  24844. /** @hidden */
  24845. Scene.prototype.getSpritesDuration = function () {
  24846. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24847. return 0;
  24848. };
  24849. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24850. /** @hidden */
  24851. get: function () {
  24852. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24853. return null;
  24854. },
  24855. enumerable: true,
  24856. configurable: true
  24857. });
  24858. /**
  24859. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24860. * @returns a number
  24861. */
  24862. Scene.prototype.getAnimationRatio = function () {
  24863. return this._animationRatio;
  24864. };
  24865. /**
  24866. * Gets an unique Id for the current frame
  24867. * @returns a number
  24868. */
  24869. Scene.prototype.getRenderId = function () {
  24870. return this._renderId;
  24871. };
  24872. /** Call this function if you want to manually increment the render Id*/
  24873. Scene.prototype.incrementRenderId = function () {
  24874. this._renderId++;
  24875. };
  24876. Scene.prototype._updatePointerPosition = function (evt) {
  24877. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24878. if (!canvasRect) {
  24879. return;
  24880. }
  24881. this._pointerX = evt.clientX - canvasRect.left;
  24882. this._pointerY = evt.clientY - canvasRect.top;
  24883. this._unTranslatedPointerX = this._pointerX;
  24884. this._unTranslatedPointerY = this._pointerY;
  24885. };
  24886. Scene.prototype._createUbo = function () {
  24887. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24888. this._sceneUbo.addUniform("viewProjection", 16);
  24889. this._sceneUbo.addUniform("view", 16);
  24890. };
  24891. Scene.prototype._createAlternateUbo = function () {
  24892. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24893. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24894. this._alternateSceneUbo.addUniform("view", 16);
  24895. };
  24896. // Pointers handling
  24897. /**
  24898. * Use this method to simulate a pointer move on a mesh
  24899. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24900. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24901. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24902. * @returns the current scene
  24903. */
  24904. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24905. var evt = new PointerEvent("pointermove", pointerEventInit);
  24906. return this._processPointerMove(pickResult, evt);
  24907. };
  24908. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24909. var canvas = this._engine.getRenderingCanvas();
  24910. if (!canvas) {
  24911. return this;
  24912. }
  24913. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24914. this.setPointerOverSprite(null);
  24915. this.setPointerOverMesh(pickResult.pickedMesh);
  24916. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24917. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24918. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24919. }
  24920. else {
  24921. canvas.style.cursor = this.hoverCursor;
  24922. }
  24923. }
  24924. else {
  24925. canvas.style.cursor = this.defaultCursor;
  24926. }
  24927. }
  24928. else {
  24929. this.setPointerOverMesh(null);
  24930. // Sprites
  24931. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24932. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24933. this.setPointerOverSprite(pickResult.pickedSprite);
  24934. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24935. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24936. }
  24937. else {
  24938. canvas.style.cursor = this.hoverCursor;
  24939. }
  24940. }
  24941. else {
  24942. this.setPointerOverSprite(null);
  24943. // Restore pointer
  24944. canvas.style.cursor = this.defaultCursor;
  24945. }
  24946. }
  24947. if (pickResult) {
  24948. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24949. if (this.onPointerMove) {
  24950. this.onPointerMove(evt, pickResult, type);
  24951. }
  24952. if (this.onPointerObservable.hasObservers()) {
  24953. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24954. this.onPointerObservable.notifyObservers(pi, type);
  24955. }
  24956. }
  24957. return this;
  24958. };
  24959. /**
  24960. * Use this method to simulate a pointer down on a mesh
  24961. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24962. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24963. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24964. * @returns the current scene
  24965. */
  24966. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24967. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24968. return this._processPointerDown(pickResult, evt);
  24969. };
  24970. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24971. var _this = this;
  24972. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24973. this._pickedDownMesh = pickResult.pickedMesh;
  24974. var actionManager = pickResult.pickedMesh.actionManager;
  24975. if (actionManager) {
  24976. if (actionManager.hasPickTriggers) {
  24977. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24978. switch (evt.button) {
  24979. case 0:
  24980. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24981. break;
  24982. case 1:
  24983. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24984. break;
  24985. case 2:
  24986. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24987. break;
  24988. }
  24989. }
  24990. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  24991. window.setTimeout(function () {
  24992. 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);
  24993. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  24994. if (_this._totalPointersPressed !== 0 &&
  24995. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  24996. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  24997. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  24998. _this._startingPointerTime = 0;
  24999. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25000. }
  25001. }
  25002. }, Scene.LongPressDelay);
  25003. }
  25004. }
  25005. }
  25006. if (pickResult) {
  25007. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25008. if (this.onPointerDown) {
  25009. this.onPointerDown(evt, pickResult, type);
  25010. }
  25011. if (this.onPointerObservable.hasObservers()) {
  25012. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25013. this.onPointerObservable.notifyObservers(pi, type);
  25014. }
  25015. }
  25016. return this;
  25017. };
  25018. /**
  25019. * Use this method to simulate a pointer up on a mesh
  25020. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25021. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25022. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25023. * @returns the current scene
  25024. */
  25025. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25026. var evt = new PointerEvent("pointerup", pointerEventInit);
  25027. var clickInfo = new ClickInfo();
  25028. clickInfo.singleClick = true;
  25029. clickInfo.ignore = true;
  25030. return this._processPointerUp(pickResult, evt, clickInfo);
  25031. };
  25032. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25033. if (pickResult && pickResult && pickResult.pickedMesh) {
  25034. this._pickedUpMesh = pickResult.pickedMesh;
  25035. if (this._pickedDownMesh === this._pickedUpMesh) {
  25036. if (this.onPointerPick) {
  25037. this.onPointerPick(evt, pickResult);
  25038. }
  25039. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25040. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25041. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25042. this.onPointerObservable.notifyObservers(pi, type_1);
  25043. }
  25044. }
  25045. if (pickResult.pickedMesh.actionManager) {
  25046. if (clickInfo.ignore) {
  25047. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25048. }
  25049. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25050. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25051. }
  25052. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25053. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25054. }
  25055. }
  25056. }
  25057. if (this._pickedDownMesh &&
  25058. this._pickedDownMesh.actionManager &&
  25059. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25060. this._pickedDownMesh !== this._pickedUpMesh) {
  25061. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25062. }
  25063. var type = BABYLON.PointerEventTypes.POINTERUP;
  25064. if (this.onPointerObservable.hasObservers()) {
  25065. if (!clickInfo.ignore) {
  25066. if (!clickInfo.hasSwiped) {
  25067. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25068. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25069. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25070. this.onPointerObservable.notifyObservers(pi, type_2);
  25071. }
  25072. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25073. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25074. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25075. this.onPointerObservable.notifyObservers(pi, type_3);
  25076. }
  25077. }
  25078. }
  25079. else {
  25080. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25081. this.onPointerObservable.notifyObservers(pi, type);
  25082. }
  25083. }
  25084. if (this.onPointerUp) {
  25085. this.onPointerUp(evt, pickResult, type);
  25086. }
  25087. return this;
  25088. };
  25089. /**
  25090. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25091. * @param attachUp defines if you want to attach events to pointerup
  25092. * @param attachDown defines if you want to attach events to pointerdown
  25093. * @param attachMove defines if you want to attach events to pointermove
  25094. */
  25095. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25096. var _this = this;
  25097. if (attachUp === void 0) { attachUp = true; }
  25098. if (attachDown === void 0) { attachDown = true; }
  25099. if (attachMove === void 0) { attachMove = true; }
  25100. this._initActionManager = function (act, clickInfo) {
  25101. if (!_this._meshPickProceed) {
  25102. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25103. _this._currentPickResult = pickResult;
  25104. if (pickResult) {
  25105. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25106. }
  25107. _this._meshPickProceed = true;
  25108. }
  25109. return act;
  25110. };
  25111. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25112. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25113. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25114. btn !== _this._previousButtonPressed) {
  25115. _this._doubleClickOccured = false;
  25116. clickInfo.singleClick = true;
  25117. clickInfo.ignore = false;
  25118. cb(clickInfo, _this._currentPickResult);
  25119. }
  25120. };
  25121. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25122. var clickInfo = new ClickInfo();
  25123. _this._currentPickResult = null;
  25124. var act = null;
  25125. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25126. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25127. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25128. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25129. act = _this._initActionManager(act, clickInfo);
  25130. if (act)
  25131. checkPicking = act.hasPickTriggers;
  25132. }
  25133. if (checkPicking) {
  25134. var btn = evt.button;
  25135. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25136. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25137. if (!clickInfo.hasSwiped) {
  25138. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25139. if (!checkSingleClickImmediately) {
  25140. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25141. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25142. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25143. act = _this._initActionManager(act, clickInfo);
  25144. if (act)
  25145. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25146. }
  25147. }
  25148. if (checkSingleClickImmediately) {
  25149. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25150. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25151. btn !== _this._previousButtonPressed) {
  25152. clickInfo.singleClick = true;
  25153. cb(clickInfo, _this._currentPickResult);
  25154. }
  25155. }
  25156. // at least one double click is required to be check and exclusive double click is enabled
  25157. else {
  25158. // wait that no double click has been raised during the double click delay
  25159. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25160. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25161. }
  25162. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25163. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25164. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25165. act = _this._initActionManager(act, clickInfo);
  25166. if (act)
  25167. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25168. }
  25169. if (checkDoubleClick) {
  25170. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25171. if (btn === _this._previousButtonPressed &&
  25172. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25173. !_this._doubleClickOccured) {
  25174. // pointer has not moved for 2 clicks, it's a double click
  25175. if (!clickInfo.hasSwiped &&
  25176. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25177. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25178. _this._previousStartingPointerTime = 0;
  25179. _this._doubleClickOccured = true;
  25180. clickInfo.doubleClick = true;
  25181. clickInfo.ignore = false;
  25182. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25183. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25184. }
  25185. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25186. cb(clickInfo, _this._currentPickResult);
  25187. }
  25188. // if the two successive clicks are too far, it's just two simple clicks
  25189. else {
  25190. _this._doubleClickOccured = false;
  25191. _this._previousStartingPointerTime = _this._startingPointerTime;
  25192. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25193. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25194. _this._previousButtonPressed = btn;
  25195. if (Scene.ExclusiveDoubleClickMode) {
  25196. if (_this._previousDelayedSimpleClickTimeout) {
  25197. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25198. }
  25199. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25200. cb(clickInfo, _this._previousPickResult);
  25201. }
  25202. else {
  25203. cb(clickInfo, _this._currentPickResult);
  25204. }
  25205. }
  25206. }
  25207. // just the first click of the double has been raised
  25208. else {
  25209. _this._doubleClickOccured = false;
  25210. _this._previousStartingPointerTime = _this._startingPointerTime;
  25211. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25212. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25213. _this._previousButtonPressed = btn;
  25214. }
  25215. }
  25216. }
  25217. }
  25218. clickInfo.ignore = true;
  25219. cb(clickInfo, _this._currentPickResult);
  25220. };
  25221. this._spritePredicate = function (sprite) {
  25222. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25223. };
  25224. this._onPointerMove = function (evt) {
  25225. _this._updatePointerPosition(evt);
  25226. // PreObservable support
  25227. if (_this.onPrePointerObservable.hasObservers()) {
  25228. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25229. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25230. _this.onPrePointerObservable.notifyObservers(pi, type);
  25231. if (pi.skipOnPointerObservable) {
  25232. return;
  25233. }
  25234. }
  25235. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25236. return;
  25237. }
  25238. if (!_this.pointerMovePredicate) {
  25239. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25240. }
  25241. // Meshes
  25242. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25243. _this._processPointerMove(pickResult, evt);
  25244. };
  25245. this._onPointerDown = function (evt) {
  25246. _this._totalPointersPressed++;
  25247. _this._pickedDownMesh = null;
  25248. _this._meshPickProceed = false;
  25249. _this._updatePointerPosition(evt);
  25250. if (_this.preventDefaultOnPointerDown && canvas) {
  25251. evt.preventDefault();
  25252. canvas.focus();
  25253. }
  25254. // PreObservable support
  25255. if (_this.onPrePointerObservable.hasObservers()) {
  25256. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25257. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25258. _this.onPrePointerObservable.notifyObservers(pi, type);
  25259. if (pi.skipOnPointerObservable) {
  25260. return;
  25261. }
  25262. }
  25263. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25264. return;
  25265. }
  25266. _this._startingPointerPosition.x = _this._pointerX;
  25267. _this._startingPointerPosition.y = _this._pointerY;
  25268. _this._startingPointerTime = Date.now();
  25269. if (!_this.pointerDownPredicate) {
  25270. _this.pointerDownPredicate = function (mesh) {
  25271. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25272. };
  25273. }
  25274. // Meshes
  25275. _this._pickedDownMesh = null;
  25276. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25277. _this._processPointerDown(pickResult, evt);
  25278. // Sprites
  25279. _this._pickedDownSprite = null;
  25280. if (_this.spriteManagers.length > 0) {
  25281. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25282. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25283. if (pickResult.pickedSprite.actionManager) {
  25284. _this._pickedDownSprite = pickResult.pickedSprite;
  25285. switch (evt.button) {
  25286. case 0:
  25287. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25288. break;
  25289. case 1:
  25290. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25291. break;
  25292. case 2:
  25293. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25294. break;
  25295. }
  25296. if (pickResult.pickedSprite.actionManager) {
  25297. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25298. }
  25299. }
  25300. }
  25301. }
  25302. };
  25303. this._onPointerUp = function (evt) {
  25304. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25305. return; // So we need to test it the pointer down was pressed before.
  25306. }
  25307. _this._totalPointersPressed--;
  25308. _this._pickedUpMesh = null;
  25309. _this._meshPickProceed = false;
  25310. _this._updatePointerPosition(evt);
  25311. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25312. // PreObservable support
  25313. if (_this.onPrePointerObservable.hasObservers()) {
  25314. if (!clickInfo.ignore) {
  25315. if (!clickInfo.hasSwiped) {
  25316. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25317. var type = BABYLON.PointerEventTypes.POINTERTAP;
  25318. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25319. _this.onPrePointerObservable.notifyObservers(pi, type);
  25320. if (pi.skipOnPointerObservable) {
  25321. return;
  25322. }
  25323. }
  25324. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25325. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25326. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25327. _this.onPrePointerObservable.notifyObservers(pi, type);
  25328. if (pi.skipOnPointerObservable) {
  25329. return;
  25330. }
  25331. }
  25332. }
  25333. }
  25334. else {
  25335. var type = BABYLON.PointerEventTypes.POINTERUP;
  25336. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25337. _this.onPrePointerObservable.notifyObservers(pi, type);
  25338. if (pi.skipOnPointerObservable) {
  25339. return;
  25340. }
  25341. }
  25342. }
  25343. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25344. return;
  25345. }
  25346. if (!_this.pointerUpPredicate) {
  25347. _this.pointerUpPredicate = function (mesh) {
  25348. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25349. };
  25350. }
  25351. // Meshes
  25352. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25353. _this._initActionManager(null, clickInfo);
  25354. }
  25355. if (!pickResult) {
  25356. pickResult = _this._currentPickResult;
  25357. }
  25358. _this._processPointerUp(pickResult, evt, clickInfo);
  25359. // Sprites
  25360. if (_this.spriteManagers.length > 0) {
  25361. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25362. if (spritePickResult) {
  25363. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25364. if (spritePickResult.pickedSprite.actionManager) {
  25365. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25366. if (spritePickResult.pickedSprite.actionManager) {
  25367. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25368. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25369. }
  25370. }
  25371. }
  25372. }
  25373. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25374. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25375. }
  25376. }
  25377. }
  25378. _this._previousPickResult = _this._currentPickResult;
  25379. });
  25380. };
  25381. this._onKeyDown = function (evt) {
  25382. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25383. if (_this.onPreKeyboardObservable.hasObservers()) {
  25384. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25385. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25386. if (pi.skipOnPointerObservable) {
  25387. return;
  25388. }
  25389. }
  25390. if (_this.onKeyboardObservable.hasObservers()) {
  25391. var pi = new BABYLON.KeyboardInfo(type, evt);
  25392. _this.onKeyboardObservable.notifyObservers(pi, type);
  25393. }
  25394. if (_this.actionManager) {
  25395. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25396. }
  25397. };
  25398. this._onKeyUp = function (evt) {
  25399. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25400. if (_this.onPreKeyboardObservable.hasObservers()) {
  25401. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25402. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25403. if (pi.skipOnPointerObservable) {
  25404. return;
  25405. }
  25406. }
  25407. if (_this.onKeyboardObservable.hasObservers()) {
  25408. var pi = new BABYLON.KeyboardInfo(type, evt);
  25409. _this.onKeyboardObservable.notifyObservers(pi, type);
  25410. }
  25411. if (_this.actionManager) {
  25412. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25413. }
  25414. };
  25415. var engine = this.getEngine();
  25416. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25417. if (!canvas) {
  25418. return;
  25419. }
  25420. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25421. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25422. });
  25423. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25424. if (!canvas) {
  25425. return;
  25426. }
  25427. canvas.removeEventListener("keydown", _this._onKeyDown);
  25428. canvas.removeEventListener("keyup", _this._onKeyUp);
  25429. });
  25430. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25431. var canvas = this._engine.getRenderingCanvas();
  25432. if (!canvas) {
  25433. return;
  25434. }
  25435. if (attachMove) {
  25436. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25437. // Wheel
  25438. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25439. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25440. }
  25441. if (attachDown) {
  25442. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25443. }
  25444. if (attachUp) {
  25445. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25446. }
  25447. canvas.tabIndex = 1;
  25448. };
  25449. /** Detaches all event handlers*/
  25450. Scene.prototype.detachControl = function () {
  25451. var engine = this.getEngine();
  25452. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25453. var canvas = engine.getRenderingCanvas();
  25454. if (!canvas) {
  25455. return;
  25456. }
  25457. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25458. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25459. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25460. if (this._onCanvasBlurObserver) {
  25461. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25462. }
  25463. if (this._onCanvasFocusObserver) {
  25464. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25465. }
  25466. // Wheel
  25467. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25468. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25469. // Keyboard
  25470. canvas.removeEventListener("keydown", this._onKeyDown);
  25471. canvas.removeEventListener("keyup", this._onKeyUp);
  25472. // Observables
  25473. this.onKeyboardObservable.clear();
  25474. this.onPreKeyboardObservable.clear();
  25475. this.onPointerObservable.clear();
  25476. this.onPrePointerObservable.clear();
  25477. };
  25478. /**
  25479. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25480. * Delay loaded resources are not taking in account
  25481. * @return true if all required resources are ready
  25482. */
  25483. Scene.prototype.isReady = function () {
  25484. if (this._isDisposed) {
  25485. return false;
  25486. }
  25487. if (this._pendingData.length > 0) {
  25488. return false;
  25489. }
  25490. var index;
  25491. var engine = this.getEngine();
  25492. // Geometries
  25493. for (index = 0; index < this._geometries.length; index++) {
  25494. var geometry = this._geometries[index];
  25495. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25496. return false;
  25497. }
  25498. }
  25499. // Meshes
  25500. for (index = 0; index < this.meshes.length; index++) {
  25501. var mesh = this.meshes[index];
  25502. if (!mesh.isEnabled()) {
  25503. continue;
  25504. }
  25505. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25506. continue;
  25507. }
  25508. if (!mesh.isReady(true)) {
  25509. return false;
  25510. }
  25511. // Effect layers
  25512. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25513. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25514. var layer = _a[_i];
  25515. if (!layer.hasMesh(mesh)) {
  25516. continue;
  25517. }
  25518. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25519. var subMesh = _c[_b];
  25520. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25521. return false;
  25522. }
  25523. }
  25524. }
  25525. }
  25526. // Post-processes
  25527. if (this.activeCameras && this.activeCameras.length > 0) {
  25528. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25529. var camera = _e[_d];
  25530. if (!camera.isReady(true)) {
  25531. return false;
  25532. }
  25533. }
  25534. }
  25535. else if (this.activeCamera) {
  25536. if (!this.activeCamera.isReady(true)) {
  25537. return false;
  25538. }
  25539. }
  25540. // Particles
  25541. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25542. var particleSystem = _g[_f];
  25543. if (!particleSystem.isReady()) {
  25544. return false;
  25545. }
  25546. }
  25547. return true;
  25548. };
  25549. /** Resets all cached information relative to material (including effect and visibility) */
  25550. Scene.prototype.resetCachedMaterial = function () {
  25551. this._cachedMaterial = null;
  25552. this._cachedEffect = null;
  25553. this._cachedVisibility = null;
  25554. };
  25555. /**
  25556. * Registers a function to be called before every frame render
  25557. * @param func defines the function to register
  25558. */
  25559. Scene.prototype.registerBeforeRender = function (func) {
  25560. this.onBeforeRenderObservable.add(func);
  25561. };
  25562. /**
  25563. * Unregisters a function called before every frame render
  25564. * @param func defines the function to unregister
  25565. */
  25566. Scene.prototype.unregisterBeforeRender = function (func) {
  25567. this.onBeforeRenderObservable.removeCallback(func);
  25568. };
  25569. /**
  25570. * Registers a function to be called after every frame render
  25571. * @param func defines the function to register
  25572. */
  25573. Scene.prototype.registerAfterRender = function (func) {
  25574. this.onAfterRenderObservable.add(func);
  25575. };
  25576. /**
  25577. * Unregisters a function called after every frame render
  25578. * @param func defines the function to unregister
  25579. */
  25580. Scene.prototype.unregisterAfterRender = function (func) {
  25581. this.onAfterRenderObservable.removeCallback(func);
  25582. };
  25583. Scene.prototype._executeOnceBeforeRender = function (func) {
  25584. var _this = this;
  25585. var execFunc = function () {
  25586. func();
  25587. setTimeout(function () {
  25588. _this.unregisterBeforeRender(execFunc);
  25589. });
  25590. };
  25591. this.registerBeforeRender(execFunc);
  25592. };
  25593. /**
  25594. * The provided function will run before render once and will be disposed afterwards.
  25595. * A timeout delay can be provided so that the function will be executed in N ms.
  25596. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25597. * @param func The function to be executed.
  25598. * @param timeout optional delay in ms
  25599. */
  25600. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25601. var _this = this;
  25602. if (timeout !== undefined) {
  25603. setTimeout(function () {
  25604. _this._executeOnceBeforeRender(func);
  25605. }, timeout);
  25606. }
  25607. else {
  25608. this._executeOnceBeforeRender(func);
  25609. }
  25610. };
  25611. /** @hidden */
  25612. Scene.prototype._addPendingData = function (data) {
  25613. this._pendingData.push(data);
  25614. };
  25615. /** @hidden */
  25616. Scene.prototype._removePendingData = function (data) {
  25617. var wasLoading = this.isLoading;
  25618. var index = this._pendingData.indexOf(data);
  25619. if (index !== -1) {
  25620. this._pendingData.splice(index, 1);
  25621. }
  25622. if (wasLoading && !this.isLoading) {
  25623. this.onDataLoadedObservable.notifyObservers(this);
  25624. }
  25625. };
  25626. /**
  25627. * Returns the number of items waiting to be loaded
  25628. * @returns the number of items waiting to be loaded
  25629. */
  25630. Scene.prototype.getWaitingItemsCount = function () {
  25631. return this._pendingData.length;
  25632. };
  25633. Object.defineProperty(Scene.prototype, "isLoading", {
  25634. /**
  25635. * Returns a boolean indicating if the scene is still loading data
  25636. */
  25637. get: function () {
  25638. return this._pendingData.length > 0;
  25639. },
  25640. enumerable: true,
  25641. configurable: true
  25642. });
  25643. /**
  25644. * Registers a function to be executed when the scene is ready
  25645. * @param {Function} func - the function to be executed
  25646. */
  25647. Scene.prototype.executeWhenReady = function (func) {
  25648. var _this = this;
  25649. this.onReadyObservable.add(func);
  25650. if (this._executeWhenReadyTimeoutId !== -1) {
  25651. return;
  25652. }
  25653. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25654. _this._checkIsReady();
  25655. }, 150);
  25656. };
  25657. /**
  25658. * Returns a promise that resolves when the scene is ready
  25659. * @returns A promise that resolves when the scene is ready
  25660. */
  25661. Scene.prototype.whenReadyAsync = function () {
  25662. var _this = this;
  25663. return new Promise(function (resolve) {
  25664. _this.executeWhenReady(function () {
  25665. resolve();
  25666. });
  25667. });
  25668. };
  25669. /** @hidden */
  25670. Scene.prototype._checkIsReady = function () {
  25671. var _this = this;
  25672. if (this.isReady()) {
  25673. this.onReadyObservable.notifyObservers(this);
  25674. this.onReadyObservable.clear();
  25675. this._executeWhenReadyTimeoutId = -1;
  25676. return;
  25677. }
  25678. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25679. _this._checkIsReady();
  25680. }, 150);
  25681. };
  25682. // Animations
  25683. /**
  25684. * Will start the animation sequence of a given target
  25685. * @param target defines the target
  25686. * @param from defines from which frame should animation start
  25687. * @param to defines until which frame should animation run.
  25688. * @param weight defines the weight to apply to the animation (1.0 by default)
  25689. * @param loop defines if the animation loops
  25690. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25691. * @param onAnimationEnd defines the function to be executed when the animation ends
  25692. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25693. * @returns the animatable object created for this animation
  25694. */
  25695. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25696. if (weight === void 0) { weight = 1.0; }
  25697. if (speedRatio === void 0) { speedRatio = 1.0; }
  25698. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25699. returnedAnimatable.weight = weight;
  25700. return returnedAnimatable;
  25701. };
  25702. /**
  25703. * Will start the animation sequence of a given target
  25704. * @param target defines the target
  25705. * @param from defines from which frame should animation start
  25706. * @param to defines until which frame should animation run.
  25707. * @param loop defines if the animation loops
  25708. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25709. * @param onAnimationEnd defines the function to be executed when the animation ends
  25710. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25711. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25712. * @returns the animatable object created for this animation
  25713. */
  25714. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25715. if (speedRatio === void 0) { speedRatio = 1.0; }
  25716. if (stopCurrent === void 0) { stopCurrent = true; }
  25717. if (from > to && speedRatio > 0) {
  25718. speedRatio *= -1;
  25719. }
  25720. if (stopCurrent) {
  25721. this.stopAnimation(target);
  25722. }
  25723. if (!animatable) {
  25724. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25725. }
  25726. // Local animations
  25727. if (target.animations) {
  25728. animatable.appendAnimations(target, target.animations);
  25729. }
  25730. // Children animations
  25731. if (target.getAnimatables) {
  25732. var animatables = target.getAnimatables();
  25733. for (var index = 0; index < animatables.length; index++) {
  25734. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25735. }
  25736. }
  25737. animatable.reset();
  25738. return animatable;
  25739. };
  25740. /**
  25741. * Begin a new animation on a given node
  25742. * @param target defines the target where the animation will take place
  25743. * @param animations defines the list of animations to start
  25744. * @param from defines the initial value
  25745. * @param to defines the final value
  25746. * @param loop defines if you want animation to loop (off by default)
  25747. * @param speedRatio defines the speed ratio to apply to all animations
  25748. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25749. * @returns the list of created animatables
  25750. */
  25751. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25752. if (speedRatio === undefined) {
  25753. speedRatio = 1.0;
  25754. }
  25755. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25756. return animatable;
  25757. };
  25758. /**
  25759. * Begin a new animation on a given node and its hierarchy
  25760. * @param target defines the root node where the animation will take place
  25761. * @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.
  25762. * @param animations defines the list of animations to start
  25763. * @param from defines the initial value
  25764. * @param to defines the final value
  25765. * @param loop defines if you want animation to loop (off by default)
  25766. * @param speedRatio defines the speed ratio to apply to all animations
  25767. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25768. * @returns the list of animatables created for all nodes
  25769. */
  25770. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25771. var children = target.getDescendants(directDescendantsOnly);
  25772. var result = [];
  25773. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25774. var child = children_1[_i];
  25775. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25776. }
  25777. return result;
  25778. };
  25779. /**
  25780. * Gets the animatable associated with a specific target
  25781. * @param target defines the target of the animatable
  25782. * @returns the required animatable if found
  25783. */
  25784. Scene.prototype.getAnimatableByTarget = function (target) {
  25785. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25786. if (this._activeAnimatables[index].target === target) {
  25787. return this._activeAnimatables[index];
  25788. }
  25789. }
  25790. return null;
  25791. };
  25792. /**
  25793. * Gets all animatables associated with a given target
  25794. * @param target defines the target to look animatables for
  25795. * @returns an array of Animatables
  25796. */
  25797. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25798. var result = [];
  25799. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25800. if (this._activeAnimatables[index].target === target) {
  25801. result.push(this._activeAnimatables[index]);
  25802. }
  25803. }
  25804. return result;
  25805. };
  25806. Object.defineProperty(Scene.prototype, "animatables", {
  25807. /**
  25808. * Gets all animatable attached to the scene
  25809. */
  25810. get: function () {
  25811. return this._activeAnimatables;
  25812. },
  25813. enumerable: true,
  25814. configurable: true
  25815. });
  25816. /**
  25817. * Will stop the animation of the given target
  25818. * @param target - the target
  25819. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25820. */
  25821. Scene.prototype.stopAnimation = function (target, animationName) {
  25822. var animatables = this.getAllAnimatablesByTarget(target);
  25823. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25824. var animatable = animatables_1[_i];
  25825. animatable.stop(animationName);
  25826. }
  25827. };
  25828. /**
  25829. * Stops and removes all animations that have been applied to the scene
  25830. */
  25831. Scene.prototype.stopAllAnimations = function () {
  25832. if (this._activeAnimatables) {
  25833. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25834. this._activeAnimatables[i].stop();
  25835. }
  25836. this._activeAnimatables = [];
  25837. }
  25838. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25839. var group = _a[_i];
  25840. group.stop();
  25841. }
  25842. };
  25843. Scene.prototype._animate = function () {
  25844. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25845. return;
  25846. }
  25847. // Getting time
  25848. var now = BABYLON.Tools.Now;
  25849. if (!this._animationTimeLast) {
  25850. if (this._pendingData.length > 0) {
  25851. return;
  25852. }
  25853. this._animationTimeLast = now;
  25854. }
  25855. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25856. this._animationTime += deltaTime;
  25857. this._animationTimeLast = now;
  25858. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25859. this._activeAnimatables[index]._animate(this._animationTime);
  25860. }
  25861. // Late animation bindings
  25862. this._processLateAnimationBindings();
  25863. };
  25864. /** @hidden */
  25865. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  25866. var target = runtimeAnimation.target;
  25867. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25868. if (!target._lateAnimationHolders) {
  25869. target._lateAnimationHolders = {};
  25870. }
  25871. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25872. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25873. totalWeight: 0,
  25874. animations: []
  25875. };
  25876. }
  25877. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25878. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25879. };
  25880. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder, originalValue) {
  25881. var normalizer = 1.0;
  25882. var finalPosition = BABYLON.Tmp.Vector3[0];
  25883. var finalScaling = BABYLON.Tmp.Vector3[1];
  25884. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25885. var startIndex = 0;
  25886. var originalAnimation = holder.animations[0];
  25887. var scale = 1;
  25888. if (holder.totalWeight < 1.0) {
  25889. // We need to mix the original value in
  25890. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25891. scale = 1.0 - holder.totalWeight;
  25892. }
  25893. else {
  25894. startIndex = 1;
  25895. // We need to normalize the weights
  25896. normalizer = holder.totalWeight;
  25897. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25898. scale = originalAnimation.weight / normalizer;
  25899. if (scale == 1) {
  25900. return originalAnimation.currentValue;
  25901. }
  25902. }
  25903. finalScaling.scaleInPlace(scale);
  25904. finalPosition.scaleInPlace(scale);
  25905. finalQuaternion.scaleInPlace(scale);
  25906. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25907. var runtimeAnimation = holder.animations[animIndex];
  25908. var scale = runtimeAnimation.weight / normalizer;
  25909. var currentPosition = BABYLON.Tmp.Vector3[2];
  25910. var currentScaling = BABYLON.Tmp.Vector3[3];
  25911. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25912. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25913. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25914. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25915. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25916. }
  25917. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25918. return originalAnimation._workValue;
  25919. };
  25920. Scene.prototype._processLateAnimationBindings = function () {
  25921. if (!this._registeredForLateAnimationBindings.length) {
  25922. return;
  25923. }
  25924. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  25925. var target = this._registeredForLateAnimationBindings.data[index];
  25926. for (var path in target._lateAnimationHolders) {
  25927. var holder = target._lateAnimationHolders[path];
  25928. var originalAnimation = holder.animations[0];
  25929. var originalValue = originalAnimation.originalValue;
  25930. var finalTarget = originalAnimation.target;
  25931. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  25932. var finalValue = void 0;
  25933. if (matrixDecomposeMode) {
  25934. finalValue = this._processLateAnimationBindingsForMatrices(holder, originalValue);
  25935. }
  25936. else {
  25937. var startIndex = 0;
  25938. var normalizer = 1.0;
  25939. if (holder.totalWeight < 1.0) {
  25940. // We need to mix the original value in
  25941. if (originalValue.scale) {
  25942. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  25943. }
  25944. else {
  25945. finalValue = originalValue * (1.0 - holder.totalWeight);
  25946. }
  25947. }
  25948. else {
  25949. // We need to normalize the weights
  25950. normalizer = holder.totalWeight;
  25951. var scale_1 = originalAnimation.weight / normalizer;
  25952. if (scale_1 !== 1) {
  25953. if (originalAnimation.currentValue.scale) {
  25954. finalValue = originalAnimation.currentValue.scale(scale_1);
  25955. }
  25956. else {
  25957. finalValue = originalAnimation.currentValue * scale_1;
  25958. }
  25959. }
  25960. else {
  25961. finalValue = originalAnimation.currentValue;
  25962. }
  25963. startIndex = 1;
  25964. }
  25965. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25966. var runtimeAnimation = holder.animations[animIndex];
  25967. var scale = runtimeAnimation.weight / normalizer;
  25968. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  25969. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  25970. }
  25971. else {
  25972. finalValue += runtimeAnimation.currentValue * scale;
  25973. }
  25974. }
  25975. }
  25976. finalTarget[path] = finalValue;
  25977. }
  25978. target._lateAnimationHolders = {};
  25979. }
  25980. this._registeredForLateAnimationBindings.reset();
  25981. };
  25982. // Matrix
  25983. /** @hidden */
  25984. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  25985. this._useAlternateCameraConfiguration = active;
  25986. };
  25987. /**
  25988. * Gets the current view matrix
  25989. * @returns a Matrix
  25990. */
  25991. Scene.prototype.getViewMatrix = function () {
  25992. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  25993. };
  25994. /**
  25995. * Gets the current projection matrix
  25996. * @returns a Matrix
  25997. */
  25998. Scene.prototype.getProjectionMatrix = function () {
  25999. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26000. };
  26001. /**
  26002. * Gets the current transform matrix
  26003. * @returns a Matrix made of View * Projection
  26004. */
  26005. Scene.prototype.getTransformMatrix = function () {
  26006. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26007. };
  26008. /**
  26009. * Sets the current transform matrix
  26010. * @param view defines the View matrix to use
  26011. * @param projection defines the Projection matrix to use
  26012. */
  26013. Scene.prototype.setTransformMatrix = function (view, projection) {
  26014. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26015. return;
  26016. }
  26017. this._viewUpdateFlag = view.updateFlag;
  26018. this._projectionUpdateFlag = projection.updateFlag;
  26019. this._viewMatrix = view;
  26020. this._projectionMatrix = projection;
  26021. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26022. // Update frustum
  26023. if (!this._frustumPlanes) {
  26024. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26025. }
  26026. else {
  26027. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26028. }
  26029. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26030. var otherCamera = this.activeCamera._alternateCamera;
  26031. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26032. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26033. }
  26034. if (this._sceneUbo.useUbo) {
  26035. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26036. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26037. this._sceneUbo.update();
  26038. }
  26039. };
  26040. /** @hidden */
  26041. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26042. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26043. return;
  26044. }
  26045. this._alternateViewUpdateFlag = view.updateFlag;
  26046. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26047. this._alternateViewMatrix = view;
  26048. this._alternateProjectionMatrix = projection;
  26049. if (!this._alternateTransformMatrix) {
  26050. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26051. }
  26052. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26053. if (!this._alternateSceneUbo) {
  26054. this._createAlternateUbo();
  26055. }
  26056. if (this._alternateSceneUbo.useUbo) {
  26057. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26058. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26059. this._alternateSceneUbo.update();
  26060. }
  26061. };
  26062. /**
  26063. * Gets the uniform buffer used to store scene data
  26064. * @returns a UniformBuffer
  26065. */
  26066. Scene.prototype.getSceneUniformBuffer = function () {
  26067. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26068. };
  26069. /**
  26070. * Gets an unique (relatively to the current scene) Id
  26071. * @returns an unique number for the scene
  26072. */
  26073. Scene.prototype.getUniqueId = function () {
  26074. var result = Scene._uniqueIdCounter;
  26075. Scene._uniqueIdCounter++;
  26076. return result;
  26077. };
  26078. /**
  26079. * Add a mesh to the list of scene's meshes
  26080. * @param newMesh defines the mesh to add
  26081. */
  26082. Scene.prototype.addMesh = function (newMesh) {
  26083. this.meshes.push(newMesh);
  26084. //notify the collision coordinator
  26085. if (this.collisionCoordinator) {
  26086. this.collisionCoordinator.onMeshAdded(newMesh);
  26087. }
  26088. newMesh._resyncLightSources();
  26089. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26090. };
  26091. /**
  26092. * Remove a mesh for the list of scene's meshes
  26093. * @param toRemove defines the mesh to remove
  26094. * @returns the index where the mesh was in the mesh list
  26095. */
  26096. Scene.prototype.removeMesh = function (toRemove) {
  26097. var index = this.meshes.indexOf(toRemove);
  26098. if (index !== -1) {
  26099. // Remove from the scene if mesh found
  26100. this.meshes.splice(index, 1);
  26101. }
  26102. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26103. return index;
  26104. };
  26105. /**
  26106. * Add a transform node to the list of scene's transform nodes
  26107. * @param newTransformNode defines the transform node to add
  26108. */
  26109. Scene.prototype.addTransformNode = function (newTransformNode) {
  26110. this.transformNodes.push(newTransformNode);
  26111. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26112. };
  26113. /**
  26114. * Remove a transform node for the list of scene's transform nodes
  26115. * @param toRemove defines the transform node to remove
  26116. * @returns the index where the transform node was in the transform node list
  26117. */
  26118. Scene.prototype.removeTransformNode = function (toRemove) {
  26119. var index = this.transformNodes.indexOf(toRemove);
  26120. if (index !== -1) {
  26121. // Remove from the scene if found
  26122. this.transformNodes.splice(index, 1);
  26123. }
  26124. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26125. return index;
  26126. };
  26127. /**
  26128. * Remove a skeleton for the list of scene's skeletons
  26129. * @param toRemove defines the skeleton to remove
  26130. * @returns the index where the skeleton was in the skeleton list
  26131. */
  26132. Scene.prototype.removeSkeleton = function (toRemove) {
  26133. var index = this.skeletons.indexOf(toRemove);
  26134. if (index !== -1) {
  26135. // Remove from the scene if found
  26136. this.skeletons.splice(index, 1);
  26137. }
  26138. return index;
  26139. };
  26140. /**
  26141. * Remove a morph target for the list of scene's morph targets
  26142. * @param toRemove defines the morph target to remove
  26143. * @returns the index where the morph target was in the morph target list
  26144. */
  26145. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26146. var index = this.morphTargetManagers.indexOf(toRemove);
  26147. if (index !== -1) {
  26148. // Remove from the scene if found
  26149. this.morphTargetManagers.splice(index, 1);
  26150. }
  26151. return index;
  26152. };
  26153. /**
  26154. * Remove a light for the list of scene's lights
  26155. * @param toRemove defines the light to remove
  26156. * @returns the index where the light was in the light list
  26157. */
  26158. Scene.prototype.removeLight = function (toRemove) {
  26159. var index = this.lights.indexOf(toRemove);
  26160. if (index !== -1) {
  26161. // Remove from meshes
  26162. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26163. var mesh = _a[_i];
  26164. mesh._removeLightSource(toRemove);
  26165. }
  26166. // Remove from the scene if mesh found
  26167. this.lights.splice(index, 1);
  26168. this.sortLightsByPriority();
  26169. }
  26170. this.onLightRemovedObservable.notifyObservers(toRemove);
  26171. return index;
  26172. };
  26173. /**
  26174. * Remove a camera for the list of scene's cameras
  26175. * @param toRemove defines the camera to remove
  26176. * @returns the index where the camera was in the camera list
  26177. */
  26178. Scene.prototype.removeCamera = function (toRemove) {
  26179. var index = this.cameras.indexOf(toRemove);
  26180. if (index !== -1) {
  26181. // Remove from the scene if mesh found
  26182. this.cameras.splice(index, 1);
  26183. }
  26184. // Remove from activeCameras
  26185. var index2 = this.activeCameras.indexOf(toRemove);
  26186. if (index2 !== -1) {
  26187. // Remove from the scene if mesh found
  26188. this.activeCameras.splice(index2, 1);
  26189. }
  26190. // Reset the activeCamera
  26191. if (this.activeCamera === toRemove) {
  26192. if (this.cameras.length > 0) {
  26193. this.activeCamera = this.cameras[0];
  26194. }
  26195. else {
  26196. this.activeCamera = null;
  26197. }
  26198. }
  26199. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26200. return index;
  26201. };
  26202. /**
  26203. * Remove a particle system for the list of scene's particle systems
  26204. * @param toRemove defines the particle system to remove
  26205. * @returns the index where the particle system was in the particle system list
  26206. */
  26207. Scene.prototype.removeParticleSystem = function (toRemove) {
  26208. var index = this.particleSystems.indexOf(toRemove);
  26209. if (index !== -1) {
  26210. this.particleSystems.splice(index, 1);
  26211. }
  26212. return index;
  26213. };
  26214. /**
  26215. * Remove a animation for the list of scene's animations
  26216. * @param toRemove defines the animation to remove
  26217. * @returns the index where the animation was in the animation list
  26218. */
  26219. Scene.prototype.removeAnimation = function (toRemove) {
  26220. var index = this.animations.indexOf(toRemove);
  26221. if (index !== -1) {
  26222. this.animations.splice(index, 1);
  26223. }
  26224. return index;
  26225. };
  26226. /**
  26227. * Removes the given animation group from this scene.
  26228. * @param toRemove The animation group to remove
  26229. * @returns The index of the removed animation group
  26230. */
  26231. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26232. var index = this.animationGroups.indexOf(toRemove);
  26233. if (index !== -1) {
  26234. this.animationGroups.splice(index, 1);
  26235. }
  26236. return index;
  26237. };
  26238. /**
  26239. * Removes the given multi-material from this scene.
  26240. * @param toRemove The multi-material to remove
  26241. * @returns The index of the removed multi-material
  26242. */
  26243. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26244. var index = this.multiMaterials.indexOf(toRemove);
  26245. if (index !== -1) {
  26246. this.multiMaterials.splice(index, 1);
  26247. }
  26248. return index;
  26249. };
  26250. /**
  26251. * Removes the given material from this scene.
  26252. * @param toRemove The material to remove
  26253. * @returns The index of the removed material
  26254. */
  26255. Scene.prototype.removeMaterial = function (toRemove) {
  26256. var index = this.materials.indexOf(toRemove);
  26257. if (index !== -1) {
  26258. this.materials.splice(index, 1);
  26259. }
  26260. return index;
  26261. };
  26262. /**
  26263. * Removes the given lens flare system from this scene.
  26264. * @param toRemove The lens flare system to remove
  26265. * @returns The index of the removed lens flare system
  26266. */
  26267. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26268. var index = this.lensFlareSystems.indexOf(toRemove);
  26269. if (index !== -1) {
  26270. this.lensFlareSystems.splice(index, 1);
  26271. }
  26272. return index;
  26273. };
  26274. /**
  26275. * Removes the given action manager from this scene.
  26276. * @param toRemove The action manager to remove
  26277. * @returns The index of the removed action manager
  26278. */
  26279. Scene.prototype.removeActionManager = function (toRemove) {
  26280. var index = this._actionManagers.indexOf(toRemove);
  26281. if (index !== -1) {
  26282. this._actionManagers.splice(index, 1);
  26283. }
  26284. return index;
  26285. };
  26286. /**
  26287. * Removes the given effect layer from this scene.
  26288. * @param toRemove defines the effect layer to remove
  26289. * @returns the index of the removed effect layer
  26290. */
  26291. Scene.prototype.removeEffectLayer = function (toRemove) {
  26292. var index = this.effectLayers.indexOf(toRemove);
  26293. if (index !== -1) {
  26294. this.effectLayers.splice(index, 1);
  26295. }
  26296. return index;
  26297. };
  26298. /**
  26299. * Removes the given texture from this scene.
  26300. * @param toRemove The texture to remove
  26301. * @returns The index of the removed texture
  26302. */
  26303. Scene.prototype.removeTexture = function (toRemove) {
  26304. var index = this.textures.indexOf(toRemove);
  26305. if (index !== -1) {
  26306. this.textures.splice(index, 1);
  26307. }
  26308. return index;
  26309. };
  26310. /**
  26311. * Adds the given light to this scene
  26312. * @param newLight The light to add
  26313. */
  26314. Scene.prototype.addLight = function (newLight) {
  26315. this.lights.push(newLight);
  26316. this.sortLightsByPriority();
  26317. // Add light to all meshes (To support if the light is removed and then readded)
  26318. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26319. var mesh = _a[_i];
  26320. if (mesh._lightSources.indexOf(newLight) === -1) {
  26321. mesh._lightSources.push(newLight);
  26322. mesh._resyncLightSources();
  26323. }
  26324. }
  26325. this.onNewLightAddedObservable.notifyObservers(newLight);
  26326. };
  26327. /**
  26328. * Sorts the list list based on light priorities
  26329. */
  26330. Scene.prototype.sortLightsByPriority = function () {
  26331. if (this.requireLightSorting) {
  26332. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26333. }
  26334. };
  26335. /**
  26336. * Adds the given camera to this scene
  26337. * @param newCamera The camera to add
  26338. */
  26339. Scene.prototype.addCamera = function (newCamera) {
  26340. this.cameras.push(newCamera);
  26341. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26342. };
  26343. /**
  26344. * Adds the given skeleton to this scene
  26345. * @param newSkeleton The skeleton to add
  26346. */
  26347. Scene.prototype.addSkeleton = function (newSkeleton) {
  26348. this.skeletons.push(newSkeleton);
  26349. };
  26350. /**
  26351. * Adds the given particle system to this scene
  26352. * @param newParticleSystem The particle system to add
  26353. */
  26354. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26355. this.particleSystems.push(newParticleSystem);
  26356. };
  26357. /**
  26358. * Adds the given animation to this scene
  26359. * @param newAnimation The animation to add
  26360. */
  26361. Scene.prototype.addAnimation = function (newAnimation) {
  26362. this.animations.push(newAnimation);
  26363. };
  26364. /**
  26365. * Adds the given animation group to this scene.
  26366. * @param newAnimationGroup The animation group to add
  26367. */
  26368. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26369. this.animationGroups.push(newAnimationGroup);
  26370. };
  26371. /**
  26372. * Adds the given multi-material to this scene
  26373. * @param newMultiMaterial The multi-material to add
  26374. */
  26375. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26376. this.multiMaterials.push(newMultiMaterial);
  26377. };
  26378. /**
  26379. * Adds the given material to this scene
  26380. * @param newMaterial The material to add
  26381. */
  26382. Scene.prototype.addMaterial = function (newMaterial) {
  26383. this.materials.push(newMaterial);
  26384. };
  26385. /**
  26386. * Adds the given morph target to this scene
  26387. * @param newMorphTargetManager The morph target to add
  26388. */
  26389. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26390. this.morphTargetManagers.push(newMorphTargetManager);
  26391. };
  26392. /**
  26393. * Adds the given geometry to this scene
  26394. * @param newGeometry The geometry to add
  26395. */
  26396. Scene.prototype.addGeometry = function (newGeometry) {
  26397. this._geometries.push(newGeometry);
  26398. };
  26399. /**
  26400. * Adds the given lens flare system to this scene
  26401. * @param newLensFlareSystem The lens flare system to add
  26402. */
  26403. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26404. this.lensFlareSystems.push(newLensFlareSystem);
  26405. };
  26406. /**
  26407. * Adds the given effect layer to this scene
  26408. * @param newEffectLayer defines the effect layer to add
  26409. */
  26410. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26411. this.effectLayers.push(newEffectLayer);
  26412. };
  26413. /**
  26414. * Adds the given action manager to this scene
  26415. * @param newActionManager The action manager to add
  26416. */
  26417. Scene.prototype.addActionManager = function (newActionManager) {
  26418. this._actionManagers.push(newActionManager);
  26419. };
  26420. /**
  26421. * Adds the given texture to this scene.
  26422. * @param newTexture The texture to add
  26423. */
  26424. Scene.prototype.addTexture = function (newTexture) {
  26425. this.textures.push(newTexture);
  26426. };
  26427. /**
  26428. * Switch active camera
  26429. * @param newCamera defines the new active camera
  26430. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26431. */
  26432. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26433. if (attachControl === void 0) { attachControl = true; }
  26434. var canvas = this._engine.getRenderingCanvas();
  26435. if (!canvas) {
  26436. return;
  26437. }
  26438. if (this.activeCamera) {
  26439. this.activeCamera.detachControl(canvas);
  26440. }
  26441. this.activeCamera = newCamera;
  26442. if (attachControl) {
  26443. newCamera.attachControl(canvas);
  26444. }
  26445. };
  26446. /**
  26447. * sets the active camera of the scene using its ID
  26448. * @param id defines the camera's ID
  26449. * @return the new active camera or null if none found.
  26450. */
  26451. Scene.prototype.setActiveCameraByID = function (id) {
  26452. var camera = this.getCameraByID(id);
  26453. if (camera) {
  26454. this.activeCamera = camera;
  26455. return camera;
  26456. }
  26457. return null;
  26458. };
  26459. /**
  26460. * sets the active camera of the scene using its name
  26461. * @param name defines the camera's name
  26462. * @returns the new active camera or null if none found.
  26463. */
  26464. Scene.prototype.setActiveCameraByName = function (name) {
  26465. var camera = this.getCameraByName(name);
  26466. if (camera) {
  26467. this.activeCamera = camera;
  26468. return camera;
  26469. }
  26470. return null;
  26471. };
  26472. /**
  26473. * get an animation group using its name
  26474. * @param name defines the material's name
  26475. * @return the animation group or null if none found.
  26476. */
  26477. Scene.prototype.getAnimationGroupByName = function (name) {
  26478. for (var index = 0; index < this.animationGroups.length; index++) {
  26479. if (this.animationGroups[index].name === name) {
  26480. return this.animationGroups[index];
  26481. }
  26482. }
  26483. return null;
  26484. };
  26485. /**
  26486. * get a material using its id
  26487. * @param id defines the material's ID
  26488. * @return the material or null if none found.
  26489. */
  26490. Scene.prototype.getMaterialByID = function (id) {
  26491. for (var index = 0; index < this.materials.length; index++) {
  26492. if (this.materials[index].id === id) {
  26493. return this.materials[index];
  26494. }
  26495. }
  26496. return null;
  26497. };
  26498. /**
  26499. * Gets a material using its name
  26500. * @param name defines the material's name
  26501. * @return the material or null if none found.
  26502. */
  26503. Scene.prototype.getMaterialByName = function (name) {
  26504. for (var index = 0; index < this.materials.length; index++) {
  26505. if (this.materials[index].name === name) {
  26506. return this.materials[index];
  26507. }
  26508. }
  26509. return null;
  26510. };
  26511. /**
  26512. * Gets a lens flare system using its name
  26513. * @param name defines the name to look for
  26514. * @returns the lens flare system or null if not found
  26515. */
  26516. Scene.prototype.getLensFlareSystemByName = function (name) {
  26517. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26518. if (this.lensFlareSystems[index].name === name) {
  26519. return this.lensFlareSystems[index];
  26520. }
  26521. }
  26522. return null;
  26523. };
  26524. /**
  26525. * Gets a lens flare system using its id
  26526. * @param id defines the id to look for
  26527. * @returns the lens flare system or null if not found
  26528. */
  26529. Scene.prototype.getLensFlareSystemByID = function (id) {
  26530. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26531. if (this.lensFlareSystems[index].id === id) {
  26532. return this.lensFlareSystems[index];
  26533. }
  26534. }
  26535. return null;
  26536. };
  26537. /**
  26538. * Gets a camera using its id
  26539. * @param id defines the id to look for
  26540. * @returns the camera or null if not found
  26541. */
  26542. Scene.prototype.getCameraByID = function (id) {
  26543. for (var index = 0; index < this.cameras.length; index++) {
  26544. if (this.cameras[index].id === id) {
  26545. return this.cameras[index];
  26546. }
  26547. }
  26548. return null;
  26549. };
  26550. /**
  26551. * Gets a camera using its unique id
  26552. * @param uniqueId defines the unique id to look for
  26553. * @returns the camera or null if not found
  26554. */
  26555. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26556. for (var index = 0; index < this.cameras.length; index++) {
  26557. if (this.cameras[index].uniqueId === uniqueId) {
  26558. return this.cameras[index];
  26559. }
  26560. }
  26561. return null;
  26562. };
  26563. /**
  26564. * Gets a camera using its name
  26565. * @param name defines the camera's name
  26566. * @return the camera or null if none found.
  26567. */
  26568. Scene.prototype.getCameraByName = function (name) {
  26569. for (var index = 0; index < this.cameras.length; index++) {
  26570. if (this.cameras[index].name === name) {
  26571. return this.cameras[index];
  26572. }
  26573. }
  26574. return null;
  26575. };
  26576. /**
  26577. * Gets a bone using its id
  26578. * @param id defines the bone's id
  26579. * @return the bone or null if not found
  26580. */
  26581. Scene.prototype.getBoneByID = function (id) {
  26582. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26583. var skeleton = this.skeletons[skeletonIndex];
  26584. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26585. if (skeleton.bones[boneIndex].id === id) {
  26586. return skeleton.bones[boneIndex];
  26587. }
  26588. }
  26589. }
  26590. return null;
  26591. };
  26592. /**
  26593. * Gets a bone using its id
  26594. * @param name defines the bone's name
  26595. * @return the bone or null if not found
  26596. */
  26597. Scene.prototype.getBoneByName = function (name) {
  26598. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26599. var skeleton = this.skeletons[skeletonIndex];
  26600. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26601. if (skeleton.bones[boneIndex].name === name) {
  26602. return skeleton.bones[boneIndex];
  26603. }
  26604. }
  26605. }
  26606. return null;
  26607. };
  26608. /**
  26609. * Gets a light node using its name
  26610. * @param name defines the the light's name
  26611. * @return the light or null if none found.
  26612. */
  26613. Scene.prototype.getLightByName = function (name) {
  26614. for (var index = 0; index < this.lights.length; index++) {
  26615. if (this.lights[index].name === name) {
  26616. return this.lights[index];
  26617. }
  26618. }
  26619. return null;
  26620. };
  26621. /**
  26622. * Gets a light node using its id
  26623. * @param id defines the light's id
  26624. * @return the light or null if none found.
  26625. */
  26626. Scene.prototype.getLightByID = function (id) {
  26627. for (var index = 0; index < this.lights.length; index++) {
  26628. if (this.lights[index].id === id) {
  26629. return this.lights[index];
  26630. }
  26631. }
  26632. return null;
  26633. };
  26634. /**
  26635. * Gets a light node using its scene-generated unique ID
  26636. * @param uniqueId defines the light's unique id
  26637. * @return the light or null if none found.
  26638. */
  26639. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26640. for (var index = 0; index < this.lights.length; index++) {
  26641. if (this.lights[index].uniqueId === uniqueId) {
  26642. return this.lights[index];
  26643. }
  26644. }
  26645. return null;
  26646. };
  26647. /**
  26648. * Gets a particle system by id
  26649. * @param id defines the particle system id
  26650. * @return the corresponding system or null if none found
  26651. */
  26652. Scene.prototype.getParticleSystemByID = function (id) {
  26653. for (var index = 0; index < this.particleSystems.length; index++) {
  26654. if (this.particleSystems[index].id === id) {
  26655. return this.particleSystems[index];
  26656. }
  26657. }
  26658. return null;
  26659. };
  26660. /**
  26661. * Gets a geometry using its ID
  26662. * @param id defines the geometry's id
  26663. * @return the geometry or null if none found.
  26664. */
  26665. Scene.prototype.getGeometryByID = function (id) {
  26666. for (var index = 0; index < this._geometries.length; index++) {
  26667. if (this._geometries[index].id === id) {
  26668. return this._geometries[index];
  26669. }
  26670. }
  26671. return null;
  26672. };
  26673. /**
  26674. * Add a new geometry to this scene
  26675. * @param geometry defines the geometry to be added to the scene.
  26676. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26677. * @return a boolean defining if the geometry was added or not
  26678. */
  26679. Scene.prototype.pushGeometry = function (geometry, force) {
  26680. if (!force && this.getGeometryByID(geometry.id)) {
  26681. return false;
  26682. }
  26683. this._geometries.push(geometry);
  26684. //notify the collision coordinator
  26685. if (this.collisionCoordinator) {
  26686. this.collisionCoordinator.onGeometryAdded(geometry);
  26687. }
  26688. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26689. return true;
  26690. };
  26691. /**
  26692. * Removes an existing geometry
  26693. * @param geometry defines the geometry to be removed from the scene
  26694. * @return a boolean defining if the geometry was removed or not
  26695. */
  26696. Scene.prototype.removeGeometry = function (geometry) {
  26697. var index = this._geometries.indexOf(geometry);
  26698. if (index > -1) {
  26699. this._geometries.splice(index, 1);
  26700. //notify the collision coordinator
  26701. if (this.collisionCoordinator) {
  26702. this.collisionCoordinator.onGeometryDeleted(geometry);
  26703. }
  26704. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26705. return true;
  26706. }
  26707. return false;
  26708. };
  26709. /**
  26710. * Gets the list of geometries attached to the scene
  26711. * @returns an array of Geometry
  26712. */
  26713. Scene.prototype.getGeometries = function () {
  26714. return this._geometries;
  26715. };
  26716. /**
  26717. * Gets the first added mesh found of a given ID
  26718. * @param id defines the id to search for
  26719. * @return the mesh found or null if not found at all
  26720. */
  26721. Scene.prototype.getMeshByID = function (id) {
  26722. for (var index = 0; index < this.meshes.length; index++) {
  26723. if (this.meshes[index].id === id) {
  26724. return this.meshes[index];
  26725. }
  26726. }
  26727. return null;
  26728. };
  26729. /**
  26730. * Gets a list of meshes using their id
  26731. * @param id defines the id to search for
  26732. * @returns a list of meshes
  26733. */
  26734. Scene.prototype.getMeshesByID = function (id) {
  26735. return this.meshes.filter(function (m) {
  26736. return m.id === id;
  26737. });
  26738. };
  26739. /**
  26740. * Gets the first added transform node found of a given ID
  26741. * @param id defines the id to search for
  26742. * @return the found transform node or null if not found at all.
  26743. */
  26744. Scene.prototype.getTransformNodeByID = function (id) {
  26745. for (var index = 0; index < this.transformNodes.length; index++) {
  26746. if (this.transformNodes[index].id === id) {
  26747. return this.transformNodes[index];
  26748. }
  26749. }
  26750. return null;
  26751. };
  26752. /**
  26753. * Gets a list of transform nodes using their id
  26754. * @param id defines the id to search for
  26755. * @returns a list of transform nodes
  26756. */
  26757. Scene.prototype.getTransformNodesByID = function (id) {
  26758. return this.transformNodes.filter(function (m) {
  26759. return m.id === id;
  26760. });
  26761. };
  26762. /**
  26763. * Gets a mesh with its auto-generated unique id
  26764. * @param uniqueId defines the unique id to search for
  26765. * @return the found mesh or null if not found at all.
  26766. */
  26767. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26768. for (var index = 0; index < this.meshes.length; index++) {
  26769. if (this.meshes[index].uniqueId === uniqueId) {
  26770. return this.meshes[index];
  26771. }
  26772. }
  26773. return null;
  26774. };
  26775. /**
  26776. * Gets a the last added mesh using a given id
  26777. * @param id defines the id to search for
  26778. * @return the found mesh or null if not found at all.
  26779. */
  26780. Scene.prototype.getLastMeshByID = function (id) {
  26781. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26782. if (this.meshes[index].id === id) {
  26783. return this.meshes[index];
  26784. }
  26785. }
  26786. return null;
  26787. };
  26788. /**
  26789. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26790. * @param id defines the id to search for
  26791. * @return the found node or null if not found at all
  26792. */
  26793. Scene.prototype.getLastEntryByID = function (id) {
  26794. var index;
  26795. for (index = this.meshes.length - 1; index >= 0; index--) {
  26796. if (this.meshes[index].id === id) {
  26797. return this.meshes[index];
  26798. }
  26799. }
  26800. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26801. if (this.transformNodes[index].id === id) {
  26802. return this.transformNodes[index];
  26803. }
  26804. }
  26805. for (index = this.cameras.length - 1; index >= 0; index--) {
  26806. if (this.cameras[index].id === id) {
  26807. return this.cameras[index];
  26808. }
  26809. }
  26810. for (index = this.lights.length - 1; index >= 0; index--) {
  26811. if (this.lights[index].id === id) {
  26812. return this.lights[index];
  26813. }
  26814. }
  26815. return null;
  26816. };
  26817. /**
  26818. * Gets a node (Mesh, Camera, Light) using a given id
  26819. * @param id defines the id to search for
  26820. * @return the found node or null if not found at all
  26821. */
  26822. Scene.prototype.getNodeByID = function (id) {
  26823. var mesh = this.getMeshByID(id);
  26824. if (mesh) {
  26825. return mesh;
  26826. }
  26827. var light = this.getLightByID(id);
  26828. if (light) {
  26829. return light;
  26830. }
  26831. var camera = this.getCameraByID(id);
  26832. if (camera) {
  26833. return camera;
  26834. }
  26835. var bone = this.getBoneByID(id);
  26836. return bone;
  26837. };
  26838. /**
  26839. * Gets a node (Mesh, Camera, Light) using a given name
  26840. * @param name defines the name to search for
  26841. * @return the found node or null if not found at all.
  26842. */
  26843. Scene.prototype.getNodeByName = function (name) {
  26844. var mesh = this.getMeshByName(name);
  26845. if (mesh) {
  26846. return mesh;
  26847. }
  26848. var light = this.getLightByName(name);
  26849. if (light) {
  26850. return light;
  26851. }
  26852. var camera = this.getCameraByName(name);
  26853. if (camera) {
  26854. return camera;
  26855. }
  26856. var bone = this.getBoneByName(name);
  26857. return bone;
  26858. };
  26859. /**
  26860. * Gets a mesh using a given name
  26861. * @param name defines the name to search for
  26862. * @return the found mesh or null if not found at all.
  26863. */
  26864. Scene.prototype.getMeshByName = function (name) {
  26865. for (var index = 0; index < this.meshes.length; index++) {
  26866. if (this.meshes[index].name === name) {
  26867. return this.meshes[index];
  26868. }
  26869. }
  26870. return null;
  26871. };
  26872. /**
  26873. * Gets a transform node using a given name
  26874. * @param name defines the name to search for
  26875. * @return the found transform node or null if not found at all.
  26876. */
  26877. Scene.prototype.getTransformNodeByName = function (name) {
  26878. for (var index = 0; index < this.transformNodes.length; index++) {
  26879. if (this.transformNodes[index].name === name) {
  26880. return this.transformNodes[index];
  26881. }
  26882. }
  26883. return null;
  26884. };
  26885. /**
  26886. * Gets a sound using a given name
  26887. * @param name defines the name to search for
  26888. * @return the found sound or null if not found at all.
  26889. */
  26890. Scene.prototype.getSoundByName = function (name) {
  26891. var index;
  26892. if (BABYLON.AudioEngine) {
  26893. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26894. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26895. return this.mainSoundTrack.soundCollection[index];
  26896. }
  26897. }
  26898. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26899. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26900. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26901. return this.soundTracks[sdIndex].soundCollection[index];
  26902. }
  26903. }
  26904. }
  26905. }
  26906. return null;
  26907. };
  26908. /**
  26909. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26910. * @param id defines the id to search for
  26911. * @return the found skeleton or null if not found at all.
  26912. */
  26913. Scene.prototype.getLastSkeletonByID = function (id) {
  26914. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26915. if (this.skeletons[index].id === id) {
  26916. return this.skeletons[index];
  26917. }
  26918. }
  26919. return null;
  26920. };
  26921. /**
  26922. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26923. * @param id defines the id to search for
  26924. * @return the found skeleton or null if not found at all.
  26925. */
  26926. Scene.prototype.getSkeletonById = function (id) {
  26927. for (var index = 0; index < this.skeletons.length; index++) {
  26928. if (this.skeletons[index].id === id) {
  26929. return this.skeletons[index];
  26930. }
  26931. }
  26932. return null;
  26933. };
  26934. /**
  26935. * Gets a skeleton using a given name
  26936. * @param name defines the name to search for
  26937. * @return the found skeleton or null if not found at all.
  26938. */
  26939. Scene.prototype.getSkeletonByName = function (name) {
  26940. for (var index = 0; index < this.skeletons.length; index++) {
  26941. if (this.skeletons[index].name === name) {
  26942. return this.skeletons[index];
  26943. }
  26944. }
  26945. return null;
  26946. };
  26947. /**
  26948. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  26949. * @param id defines the id to search for
  26950. * @return the found morph target manager or null if not found at all.
  26951. */
  26952. Scene.prototype.getMorphTargetManagerById = function (id) {
  26953. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  26954. if (this.morphTargetManagers[index].uniqueId === id) {
  26955. return this.morphTargetManagers[index];
  26956. }
  26957. }
  26958. return null;
  26959. };
  26960. /**
  26961. * Gets a boolean indicating if the given mesh is active
  26962. * @param mesh defines the mesh to look for
  26963. * @returns true if the mesh is in the active list
  26964. */
  26965. Scene.prototype.isActiveMesh = function (mesh) {
  26966. return (this._activeMeshes.indexOf(mesh) !== -1);
  26967. };
  26968. /**
  26969. * Return a the first highlight layer of the scene with a given name.
  26970. * @param name The name of the highlight layer to look for.
  26971. * @return The highlight layer if found otherwise null.
  26972. */
  26973. Scene.prototype.getHighlightLayerByName = function (name) {
  26974. for (var index = 0; index < this.effectLayers.length; index++) {
  26975. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  26976. return this.effectLayers[index];
  26977. }
  26978. }
  26979. return null;
  26980. };
  26981. /**
  26982. * Return a the first highlight layer of the scene with a given name.
  26983. * @param name The name of the highlight layer to look for.
  26984. * @return The highlight layer if found otherwise null.
  26985. */
  26986. Scene.prototype.getGlowLayerByName = function (name) {
  26987. for (var index = 0; index < this.effectLayers.length; index++) {
  26988. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  26989. return this.effectLayers[index];
  26990. }
  26991. }
  26992. return null;
  26993. };
  26994. Object.defineProperty(Scene.prototype, "uid", {
  26995. /**
  26996. * Return a unique id as a string which can serve as an identifier for the scene
  26997. */
  26998. get: function () {
  26999. if (!this._uid) {
  27000. this._uid = BABYLON.Tools.RandomId();
  27001. }
  27002. return this._uid;
  27003. },
  27004. enumerable: true,
  27005. configurable: true
  27006. });
  27007. /**
  27008. * Add an externaly attached data from its key.
  27009. * This method call will fail and return false, if such key already exists.
  27010. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27011. * @param key the unique key that identifies the data
  27012. * @param data the data object to associate to the key for this Engine instance
  27013. * @return true if no such key were already present and the data was added successfully, false otherwise
  27014. */
  27015. Scene.prototype.addExternalData = function (key, data) {
  27016. if (!this._externalData) {
  27017. this._externalData = new BABYLON.StringDictionary();
  27018. }
  27019. return this._externalData.add(key, data);
  27020. };
  27021. /**
  27022. * Get an externaly attached data from its key
  27023. * @param key the unique key that identifies the data
  27024. * @return the associated data, if present (can be null), or undefined if not present
  27025. */
  27026. Scene.prototype.getExternalData = function (key) {
  27027. if (!this._externalData) {
  27028. return null;
  27029. }
  27030. return this._externalData.get(key);
  27031. };
  27032. /**
  27033. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27034. * @param key the unique key that identifies the data
  27035. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27036. * @return the associated data, can be null if the factory returned null.
  27037. */
  27038. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27039. if (!this._externalData) {
  27040. this._externalData = new BABYLON.StringDictionary();
  27041. }
  27042. return this._externalData.getOrAddWithFactory(key, factory);
  27043. };
  27044. /**
  27045. * Remove an externaly attached data from the Engine instance
  27046. * @param key the unique key that identifies the data
  27047. * @return true if the data was successfully removed, false if it doesn't exist
  27048. */
  27049. Scene.prototype.removeExternalData = function (key) {
  27050. return this._externalData.remove(key);
  27051. };
  27052. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27053. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27054. if (mesh.showSubMeshesBoundingBox) {
  27055. var boundingInfo = subMesh.getBoundingInfo();
  27056. if (boundingInfo !== null && boundingInfo !== undefined) {
  27057. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27058. }
  27059. }
  27060. var material = subMesh.getMaterial();
  27061. if (material !== null && material !== undefined) {
  27062. // Render targets
  27063. if (material.getRenderTargetTextures !== undefined) {
  27064. if (this._processedMaterials.indexOf(material) === -1) {
  27065. this._processedMaterials.push(material);
  27066. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27067. }
  27068. }
  27069. // Dispatch
  27070. this._activeIndices.addCount(subMesh.indexCount, false);
  27071. this._renderingManager.dispatch(subMesh, mesh, material);
  27072. }
  27073. }
  27074. };
  27075. /**
  27076. * Clear the processed materials smart array preventing retention point in material dispose.
  27077. */
  27078. Scene.prototype.freeProcessedMaterials = function () {
  27079. this._processedMaterials.dispose();
  27080. };
  27081. /**
  27082. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27083. */
  27084. Scene.prototype.freeActiveMeshes = function () {
  27085. this._activeMeshes.dispose();
  27086. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27087. this.activeCamera._activeMeshes.dispose();
  27088. }
  27089. if (this.activeCameras) {
  27090. for (var i = 0; i < this.activeCameras.length; i++) {
  27091. var activeCamera = this.activeCameras[i];
  27092. if (activeCamera && activeCamera._activeMeshes) {
  27093. activeCamera._activeMeshes.dispose();
  27094. }
  27095. }
  27096. }
  27097. };
  27098. /**
  27099. * Clear the info related to rendering groups preventing retention points during dispose.
  27100. */
  27101. Scene.prototype.freeRenderingGroups = function () {
  27102. if (this._renderingManager) {
  27103. this._renderingManager.freeRenderingGroups();
  27104. }
  27105. if (this.textures) {
  27106. for (var i = 0; i < this.textures.length; i++) {
  27107. var texture = this.textures[i];
  27108. if (texture && texture.renderList) {
  27109. texture.freeRenderingGroups();
  27110. }
  27111. }
  27112. }
  27113. };
  27114. /** @hidden */
  27115. Scene.prototype._isInIntermediateRendering = function () {
  27116. return this._intermediateRendering;
  27117. };
  27118. /**
  27119. * Defines the current active mesh candidate provider
  27120. * @param provider defines the provider to use
  27121. */
  27122. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27123. this._activeMeshCandidateProvider = provider;
  27124. };
  27125. /**
  27126. * Gets the current active mesh candidate provider
  27127. * @returns the current active mesh candidate provider
  27128. */
  27129. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27130. return this._activeMeshCandidateProvider;
  27131. };
  27132. /**
  27133. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27134. * @returns the current scene
  27135. */
  27136. Scene.prototype.freezeActiveMeshes = function () {
  27137. if (!this.activeCamera) {
  27138. return this;
  27139. }
  27140. if (!this._frustumPlanes) {
  27141. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27142. }
  27143. this._evaluateActiveMeshes();
  27144. this._activeMeshesFrozen = true;
  27145. return this;
  27146. };
  27147. /**
  27148. * Use this function to restart evaluating active meshes on every frame
  27149. * @returns the current scene
  27150. */
  27151. Scene.prototype.unfreezeActiveMeshes = function () {
  27152. this._activeMeshesFrozen = false;
  27153. return this;
  27154. };
  27155. Scene.prototype._evaluateActiveMeshes = function () {
  27156. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27157. return;
  27158. }
  27159. if (!this.activeCamera) {
  27160. return;
  27161. }
  27162. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27163. this.activeCamera._activeMeshes.reset();
  27164. this._activeMeshes.reset();
  27165. this._renderingManager.reset();
  27166. this._processedMaterials.reset();
  27167. this._activeParticleSystems.reset();
  27168. this._activeSkeletons.reset();
  27169. this._softwareSkinnedMeshes.reset();
  27170. if (this._boundingBoxRenderer) {
  27171. this._boundingBoxRenderer.reset();
  27172. }
  27173. // Meshes
  27174. var meshes;
  27175. var len;
  27176. var checkIsEnabled = true;
  27177. // Determine mesh candidates
  27178. if (this._activeMeshCandidateProvider !== undefined) {
  27179. // Use _activeMeshCandidateProvider
  27180. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27181. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27182. if (meshes !== undefined) {
  27183. len = meshes.length;
  27184. }
  27185. else {
  27186. len = 0;
  27187. }
  27188. }
  27189. else if (this._selectionOctree !== undefined) {
  27190. // Octree
  27191. var selection = this._selectionOctree.select(this._frustumPlanes);
  27192. meshes = selection.data;
  27193. len = selection.length;
  27194. }
  27195. else {
  27196. // Full scene traversal
  27197. len = this.meshes.length;
  27198. meshes = this.meshes;
  27199. }
  27200. // Check each mesh
  27201. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27202. mesh = meshes[meshIndex];
  27203. if (mesh.isBlocked) {
  27204. continue;
  27205. }
  27206. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27207. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27208. continue;
  27209. }
  27210. mesh.computeWorldMatrix();
  27211. // Intersections
  27212. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27213. this._meshesForIntersections.pushNoDuplicate(mesh);
  27214. }
  27215. // Switch to current LOD
  27216. meshLOD = mesh.getLOD(this.activeCamera);
  27217. if (meshLOD === undefined || meshLOD === null) {
  27218. continue;
  27219. }
  27220. mesh._preActivate();
  27221. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27222. this._activeMeshes.push(mesh);
  27223. this.activeCamera._activeMeshes.push(mesh);
  27224. mesh._activate(this._renderId);
  27225. if (meshLOD !== mesh) {
  27226. meshLOD._activate(this._renderId);
  27227. }
  27228. this._activeMesh(mesh, meshLOD);
  27229. }
  27230. }
  27231. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27232. // Particle systems
  27233. if (this.particlesEnabled) {
  27234. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27235. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27236. var particleSystem = this.particleSystems[particleIndex];
  27237. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27238. continue;
  27239. }
  27240. var emitter = particleSystem.emitter;
  27241. if (!emitter.position || emitter.isEnabled()) {
  27242. this._activeParticleSystems.push(particleSystem);
  27243. particleSystem.animate();
  27244. this._renderingManager.dispatchParticles(particleSystem);
  27245. }
  27246. }
  27247. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27248. }
  27249. };
  27250. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27251. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27252. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27253. mesh.skeleton.prepare();
  27254. }
  27255. if (!mesh.computeBonesUsingShaders) {
  27256. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27257. }
  27258. }
  27259. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27260. var boundingInfo = sourceMesh.getBoundingInfo();
  27261. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27262. }
  27263. if (mesh !== undefined && mesh !== null
  27264. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27265. // Submeshes Octrees
  27266. var len;
  27267. var subMeshes;
  27268. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27269. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27270. len = intersections.length;
  27271. subMeshes = intersections.data;
  27272. }
  27273. else {
  27274. subMeshes = mesh.subMeshes;
  27275. len = subMeshes.length;
  27276. }
  27277. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27278. subMesh = subMeshes[subIndex];
  27279. this._evaluateSubMesh(subMesh, mesh);
  27280. }
  27281. }
  27282. };
  27283. /**
  27284. * Update the transform matrix to update from the current active camera
  27285. * @param force defines a boolean used to force the update even if cache is up to date
  27286. */
  27287. Scene.prototype.updateTransformMatrix = function (force) {
  27288. if (!this.activeCamera) {
  27289. return;
  27290. }
  27291. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27292. };
  27293. /**
  27294. * 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)
  27295. * @param alternateCamera defines the camera to use
  27296. */
  27297. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27298. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27299. };
  27300. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27301. if (camera && camera._skipRendering) {
  27302. return;
  27303. }
  27304. var engine = this._engine;
  27305. this.activeCamera = camera;
  27306. if (!this.activeCamera)
  27307. throw new Error("Active camera not set");
  27308. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27309. // Viewport
  27310. engine.setViewport(this.activeCamera.viewport);
  27311. // Camera
  27312. this.resetCachedMaterial();
  27313. this._renderId++;
  27314. this.updateTransformMatrix();
  27315. if (camera._alternateCamera) {
  27316. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27317. this._alternateRendering = true;
  27318. }
  27319. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27320. // Meshes
  27321. this._evaluateActiveMeshes();
  27322. // Software skinning
  27323. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27324. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27325. mesh.applySkeleton(mesh.skeleton);
  27326. }
  27327. // Render targets
  27328. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27329. var needsRestoreFrameBuffer = false;
  27330. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27331. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27332. }
  27333. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27334. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27335. }
  27336. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27337. this._intermediateRendering = true;
  27338. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27339. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27340. var renderTarget = this._renderTargets.data[renderIndex];
  27341. if (renderTarget._shouldRender()) {
  27342. this._renderId++;
  27343. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27344. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27345. }
  27346. }
  27347. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27348. this._intermediateRendering = false;
  27349. this._renderId++;
  27350. needsRestoreFrameBuffer = true; // Restore back buffer
  27351. }
  27352. // Render EffecttLayer Texture
  27353. var stencilState = this._engine.getStencilBuffer();
  27354. var renderEffects = false;
  27355. var needStencil = false;
  27356. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27357. this._intermediateRendering = true;
  27358. for (var i = 0; i < this.effectLayers.length; i++) {
  27359. var effectLayer = this.effectLayers[i];
  27360. if (effectLayer.shouldRender() &&
  27361. (!effectLayer.camera ||
  27362. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27363. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27364. renderEffects = true;
  27365. needStencil = needStencil || effectLayer.needStencil();
  27366. var renderTarget = effectLayer._mainTexture;
  27367. if (renderTarget._shouldRender()) {
  27368. this._renderId++;
  27369. renderTarget.render(false, false);
  27370. needsRestoreFrameBuffer = true;
  27371. }
  27372. }
  27373. }
  27374. this._intermediateRendering = false;
  27375. this._renderId++;
  27376. }
  27377. if (needsRestoreFrameBuffer) {
  27378. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27379. }
  27380. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27381. // Prepare Frame
  27382. this.postProcessManager._prepareFrame();
  27383. // Backgrounds
  27384. var layerIndex;
  27385. var layer;
  27386. if (this.layers.length) {
  27387. engine.setDepthBuffer(false);
  27388. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27389. layer = this.layers[layerIndex];
  27390. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27391. layer.render();
  27392. }
  27393. }
  27394. engine.setDepthBuffer(true);
  27395. }
  27396. // Activate effect Layer stencil
  27397. if (needStencil) {
  27398. this._engine.setStencilBuffer(true);
  27399. }
  27400. // Render
  27401. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27402. this._renderingManager.render(null, null, true, true);
  27403. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27404. // Restore effect Layer stencil
  27405. if (needStencil) {
  27406. this._engine.setStencilBuffer(stencilState);
  27407. }
  27408. // Bounding boxes
  27409. if (this._boundingBoxRenderer) {
  27410. this._boundingBoxRenderer.render();
  27411. }
  27412. // Lens flares
  27413. if (this.lensFlaresEnabled) {
  27414. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27415. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27416. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27417. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27418. lensFlareSystem.render();
  27419. }
  27420. }
  27421. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27422. }
  27423. // Effect Layer
  27424. if (renderEffects) {
  27425. engine.setDepthBuffer(false);
  27426. for (var i = 0; i < this.effectLayers.length; i++) {
  27427. if (this.effectLayers[i].shouldRender()) {
  27428. this.effectLayers[i].render();
  27429. }
  27430. }
  27431. engine.setDepthBuffer(true);
  27432. }
  27433. // Foregrounds
  27434. if (this.layers.length) {
  27435. engine.setDepthBuffer(false);
  27436. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27437. layer = this.layers[layerIndex];
  27438. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27439. layer.render();
  27440. }
  27441. }
  27442. engine.setDepthBuffer(true);
  27443. }
  27444. // Finalize frame
  27445. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27446. // Reset some special arrays
  27447. this._renderTargets.reset();
  27448. this._alternateRendering = false;
  27449. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27450. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27451. };
  27452. Scene.prototype._processSubCameras = function (camera) {
  27453. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27454. this._renderForCamera(camera);
  27455. return;
  27456. }
  27457. // rig cameras
  27458. for (var index = 0; index < camera._rigCameras.length; index++) {
  27459. this._renderForCamera(camera._rigCameras[index], camera);
  27460. }
  27461. this.activeCamera = camera;
  27462. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27463. };
  27464. Scene.prototype._checkIntersections = function () {
  27465. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27466. var sourceMesh = this._meshesForIntersections.data[index];
  27467. if (!sourceMesh.actionManager) {
  27468. continue;
  27469. }
  27470. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27471. var action = sourceMesh.actionManager.actions[actionIndex];
  27472. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27473. var parameters = action.getTriggerParameter();
  27474. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27475. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27476. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27477. if (areIntersecting && currentIntersectionInProgress === -1) {
  27478. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27479. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27480. sourceMesh._intersectionsInProgress.push(otherMesh);
  27481. }
  27482. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27483. sourceMesh._intersectionsInProgress.push(otherMesh);
  27484. }
  27485. }
  27486. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27487. //They intersected, and now they don't.
  27488. //is this trigger an exit trigger? execute an event.
  27489. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27490. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27491. }
  27492. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27493. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27494. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27495. return otherMesh === parameterMesh;
  27496. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27497. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27498. }
  27499. }
  27500. }
  27501. }
  27502. }
  27503. };
  27504. /**
  27505. * Render the scene
  27506. */
  27507. Scene.prototype.render = function () {
  27508. if (this.isDisposed) {
  27509. return;
  27510. }
  27511. this._activeParticles.fetchNewFrame();
  27512. this._totalVertices.fetchNewFrame();
  27513. this._activeIndices.fetchNewFrame();
  27514. this._activeBones.fetchNewFrame();
  27515. this._meshesForIntersections.reset();
  27516. this.resetCachedMaterial();
  27517. this.onBeforeAnimationsObservable.notifyObservers(this);
  27518. // Actions
  27519. if (this.actionManager) {
  27520. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27521. }
  27522. //Simplification Queue
  27523. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27524. this.simplificationQueue.executeNext();
  27525. }
  27526. if (this._engine.isDeterministicLockStep()) {
  27527. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27528. var defaultFPS = (60.0 / 1000.0);
  27529. var defaultFrameTime = 1000 / 60; // frame time in MS
  27530. if (this._physicsEngine) {
  27531. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27532. }
  27533. var stepsTaken = 0;
  27534. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27535. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27536. internalSteps = Math.min(internalSteps, maxSubSteps);
  27537. do {
  27538. this.onBeforeStepObservable.notifyObservers(this);
  27539. // Animations
  27540. this._animationRatio = defaultFrameTime * defaultFPS;
  27541. this._animate();
  27542. this.onAfterAnimationsObservable.notifyObservers(this);
  27543. // Physics
  27544. if (this._physicsEngine) {
  27545. this.onBeforePhysicsObservable.notifyObservers(this);
  27546. this._physicsEngine._step(defaultFrameTime / 1000);
  27547. this.onAfterPhysicsObservable.notifyObservers(this);
  27548. }
  27549. this.onAfterStepObservable.notifyObservers(this);
  27550. this._currentStepId++;
  27551. stepsTaken++;
  27552. deltaTime -= defaultFrameTime;
  27553. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27554. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27555. }
  27556. else {
  27557. // Animations
  27558. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27559. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27560. this._animate();
  27561. this.onAfterAnimationsObservable.notifyObservers(this);
  27562. // Physics
  27563. if (this._physicsEngine) {
  27564. this.onBeforePhysicsObservable.notifyObservers(this);
  27565. this._physicsEngine._step(deltaTime / 1000.0);
  27566. this.onAfterPhysicsObservable.notifyObservers(this);
  27567. }
  27568. }
  27569. // update gamepad manager
  27570. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27571. this._gamepadManager._checkGamepadsStatus();
  27572. }
  27573. // Update Cameras
  27574. if (this.activeCameras.length > 0) {
  27575. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27576. var camera = this.activeCameras[cameraIndex];
  27577. camera.update();
  27578. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27579. // rig cameras
  27580. for (var index = 0; index < camera._rigCameras.length; index++) {
  27581. camera._rigCameras[index].update();
  27582. }
  27583. }
  27584. }
  27585. }
  27586. else if (this.activeCamera) {
  27587. this.activeCamera.update();
  27588. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27589. // rig cameras
  27590. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27591. this.activeCamera._rigCameras[index].update();
  27592. }
  27593. }
  27594. }
  27595. // Before render
  27596. this.onBeforeRenderObservable.notifyObservers(this);
  27597. // Customs render targets
  27598. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27599. var engine = this.getEngine();
  27600. var currentActiveCamera = this.activeCamera;
  27601. if (this.renderTargetsEnabled) {
  27602. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27603. this._intermediateRendering = true;
  27604. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27605. var renderTarget = this.customRenderTargets[customIndex];
  27606. if (renderTarget._shouldRender()) {
  27607. this._renderId++;
  27608. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27609. if (!this.activeCamera)
  27610. throw new Error("Active camera not set");
  27611. // Viewport
  27612. engine.setViewport(this.activeCamera.viewport);
  27613. // Camera
  27614. this.updateTransformMatrix();
  27615. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27616. }
  27617. }
  27618. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27619. this._intermediateRendering = false;
  27620. this._renderId++;
  27621. }
  27622. // Restore back buffer
  27623. if (this.customRenderTargets.length > 0) {
  27624. engine.restoreDefaultFramebuffer();
  27625. }
  27626. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27627. this.activeCamera = currentActiveCamera;
  27628. // Procedural textures
  27629. if (this.proceduralTexturesEnabled) {
  27630. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27631. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27632. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27633. if (proceduralTexture._shouldRender()) {
  27634. proceduralTexture.render();
  27635. }
  27636. }
  27637. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27638. }
  27639. // Clear
  27640. if (this.autoClearDepthAndStencil || this.autoClear) {
  27641. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27642. }
  27643. // Shadows
  27644. if (this.shadowsEnabled) {
  27645. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27646. var light = this.lights[lightIndex];
  27647. var shadowGenerator = light.getShadowGenerator();
  27648. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27649. var shadowMap = (shadowGenerator.getShadowMap());
  27650. if (this.textures.indexOf(shadowMap) !== -1) {
  27651. this._renderTargets.push(shadowMap);
  27652. }
  27653. }
  27654. }
  27655. }
  27656. // Depth renderer
  27657. for (var key in this._depthRenderer) {
  27658. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27659. }
  27660. // Geometry renderer
  27661. if (this._geometryBufferRenderer) {
  27662. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27663. }
  27664. // RenderPipeline
  27665. if (this._postProcessRenderPipelineManager) {
  27666. this._postProcessRenderPipelineManager.update();
  27667. }
  27668. // Multi-cameras?
  27669. if (this.activeCameras.length > 0) {
  27670. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27671. if (cameraIndex > 0) {
  27672. this._engine.clear(null, false, true, true);
  27673. }
  27674. this._processSubCameras(this.activeCameras[cameraIndex]);
  27675. }
  27676. }
  27677. else {
  27678. if (!this.activeCamera) {
  27679. throw new Error("No camera defined");
  27680. }
  27681. this._processSubCameras(this.activeCamera);
  27682. }
  27683. // Intersection checks
  27684. this._checkIntersections();
  27685. // Update the audio listener attached to the camera
  27686. if (BABYLON.AudioEngine) {
  27687. this._updateAudioParameters();
  27688. }
  27689. // After render
  27690. if (this.afterRender) {
  27691. this.afterRender();
  27692. }
  27693. this.onAfterRenderObservable.notifyObservers(this);
  27694. // Cleaning
  27695. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27696. var data = this._toBeDisposed.data[index];
  27697. if (data) {
  27698. data.dispose();
  27699. }
  27700. this._toBeDisposed[index] = null;
  27701. }
  27702. this._toBeDisposed.reset();
  27703. if (this.dumpNextRenderTargets) {
  27704. this.dumpNextRenderTargets = false;
  27705. }
  27706. this._activeBones.addCount(0, true);
  27707. this._activeIndices.addCount(0, true);
  27708. this._activeParticles.addCount(0, true);
  27709. };
  27710. Scene.prototype._updateAudioParameters = function () {
  27711. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27712. return;
  27713. }
  27714. var listeningCamera;
  27715. var audioEngine = BABYLON.Engine.audioEngine;
  27716. if (this.activeCameras.length > 0) {
  27717. listeningCamera = this.activeCameras[0];
  27718. }
  27719. else {
  27720. listeningCamera = this.activeCamera;
  27721. }
  27722. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27723. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27724. // for VR cameras
  27725. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27726. listeningCamera = listeningCamera.rigCameras[0];
  27727. }
  27728. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27729. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27730. cameraDirection.normalize();
  27731. // To avoid some errors on GearVR
  27732. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27733. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27734. }
  27735. var i;
  27736. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27737. var sound = this.mainSoundTrack.soundCollection[i];
  27738. if (sound.useCustomAttenuation) {
  27739. sound.updateDistanceFromListener();
  27740. }
  27741. }
  27742. for (i = 0; i < this.soundTracks.length; i++) {
  27743. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27744. sound = this.soundTracks[i].soundCollection[j];
  27745. if (sound.useCustomAttenuation) {
  27746. sound.updateDistanceFromListener();
  27747. }
  27748. }
  27749. }
  27750. }
  27751. };
  27752. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27753. // Audio
  27754. /**
  27755. * Gets or sets if audio support is enabled
  27756. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27757. */
  27758. get: function () {
  27759. return this._audioEnabled;
  27760. },
  27761. set: function (value) {
  27762. this._audioEnabled = value;
  27763. if (BABYLON.AudioEngine) {
  27764. if (this._audioEnabled) {
  27765. this._enableAudio();
  27766. }
  27767. else {
  27768. this._disableAudio();
  27769. }
  27770. }
  27771. },
  27772. enumerable: true,
  27773. configurable: true
  27774. });
  27775. Scene.prototype._disableAudio = function () {
  27776. var i;
  27777. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27778. this.mainSoundTrack.soundCollection[i].pause();
  27779. }
  27780. for (i = 0; i < this.soundTracks.length; i++) {
  27781. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27782. this.soundTracks[i].soundCollection[j].pause();
  27783. }
  27784. }
  27785. };
  27786. Scene.prototype._enableAudio = function () {
  27787. var i;
  27788. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27789. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27790. this.mainSoundTrack.soundCollection[i].play();
  27791. }
  27792. }
  27793. for (i = 0; i < this.soundTracks.length; i++) {
  27794. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27795. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27796. this.soundTracks[i].soundCollection[j].play();
  27797. }
  27798. }
  27799. }
  27800. };
  27801. Object.defineProperty(Scene.prototype, "headphone", {
  27802. /**
  27803. * Gets or sets if audio will be output to headphones
  27804. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27805. */
  27806. get: function () {
  27807. return this._headphone;
  27808. },
  27809. set: function (value) {
  27810. this._headphone = value;
  27811. if (BABYLON.AudioEngine) {
  27812. if (this._headphone) {
  27813. this._switchAudioModeForHeadphones();
  27814. }
  27815. else {
  27816. this._switchAudioModeForNormalSpeakers();
  27817. }
  27818. }
  27819. },
  27820. enumerable: true,
  27821. configurable: true
  27822. });
  27823. Scene.prototype._switchAudioModeForHeadphones = function () {
  27824. this.mainSoundTrack.switchPanningModelToHRTF();
  27825. for (var i = 0; i < this.soundTracks.length; i++) {
  27826. this.soundTracks[i].switchPanningModelToHRTF();
  27827. }
  27828. };
  27829. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27830. this.mainSoundTrack.switchPanningModelToEqualPower();
  27831. for (var i = 0; i < this.soundTracks.length; i++) {
  27832. this.soundTracks[i].switchPanningModelToEqualPower();
  27833. }
  27834. };
  27835. /**
  27836. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27837. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27838. * @returns the created depth renderer
  27839. */
  27840. Scene.prototype.enableDepthRenderer = function (camera) {
  27841. camera = camera || this.activeCamera;
  27842. if (!camera) {
  27843. throw "No camera available to enable depth renderer";
  27844. }
  27845. if (!this._depthRenderer[camera.id]) {
  27846. var textureType = 0;
  27847. if (this._engine.getCaps().textureHalfFloatRender) {
  27848. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27849. }
  27850. else if (this._engine.getCaps().textureFloatRender) {
  27851. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27852. }
  27853. else {
  27854. throw "Depth renderer does not support int texture type";
  27855. }
  27856. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27857. }
  27858. return this._depthRenderer[camera.id];
  27859. };
  27860. /**
  27861. * Disables a depth renderer for a given camera
  27862. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27863. */
  27864. Scene.prototype.disableDepthRenderer = function (camera) {
  27865. camera = camera || this.activeCamera;
  27866. if (!camera || !this._depthRenderer[camera.id]) {
  27867. return;
  27868. }
  27869. this._depthRenderer[camera.id].dispose();
  27870. delete this._depthRenderer[camera.id];
  27871. };
  27872. /**
  27873. * Enables a GeometryBufferRender and associates it with the scene
  27874. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27875. * @returns the GeometryBufferRenderer
  27876. */
  27877. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27878. if (ratio === void 0) { ratio = 1; }
  27879. if (this._geometryBufferRenderer) {
  27880. return this._geometryBufferRenderer;
  27881. }
  27882. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27883. if (!this._geometryBufferRenderer.isSupported) {
  27884. this._geometryBufferRenderer = null;
  27885. }
  27886. return this._geometryBufferRenderer;
  27887. };
  27888. /**
  27889. * Disables the GeometryBufferRender associated with the scene
  27890. */
  27891. Scene.prototype.disableGeometryBufferRenderer = function () {
  27892. if (!this._geometryBufferRenderer) {
  27893. return;
  27894. }
  27895. this._geometryBufferRenderer.dispose();
  27896. this._geometryBufferRenderer = null;
  27897. };
  27898. /**
  27899. * Freeze all materials
  27900. * A frozen material will not be updatable but should be faster to render
  27901. */
  27902. Scene.prototype.freezeMaterials = function () {
  27903. for (var i = 0; i < this.materials.length; i++) {
  27904. this.materials[i].freeze();
  27905. }
  27906. };
  27907. /**
  27908. * Unfreeze all materials
  27909. * A frozen material will not be updatable but should be faster to render
  27910. */
  27911. Scene.prototype.unfreezeMaterials = function () {
  27912. for (var i = 0; i < this.materials.length; i++) {
  27913. this.materials[i].unfreeze();
  27914. }
  27915. };
  27916. /**
  27917. * Releases all held ressources
  27918. */
  27919. Scene.prototype.dispose = function () {
  27920. this.beforeRender = null;
  27921. this.afterRender = null;
  27922. this.skeletons = [];
  27923. this.morphTargetManagers = [];
  27924. this.importedMeshesFiles = new Array();
  27925. this.stopAllAnimations();
  27926. this.resetCachedMaterial();
  27927. for (var key in this._depthRenderer) {
  27928. this._depthRenderer[key].dispose();
  27929. }
  27930. if (this._gamepadManager) {
  27931. this._gamepadManager.dispose();
  27932. this._gamepadManager = null;
  27933. }
  27934. // Smart arrays
  27935. if (this.activeCamera) {
  27936. this.activeCamera._activeMeshes.dispose();
  27937. this.activeCamera = null;
  27938. }
  27939. this._activeMeshes.dispose();
  27940. this._renderingManager.dispose();
  27941. this._processedMaterials.dispose();
  27942. this._activeParticleSystems.dispose();
  27943. this._activeSkeletons.dispose();
  27944. this._softwareSkinnedMeshes.dispose();
  27945. this._renderTargets.dispose();
  27946. this._registeredForLateAnimationBindings.dispose();
  27947. if (this._boundingBoxRenderer) {
  27948. this._boundingBoxRenderer.dispose();
  27949. }
  27950. this._meshesForIntersections.dispose();
  27951. this._toBeDisposed.dispose();
  27952. // Abort active requests
  27953. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  27954. var request = _a[_i];
  27955. request.abort();
  27956. }
  27957. // Debug layer
  27958. if (this._debugLayer) {
  27959. this._debugLayer.hide();
  27960. }
  27961. // Events
  27962. this.onDisposeObservable.notifyObservers(this);
  27963. this.onDisposeObservable.clear();
  27964. this.onBeforeRenderObservable.clear();
  27965. this.onAfterRenderObservable.clear();
  27966. this.onBeforeRenderTargetsRenderObservable.clear();
  27967. this.onAfterRenderTargetsRenderObservable.clear();
  27968. this.onAfterStepObservable.clear();
  27969. this.onBeforeStepObservable.clear();
  27970. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27971. this.onAfterActiveMeshesEvaluationObservable.clear();
  27972. this.onBeforeParticlesRenderingObservable.clear();
  27973. this.onAfterParticlesRenderingObservable.clear();
  27974. this.onBeforeSpritesRenderingObservable.clear();
  27975. this.onAfterSpritesRenderingObservable.clear();
  27976. this.onBeforeDrawPhaseObservable.clear();
  27977. this.onAfterDrawPhaseObservable.clear();
  27978. this.onBeforePhysicsObservable.clear();
  27979. this.onAfterPhysicsObservable.clear();
  27980. this.onBeforeAnimationsObservable.clear();
  27981. this.onAfterAnimationsObservable.clear();
  27982. this.onDataLoadedObservable.clear();
  27983. this.detachControl();
  27984. // Release sounds & sounds tracks
  27985. if (BABYLON.AudioEngine) {
  27986. this.disposeSounds();
  27987. }
  27988. // VR Helper
  27989. if (this.VRHelper) {
  27990. this.VRHelper.dispose();
  27991. }
  27992. // Detach cameras
  27993. var canvas = this._engine.getRenderingCanvas();
  27994. if (canvas) {
  27995. var index;
  27996. for (index = 0; index < this.cameras.length; index++) {
  27997. this.cameras[index].detachControl(canvas);
  27998. }
  27999. }
  28000. // Release animation groups
  28001. while (this.animationGroups.length) {
  28002. this.animationGroups[0].dispose();
  28003. }
  28004. // Release lights
  28005. while (this.lights.length) {
  28006. this.lights[0].dispose();
  28007. }
  28008. // Release meshes
  28009. while (this.meshes.length) {
  28010. this.meshes[0].dispose(true);
  28011. }
  28012. while (this.transformNodes.length) {
  28013. this.removeTransformNode(this.transformNodes[0]);
  28014. }
  28015. // Release cameras
  28016. while (this.cameras.length) {
  28017. this.cameras[0].dispose();
  28018. }
  28019. // Release materials
  28020. if (this.defaultMaterial) {
  28021. this.defaultMaterial.dispose();
  28022. }
  28023. while (this.multiMaterials.length) {
  28024. this.multiMaterials[0].dispose();
  28025. }
  28026. while (this.materials.length) {
  28027. this.materials[0].dispose();
  28028. }
  28029. // Release particles
  28030. while (this.particleSystems.length) {
  28031. this.particleSystems[0].dispose();
  28032. }
  28033. // Release sprites
  28034. while (this.spriteManagers.length) {
  28035. this.spriteManagers[0].dispose();
  28036. }
  28037. // Release postProcesses
  28038. while (this.postProcesses.length) {
  28039. this.postProcesses[0].dispose();
  28040. }
  28041. // Release layers
  28042. while (this.layers.length) {
  28043. this.layers[0].dispose();
  28044. }
  28045. while (this.effectLayers.length) {
  28046. this.effectLayers[0].dispose();
  28047. }
  28048. // Release textures
  28049. while (this.textures.length) {
  28050. this.textures[0].dispose();
  28051. }
  28052. // Release UBO
  28053. this._sceneUbo.dispose();
  28054. if (this._alternateSceneUbo) {
  28055. this._alternateSceneUbo.dispose();
  28056. }
  28057. // Post-processes
  28058. this.postProcessManager.dispose();
  28059. if (this._postProcessRenderPipelineManager) {
  28060. this._postProcessRenderPipelineManager.dispose();
  28061. }
  28062. // Physics
  28063. if (this._physicsEngine) {
  28064. this.disablePhysicsEngine();
  28065. }
  28066. // Remove from engine
  28067. index = this._engine.scenes.indexOf(this);
  28068. if (index > -1) {
  28069. this._engine.scenes.splice(index, 1);
  28070. }
  28071. this._engine.wipeCaches(true);
  28072. this._isDisposed = true;
  28073. };
  28074. Object.defineProperty(Scene.prototype, "isDisposed", {
  28075. /**
  28076. * Gets if the scene is already disposed
  28077. */
  28078. get: function () {
  28079. return this._isDisposed;
  28080. },
  28081. enumerable: true,
  28082. configurable: true
  28083. });
  28084. /**
  28085. * Releases sounds & soundtracks
  28086. */
  28087. Scene.prototype.disposeSounds = function () {
  28088. if (!this._mainSoundTrack) {
  28089. return;
  28090. }
  28091. this.mainSoundTrack.dispose();
  28092. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28093. this.soundTracks[scIndex].dispose();
  28094. }
  28095. };
  28096. // Octrees
  28097. /**
  28098. * Get the world extend vectors with an optional filter
  28099. *
  28100. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28101. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28102. */
  28103. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28104. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28105. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28106. filterPredicate = filterPredicate || (function () { return true; });
  28107. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28108. mesh.computeWorldMatrix(true);
  28109. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28110. return;
  28111. }
  28112. var boundingInfo = mesh.getBoundingInfo();
  28113. var minBox = boundingInfo.boundingBox.minimumWorld;
  28114. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28115. BABYLON.Tools.CheckExtends(minBox, min, max);
  28116. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28117. });
  28118. return {
  28119. min: min,
  28120. max: max
  28121. };
  28122. };
  28123. /**
  28124. * Creates or updates the octree used to boost selection (picking)
  28125. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28126. * @param maxCapacity defines the maximum capacity per leaf
  28127. * @param maxDepth defines the maximum depth of the octree
  28128. * @returns an octree of AbstractMesh
  28129. */
  28130. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28131. if (maxCapacity === void 0) { maxCapacity = 64; }
  28132. if (maxDepth === void 0) { maxDepth = 2; }
  28133. if (!this._selectionOctree) {
  28134. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28135. }
  28136. var worldExtends = this.getWorldExtends();
  28137. // Update octree
  28138. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28139. return this._selectionOctree;
  28140. };
  28141. // Picking
  28142. /**
  28143. * Creates a ray that can be used to pick in the scene
  28144. * @param x defines the x coordinate of the origin (on-screen)
  28145. * @param y defines the y coordinate of the origin (on-screen)
  28146. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28147. * @param camera defines the camera to use for the picking
  28148. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28149. * @returns a Ray
  28150. */
  28151. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28152. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28153. var result = BABYLON.Ray.Zero();
  28154. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28155. return result;
  28156. };
  28157. /**
  28158. * Creates a ray that can be used to pick in the scene
  28159. * @param x defines the x coordinate of the origin (on-screen)
  28160. * @param y defines the y coordinate of the origin (on-screen)
  28161. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28162. * @param result defines the ray where to store the picking ray
  28163. * @param camera defines the camera to use for the picking
  28164. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28165. * @returns the current scene
  28166. */
  28167. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28168. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28169. var engine = this._engine;
  28170. if (!camera) {
  28171. if (!this.activeCamera)
  28172. throw new Error("Active camera not set");
  28173. camera = this.activeCamera;
  28174. }
  28175. var cameraViewport = camera.viewport;
  28176. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28177. // Moving coordinates to local viewport world
  28178. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28179. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28180. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28181. return this;
  28182. };
  28183. /**
  28184. * Creates a ray that can be used to pick in the scene
  28185. * @param x defines the x coordinate of the origin (on-screen)
  28186. * @param y defines the y coordinate of the origin (on-screen)
  28187. * @param camera defines the camera to use for the picking
  28188. * @returns a Ray
  28189. */
  28190. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28191. var result = BABYLON.Ray.Zero();
  28192. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28193. return result;
  28194. };
  28195. /**
  28196. * Creates a ray that can be used to pick in the scene
  28197. * @param x defines the x coordinate of the origin (on-screen)
  28198. * @param y defines the y coordinate of the origin (on-screen)
  28199. * @param result defines the ray where to store the picking ray
  28200. * @param camera defines the camera to use for the picking
  28201. * @returns the current scene
  28202. */
  28203. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28204. if (!BABYLON.PickingInfo) {
  28205. return this;
  28206. }
  28207. var engine = this._engine;
  28208. if (!camera) {
  28209. if (!this.activeCamera)
  28210. throw new Error("Active camera not set");
  28211. camera = this.activeCamera;
  28212. }
  28213. var cameraViewport = camera.viewport;
  28214. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28215. var identity = BABYLON.Matrix.Identity();
  28216. // Moving coordinates to local viewport world
  28217. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28218. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28219. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28220. return this;
  28221. };
  28222. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28223. if (!BABYLON.PickingInfo) {
  28224. return null;
  28225. }
  28226. var pickingInfo = null;
  28227. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28228. var mesh = this.meshes[meshIndex];
  28229. if (predicate) {
  28230. if (!predicate(mesh)) {
  28231. continue;
  28232. }
  28233. }
  28234. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28235. continue;
  28236. }
  28237. var world = mesh.getWorldMatrix();
  28238. var ray = rayFunction(world);
  28239. var result = mesh.intersects(ray, fastCheck);
  28240. if (!result || !result.hit)
  28241. continue;
  28242. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28243. continue;
  28244. pickingInfo = result;
  28245. if (fastCheck) {
  28246. break;
  28247. }
  28248. }
  28249. return pickingInfo || new BABYLON.PickingInfo();
  28250. };
  28251. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28252. if (!BABYLON.PickingInfo) {
  28253. return null;
  28254. }
  28255. var pickingInfos = new Array();
  28256. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28257. var mesh = this.meshes[meshIndex];
  28258. if (predicate) {
  28259. if (!predicate(mesh)) {
  28260. continue;
  28261. }
  28262. }
  28263. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28264. continue;
  28265. }
  28266. var world = mesh.getWorldMatrix();
  28267. var ray = rayFunction(world);
  28268. var result = mesh.intersects(ray, false);
  28269. if (!result || !result.hit)
  28270. continue;
  28271. pickingInfos.push(result);
  28272. }
  28273. return pickingInfos;
  28274. };
  28275. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28276. if (!BABYLON.PickingInfo) {
  28277. return null;
  28278. }
  28279. var pickingInfo = null;
  28280. if (!camera) {
  28281. if (!this.activeCamera) {
  28282. return null;
  28283. }
  28284. camera = this.activeCamera;
  28285. }
  28286. if (this.spriteManagers.length > 0) {
  28287. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28288. var spriteManager = this.spriteManagers[spriteIndex];
  28289. if (!spriteManager.isPickable) {
  28290. continue;
  28291. }
  28292. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28293. if (!result || !result.hit)
  28294. continue;
  28295. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28296. continue;
  28297. pickingInfo = result;
  28298. if (fastCheck) {
  28299. break;
  28300. }
  28301. }
  28302. }
  28303. return pickingInfo || new BABYLON.PickingInfo();
  28304. };
  28305. /** Launch a ray to try to pick a mesh in the scene
  28306. * @param x position on screen
  28307. * @param y position on screen
  28308. * @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
  28309. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28310. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28311. * @returns a PickingInfo
  28312. */
  28313. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28314. var _this = this;
  28315. if (!BABYLON.PickingInfo) {
  28316. return null;
  28317. }
  28318. return this._internalPick(function (world) {
  28319. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28320. return _this._tempPickingRay;
  28321. }, predicate, fastCheck);
  28322. };
  28323. /** Launch a ray to try to pick a sprite in the scene
  28324. * @param x position on screen
  28325. * @param y position on screen
  28326. * @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
  28327. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28328. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28329. * @returns a PickingInfo
  28330. */
  28331. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28332. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28333. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28334. };
  28335. /** Use the given ray to pick a mesh in the scene
  28336. * @param ray The ray to use to pick meshes
  28337. * @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
  28338. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28339. * @returns a PickingInfo
  28340. */
  28341. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28342. var _this = this;
  28343. return this._internalPick(function (world) {
  28344. if (!_this._pickWithRayInverseMatrix) {
  28345. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28346. }
  28347. world.invertToRef(_this._pickWithRayInverseMatrix);
  28348. if (!_this._cachedRayForTransform) {
  28349. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28350. }
  28351. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28352. return _this._cachedRayForTransform;
  28353. }, predicate, fastCheck);
  28354. };
  28355. /**
  28356. * Launch a ray to try to pick a mesh in the scene
  28357. * @param x X position on screen
  28358. * @param y Y position on screen
  28359. * @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
  28360. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28361. * @returns an array of PickingInfo
  28362. */
  28363. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28364. var _this = this;
  28365. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28366. };
  28367. /**
  28368. * Launch a ray to try to pick a mesh in the scene
  28369. * @param ray Ray to use
  28370. * @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
  28371. * @returns an array of PickingInfo
  28372. */
  28373. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28374. var _this = this;
  28375. return this._internalMultiPick(function (world) {
  28376. if (!_this._pickWithRayInverseMatrix) {
  28377. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28378. }
  28379. world.invertToRef(_this._pickWithRayInverseMatrix);
  28380. if (!_this._cachedRayForTransform) {
  28381. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28382. }
  28383. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28384. return _this._cachedRayForTransform;
  28385. }, predicate);
  28386. };
  28387. /**
  28388. * Force the value of meshUnderPointer
  28389. * @param mesh defines the mesh to use
  28390. */
  28391. Scene.prototype.setPointerOverMesh = function (mesh) {
  28392. if (this._pointerOverMesh === mesh) {
  28393. return;
  28394. }
  28395. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28396. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28397. }
  28398. this._pointerOverMesh = mesh;
  28399. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28400. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28401. }
  28402. };
  28403. /**
  28404. * Gets the mesh under the pointer
  28405. * @returns a Mesh or null if no mesh is under the pointer
  28406. */
  28407. Scene.prototype.getPointerOverMesh = function () {
  28408. return this._pointerOverMesh;
  28409. };
  28410. /**
  28411. * Force the sprite under the pointer
  28412. * @param sprite defines the sprite to use
  28413. */
  28414. Scene.prototype.setPointerOverSprite = function (sprite) {
  28415. if (this._pointerOverSprite === sprite) {
  28416. return;
  28417. }
  28418. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28419. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28420. }
  28421. this._pointerOverSprite = sprite;
  28422. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28423. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28424. }
  28425. };
  28426. /**
  28427. * Gets the sprite under the pointer
  28428. * @returns a Sprite or null if no sprite is under the pointer
  28429. */
  28430. Scene.prototype.getPointerOverSprite = function () {
  28431. return this._pointerOverSprite;
  28432. };
  28433. // Physics
  28434. /**
  28435. * Gets the current physics engine
  28436. * @returns a PhysicsEngine or null if none attached
  28437. */
  28438. Scene.prototype.getPhysicsEngine = function () {
  28439. return this._physicsEngine;
  28440. };
  28441. /**
  28442. * Enables physics to the current scene
  28443. * @param gravity defines the scene's gravity for the physics engine
  28444. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28445. * @return a boolean indicating if the physics engine was initialized
  28446. */
  28447. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28448. if (gravity === void 0) { gravity = null; }
  28449. if (this._physicsEngine) {
  28450. return true;
  28451. }
  28452. try {
  28453. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28454. return true;
  28455. }
  28456. catch (e) {
  28457. BABYLON.Tools.Error(e.message);
  28458. return false;
  28459. }
  28460. };
  28461. /**
  28462. * Disables and disposes the physics engine associated with the scene
  28463. */
  28464. Scene.prototype.disablePhysicsEngine = function () {
  28465. if (!this._physicsEngine) {
  28466. return;
  28467. }
  28468. this._physicsEngine.dispose();
  28469. this._physicsEngine = null;
  28470. };
  28471. /**
  28472. * Gets a boolean indicating if there is an active physics engine
  28473. * @returns a boolean indicating if there is an active physics engine
  28474. */
  28475. Scene.prototype.isPhysicsEnabled = function () {
  28476. return this._physicsEngine !== undefined;
  28477. };
  28478. /**
  28479. * Deletes a physics compound impostor
  28480. * @param compound defines the compound to delete
  28481. */
  28482. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28483. var mesh = compound.parts[0].mesh;
  28484. if (mesh.physicsImpostor) {
  28485. mesh.physicsImpostor.dispose( /*true*/);
  28486. mesh.physicsImpostor = null;
  28487. }
  28488. };
  28489. // Misc.
  28490. /** @hidden */
  28491. Scene.prototype._rebuildGeometries = function () {
  28492. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28493. var geometry = _a[_i];
  28494. geometry._rebuild();
  28495. }
  28496. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28497. var mesh = _c[_b];
  28498. mesh._rebuild();
  28499. }
  28500. if (this.postProcessManager) {
  28501. this.postProcessManager._rebuild();
  28502. }
  28503. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28504. var layer = _e[_d];
  28505. layer._rebuild();
  28506. }
  28507. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28508. var effectLayer = _g[_f];
  28509. effectLayer._rebuild();
  28510. }
  28511. if (this._boundingBoxRenderer) {
  28512. this._boundingBoxRenderer._rebuild();
  28513. }
  28514. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28515. var system = _j[_h];
  28516. system.rebuild();
  28517. }
  28518. if (this._postProcessRenderPipelineManager) {
  28519. this._postProcessRenderPipelineManager._rebuild();
  28520. }
  28521. };
  28522. /** @hidden */
  28523. Scene.prototype._rebuildTextures = function () {
  28524. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28525. var texture = _a[_i];
  28526. texture._rebuild();
  28527. }
  28528. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28529. };
  28530. /**
  28531. * Creates a default light for the scene.
  28532. * @param replace Whether to replace the existing lights in the scene.
  28533. */
  28534. Scene.prototype.createDefaultLight = function (replace) {
  28535. if (replace === void 0) { replace = false; }
  28536. // Dispose existing light in replace mode.
  28537. if (replace) {
  28538. if (this.lights) {
  28539. for (var i = 0; i < this.lights.length; i++) {
  28540. this.lights[i].dispose();
  28541. }
  28542. }
  28543. }
  28544. // Light
  28545. if (this.lights.length === 0) {
  28546. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28547. }
  28548. };
  28549. /**
  28550. * Creates a default camera for the scene.
  28551. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28552. * @param replace Whether to replace the existing active camera in the scene.
  28553. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28554. */
  28555. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28556. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28557. if (replace === void 0) { replace = false; }
  28558. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28559. // Dispose existing camera in replace mode.
  28560. if (replace) {
  28561. if (this.activeCamera) {
  28562. this.activeCamera.dispose();
  28563. this.activeCamera = null;
  28564. }
  28565. }
  28566. // Camera
  28567. if (!this.activeCamera) {
  28568. var worldExtends = this.getWorldExtends();
  28569. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28570. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28571. var camera;
  28572. var radius = worldSize.length() * 1.5;
  28573. // empty scene scenario!
  28574. if (!isFinite(radius)) {
  28575. radius = 1;
  28576. worldCenter.copyFromFloats(0, 0, 0);
  28577. }
  28578. if (createArcRotateCamera) {
  28579. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28580. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28581. arcRotateCamera.wheelPrecision = 100 / radius;
  28582. camera = arcRotateCamera;
  28583. }
  28584. else {
  28585. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28586. freeCamera.setTarget(worldCenter);
  28587. camera = freeCamera;
  28588. }
  28589. camera.minZ = radius * 0.01;
  28590. camera.maxZ = radius * 1000;
  28591. camera.speed = radius * 0.2;
  28592. this.activeCamera = camera;
  28593. var canvas = this.getEngine().getRenderingCanvas();
  28594. if (attachCameraControls && canvas) {
  28595. camera.attachControl(canvas);
  28596. }
  28597. }
  28598. };
  28599. /**
  28600. * Creates a default camera and a default light
  28601. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28602. * @param replace defines if the camera and/or light will replace the existing ones
  28603. * @param attachCameraControls defines if attachControl will be called on the new camera
  28604. */
  28605. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28606. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28607. if (replace === void 0) { replace = false; }
  28608. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28609. this.createDefaultLight(replace);
  28610. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28611. };
  28612. /**
  28613. * Creates a new sky box
  28614. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28615. * @param environmentTexture defines the texture to use as environment texture
  28616. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28617. * @param scale defines the overall scale of the skybox
  28618. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28619. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28620. * @returns a new mesh holding the sky box
  28621. */
  28622. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28623. if (pbr === void 0) { pbr = false; }
  28624. if (scale === void 0) { scale = 1000; }
  28625. if (blur === void 0) { blur = 0; }
  28626. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28627. if (!environmentTexture) {
  28628. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28629. return null;
  28630. }
  28631. if (setGlobalEnvTexture) {
  28632. if (environmentTexture) {
  28633. this.environmentTexture = environmentTexture;
  28634. }
  28635. }
  28636. // Skybox
  28637. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28638. if (pbr) {
  28639. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28640. hdrSkyboxMaterial.backFaceCulling = false;
  28641. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28642. if (hdrSkyboxMaterial.reflectionTexture) {
  28643. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28644. }
  28645. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28646. hdrSkyboxMaterial.disableLighting = true;
  28647. hdrSkyboxMaterial.twoSidedLighting = true;
  28648. hdrSkybox.infiniteDistance = true;
  28649. hdrSkybox.material = hdrSkyboxMaterial;
  28650. }
  28651. else {
  28652. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28653. skyboxMaterial.backFaceCulling = false;
  28654. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28655. if (skyboxMaterial.reflectionTexture) {
  28656. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28657. }
  28658. skyboxMaterial.disableLighting = true;
  28659. hdrSkybox.infiniteDistance = true;
  28660. hdrSkybox.material = skyboxMaterial;
  28661. }
  28662. return hdrSkybox;
  28663. };
  28664. /**
  28665. * Creates a new environment
  28666. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28667. * @param options defines the options you can use to configure the environment
  28668. * @returns the new EnvironmentHelper
  28669. */
  28670. Scene.prototype.createDefaultEnvironment = function (options) {
  28671. if (BABYLON.EnvironmentHelper) {
  28672. return new BABYLON.EnvironmentHelper(options, this);
  28673. }
  28674. return null;
  28675. };
  28676. /**
  28677. * Creates a new VREXperienceHelper
  28678. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28679. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28680. * @returns a new VREXperienceHelper
  28681. */
  28682. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28683. if (webVROptions === void 0) { webVROptions = {}; }
  28684. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28685. };
  28686. // Tags
  28687. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28688. if (tagsQuery === undefined) {
  28689. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28690. return list;
  28691. }
  28692. var listByTags = [];
  28693. forEach = forEach || (function (item) { return; });
  28694. for (var i in list) {
  28695. var item = list[i];
  28696. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28697. listByTags.push(item);
  28698. forEach(item);
  28699. }
  28700. }
  28701. return listByTags;
  28702. };
  28703. /**
  28704. * Get a list of meshes by tags
  28705. * @param tagsQuery defines the tags query to use
  28706. * @param forEach defines a predicate used to filter results
  28707. * @returns an array of Mesh
  28708. */
  28709. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28710. return this._getByTags(this.meshes, tagsQuery, forEach);
  28711. };
  28712. /**
  28713. * Get a list of cameras by tags
  28714. * @param tagsQuery defines the tags query to use
  28715. * @param forEach defines a predicate used to filter results
  28716. * @returns an array of Camera
  28717. */
  28718. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28719. return this._getByTags(this.cameras, tagsQuery, forEach);
  28720. };
  28721. /**
  28722. * Get a list of lights by tags
  28723. * @param tagsQuery defines the tags query to use
  28724. * @param forEach defines a predicate used to filter results
  28725. * @returns an array of Light
  28726. */
  28727. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28728. return this._getByTags(this.lights, tagsQuery, forEach);
  28729. };
  28730. /**
  28731. * Get a list of materials by tags
  28732. * @param tagsQuery defines the tags query to use
  28733. * @param forEach defines a predicate used to filter results
  28734. * @returns an array of Material
  28735. */
  28736. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28737. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28738. };
  28739. /**
  28740. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28741. * This allowed control for front to back rendering or reversly depending of the special needs.
  28742. *
  28743. * @param renderingGroupId The rendering group id corresponding to its index
  28744. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28745. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28746. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28747. */
  28748. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28749. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28750. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28751. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28752. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28753. };
  28754. /**
  28755. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28756. *
  28757. * @param renderingGroupId The rendering group id corresponding to its index
  28758. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28759. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28760. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28761. */
  28762. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28763. if (depth === void 0) { depth = true; }
  28764. if (stencil === void 0) { stencil = true; }
  28765. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28766. };
  28767. /**
  28768. * Will flag all materials as dirty to trigger new shader compilation
  28769. * @param flag defines the flag used to specify which material part must be marked as dirty
  28770. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28771. */
  28772. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28773. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28774. var material = _a[_i];
  28775. if (predicate && !predicate(material)) {
  28776. continue;
  28777. }
  28778. material.markAsDirty(flag);
  28779. }
  28780. };
  28781. /** @hidden */
  28782. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28783. var _this = this;
  28784. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28785. this._activeRequests.push(request);
  28786. request.onCompleteObservable.add(function (request) {
  28787. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28788. });
  28789. return request;
  28790. };
  28791. /** @hidden */
  28792. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28793. var _this = this;
  28794. return new Promise(function (resolve, reject) {
  28795. _this._loadFile(url, function (data) {
  28796. resolve(data);
  28797. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28798. reject(exception);
  28799. });
  28800. });
  28801. };
  28802. // Statics
  28803. Scene._FOGMODE_NONE = 0;
  28804. Scene._FOGMODE_EXP = 1;
  28805. Scene._FOGMODE_EXP2 = 2;
  28806. Scene._FOGMODE_LINEAR = 3;
  28807. Scene._uniqueIdCounter = 0;
  28808. /**
  28809. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28810. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28811. */
  28812. Scene.MinDeltaTime = 1.0;
  28813. /**
  28814. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28815. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28816. */
  28817. Scene.MaxDeltaTime = 1000.0;
  28818. /** The distance in pixel that you have to move to prevent some events */
  28819. Scene.DragMovementThreshold = 10; // in pixels
  28820. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28821. Scene.LongPressDelay = 500; // in milliseconds
  28822. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28823. Scene.DoubleClickDelay = 300; // in milliseconds
  28824. /** If you need to check double click without raising a single click at first click, enable this flag */
  28825. Scene.ExclusiveDoubleClickMode = false;
  28826. return Scene;
  28827. }());
  28828. BABYLON.Scene = Scene;
  28829. })(BABYLON || (BABYLON = {}));
  28830. //# sourceMappingURL=babylon.scene.js.map
  28831. var BABYLON;
  28832. (function (BABYLON) {
  28833. /**
  28834. * Set of assets to keep when moving a scene into an asset container.
  28835. */
  28836. var KeepAssets = /** @class */ (function () {
  28837. function KeepAssets() {
  28838. /**
  28839. * Cameras to keep.
  28840. */
  28841. this.cameras = new Array();
  28842. /**
  28843. * Lights to keep.
  28844. */
  28845. this.lights = new Array();
  28846. /**
  28847. * Meshes to keep.
  28848. */
  28849. this.meshes = new Array();
  28850. /**
  28851. * Skeletons to keep.
  28852. */
  28853. this.skeletons = new Array();
  28854. /**
  28855. * ParticleSystems to keep.
  28856. */
  28857. this.particleSystems = new Array();
  28858. /**
  28859. * Animations to keep.
  28860. */
  28861. this.animations = new Array();
  28862. /**
  28863. * AnimationGroups to keep.
  28864. */
  28865. this.animationGroups = new Array();
  28866. /**
  28867. * MultiMaterials to keep.
  28868. */
  28869. this.multiMaterials = new Array();
  28870. /**
  28871. * Materials to keep.
  28872. */
  28873. this.materials = new Array();
  28874. /**
  28875. * MorphTargetManagers to keep.
  28876. */
  28877. this.morphTargetManagers = new Array();
  28878. /**
  28879. * Geometries to keep.
  28880. */
  28881. this.geometries = new Array();
  28882. /**
  28883. * TransformNodes to keep.
  28884. */
  28885. this.transformNodes = new Array();
  28886. /**
  28887. * LensFlareSystems to keep.
  28888. */
  28889. this.lensFlareSystems = new Array();
  28890. /**
  28891. * ShadowGenerators to keep.
  28892. */
  28893. this.shadowGenerators = new Array();
  28894. /**
  28895. * ActionManagers to keep.
  28896. */
  28897. this.actionManagers = new Array();
  28898. /**
  28899. * Sounds to keep.
  28900. */
  28901. this.sounds = new Array();
  28902. /**
  28903. * Textures to keep.
  28904. */
  28905. this.textures = new Array();
  28906. /**
  28907. * Effect layers to keep.
  28908. */
  28909. this.effectLayers = new Array();
  28910. }
  28911. return KeepAssets;
  28912. }());
  28913. BABYLON.KeepAssets = KeepAssets;
  28914. /**
  28915. * Container with a set of assets that can be added or removed from a scene.
  28916. */
  28917. var AssetContainer = /** @class */ (function () {
  28918. /**
  28919. * Instantiates an AssetContainer.
  28920. * @param scene The scene the AssetContainer belongs to.
  28921. */
  28922. function AssetContainer(scene) {
  28923. // Objects
  28924. /**
  28925. * Cameras populated in the container.
  28926. */
  28927. this.cameras = new Array();
  28928. /**
  28929. * Lights populated in the container.
  28930. */
  28931. this.lights = new Array();
  28932. /**
  28933. * Meshes populated in the container.
  28934. */
  28935. this.meshes = new Array();
  28936. /**
  28937. * Skeletons populated in the container.
  28938. */
  28939. this.skeletons = new Array();
  28940. /**
  28941. * ParticleSystems populated in the container.
  28942. */
  28943. this.particleSystems = new Array();
  28944. /**
  28945. * Animations populated in the container.
  28946. */
  28947. this.animations = new Array();
  28948. /**
  28949. * AnimationGroups populated in the container.
  28950. */
  28951. this.animationGroups = new Array();
  28952. /**
  28953. * MultiMaterials populated in the container.
  28954. */
  28955. this.multiMaterials = new Array();
  28956. /**
  28957. * Materials populated in the container.
  28958. */
  28959. this.materials = new Array();
  28960. /**
  28961. * MorphTargetManagers populated in the container.
  28962. */
  28963. this.morphTargetManagers = new Array();
  28964. /**
  28965. * Geometries populated in the container.
  28966. */
  28967. this.geometries = new Array();
  28968. /**
  28969. * TransformNodes populated in the container.
  28970. */
  28971. this.transformNodes = new Array();
  28972. /**
  28973. * LensFlareSystems populated in the container.
  28974. */
  28975. this.lensFlareSystems = new Array();
  28976. /**
  28977. * ShadowGenerators populated in the container.
  28978. */
  28979. this.shadowGenerators = new Array();
  28980. /**
  28981. * ActionManagers populated in the container.
  28982. */
  28983. this.actionManagers = new Array();
  28984. /**
  28985. * Sounds populated in the container.
  28986. */
  28987. this.sounds = new Array();
  28988. /**
  28989. * Textures populated in the container.
  28990. */
  28991. this.textures = new Array();
  28992. /**
  28993. * Effect layers populated in the container.
  28994. */
  28995. this.effectLayers = new Array();
  28996. this.scene = scene;
  28997. }
  28998. /**
  28999. * Adds all the assets from the container to the scene.
  29000. */
  29001. AssetContainer.prototype.addAllToScene = function () {
  29002. var _this = this;
  29003. this.cameras.forEach(function (o) {
  29004. _this.scene.addCamera(o);
  29005. });
  29006. this.lights.forEach(function (o) {
  29007. _this.scene.addLight(o);
  29008. });
  29009. this.meshes.forEach(function (o) {
  29010. _this.scene.addMesh(o);
  29011. });
  29012. this.skeletons.forEach(function (o) {
  29013. _this.scene.addSkeleton(o);
  29014. });
  29015. this.particleSystems.forEach(function (o) {
  29016. _this.scene.addParticleSystem(o);
  29017. });
  29018. this.animations.forEach(function (o) {
  29019. _this.scene.addAnimation(o);
  29020. });
  29021. this.animationGroups.forEach(function (o) {
  29022. _this.scene.addAnimationGroup(o);
  29023. });
  29024. this.multiMaterials.forEach(function (o) {
  29025. _this.scene.addMultiMaterial(o);
  29026. });
  29027. this.materials.forEach(function (o) {
  29028. _this.scene.addMaterial(o);
  29029. });
  29030. this.morphTargetManagers.forEach(function (o) {
  29031. _this.scene.addMorphTargetManager(o);
  29032. });
  29033. this.geometries.forEach(function (o) {
  29034. _this.scene.addGeometry(o);
  29035. });
  29036. this.transformNodes.forEach(function (o) {
  29037. _this.scene.addTransformNode(o);
  29038. });
  29039. this.lensFlareSystems.forEach(function (o) {
  29040. _this.scene.addLensFlareSystem(o);
  29041. });
  29042. this.actionManagers.forEach(function (o) {
  29043. _this.scene.addActionManager(o);
  29044. });
  29045. this.sounds.forEach(function (o) {
  29046. o.play();
  29047. o.autoplay = true;
  29048. _this.scene.mainSoundTrack.AddSound(o);
  29049. });
  29050. this.textures.forEach(function (o) {
  29051. _this.scene.addTexture(o);
  29052. });
  29053. this.effectLayers.forEach(function (o) {
  29054. _this.scene.addEffectLayer(o);
  29055. });
  29056. };
  29057. /**
  29058. * Removes all the assets in the container from the scene
  29059. */
  29060. AssetContainer.prototype.removeAllFromScene = function () {
  29061. var _this = this;
  29062. this.cameras.forEach(function (o) {
  29063. _this.scene.removeCamera(o);
  29064. });
  29065. this.lights.forEach(function (o) {
  29066. _this.scene.removeLight(o);
  29067. });
  29068. this.meshes.forEach(function (o) {
  29069. _this.scene.removeMesh(o);
  29070. });
  29071. this.skeletons.forEach(function (o) {
  29072. _this.scene.removeSkeleton(o);
  29073. });
  29074. this.particleSystems.forEach(function (o) {
  29075. _this.scene.removeParticleSystem(o);
  29076. });
  29077. this.animations.forEach(function (o) {
  29078. _this.scene.removeAnimation(o);
  29079. });
  29080. this.animationGroups.forEach(function (o) {
  29081. _this.scene.removeAnimationGroup(o);
  29082. });
  29083. this.multiMaterials.forEach(function (o) {
  29084. _this.scene.removeMultiMaterial(o);
  29085. });
  29086. this.materials.forEach(function (o) {
  29087. _this.scene.removeMaterial(o);
  29088. });
  29089. this.morphTargetManagers.forEach(function (o) {
  29090. _this.scene.removeMorphTargetManager(o);
  29091. });
  29092. this.geometries.forEach(function (o) {
  29093. _this.scene.removeGeometry(o);
  29094. });
  29095. this.transformNodes.forEach(function (o) {
  29096. _this.scene.removeTransformNode(o);
  29097. });
  29098. this.lensFlareSystems.forEach(function (o) {
  29099. _this.scene.removeLensFlareSystem(o);
  29100. });
  29101. this.actionManagers.forEach(function (o) {
  29102. _this.scene.removeActionManager(o);
  29103. });
  29104. this.sounds.forEach(function (o) {
  29105. o.stop();
  29106. o.autoplay = false;
  29107. _this.scene.mainSoundTrack.RemoveSound(o);
  29108. });
  29109. this.textures.forEach(function (o) {
  29110. _this.scene.removeTexture(o);
  29111. });
  29112. this.effectLayers.forEach(function (o) {
  29113. _this.scene.removeEffectLayer(o);
  29114. });
  29115. };
  29116. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29117. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29118. var asset = sourceAssets_1[_i];
  29119. var move = true;
  29120. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29121. var keepAsset = keepAssets_1[_a];
  29122. if (asset === keepAsset) {
  29123. move = false;
  29124. break;
  29125. }
  29126. }
  29127. if (move) {
  29128. targetAssets.push(asset);
  29129. }
  29130. }
  29131. };
  29132. /**
  29133. * Removes all the assets contained in the scene and adds them to the container.
  29134. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29135. */
  29136. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29137. if (keepAssets === undefined) {
  29138. keepAssets = new KeepAssets();
  29139. }
  29140. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29141. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29142. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29143. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29144. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29145. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29146. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29147. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29148. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29149. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29150. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29151. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29152. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29153. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29154. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29155. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29156. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29157. this.removeAllFromScene();
  29158. };
  29159. return AssetContainer;
  29160. }());
  29161. BABYLON.AssetContainer = AssetContainer;
  29162. })(BABYLON || (BABYLON = {}));
  29163. //# sourceMappingURL=babylon.assetContainer.js.map
  29164. var BABYLON;
  29165. (function (BABYLON) {
  29166. var Buffer = /** @class */ (function () {
  29167. /**
  29168. * Constructor
  29169. * @param engine the engine
  29170. * @param data the data to use for this buffer
  29171. * @param updatable whether the data is updatable
  29172. * @param stride the stride (optional)
  29173. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29174. * @param instanced whether the buffer is instanced (optional)
  29175. * @param useBytes set to true if the stride in in bytes (optional)
  29176. */
  29177. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29178. if (stride === void 0) { stride = 0; }
  29179. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29180. if (instanced === void 0) { instanced = false; }
  29181. if (useBytes === void 0) { useBytes = false; }
  29182. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29183. this._engine = engine.getScene().getEngine();
  29184. }
  29185. else {
  29186. this._engine = engine;
  29187. }
  29188. this._updatable = updatable;
  29189. this._instanced = instanced;
  29190. this._data = data;
  29191. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29192. if (!postponeInternalCreation) { // by default
  29193. this.create();
  29194. }
  29195. }
  29196. /**
  29197. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29198. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29199. * @param offset defines offset in the buffer (0 by default)
  29200. * @param size defines the size in floats of attributes (position is 3 for instance)
  29201. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29202. * @param instanced defines if the vertex buffer contains indexed data
  29203. * @param useBytes defines if the offset and stride are in bytes
  29204. * @returns the new vertex buffer
  29205. */
  29206. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29207. if (useBytes === void 0) { useBytes = false; }
  29208. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29209. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29210. // a lot of these parameters are ignored as they are overriden by the buffer
  29211. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29212. };
  29213. // Properties
  29214. Buffer.prototype.isUpdatable = function () {
  29215. return this._updatable;
  29216. };
  29217. Buffer.prototype.getData = function () {
  29218. return this._data;
  29219. };
  29220. Buffer.prototype.getBuffer = function () {
  29221. return this._buffer;
  29222. };
  29223. /**
  29224. * Gets the stride in float32 units (i.e. byte stride / 4).
  29225. * May not be an integer if the byte stride is not divisible by 4.
  29226. * DEPRECATED. Use byteStride instead.
  29227. * @returns the stride in float32 units
  29228. */
  29229. Buffer.prototype.getStrideSize = function () {
  29230. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29231. };
  29232. // Methods
  29233. Buffer.prototype.create = function (data) {
  29234. if (data === void 0) { data = null; }
  29235. if (!data && this._buffer) {
  29236. return; // nothing to do
  29237. }
  29238. data = data || this._data;
  29239. if (!data) {
  29240. return;
  29241. }
  29242. if (!this._buffer) { // create buffer
  29243. if (this._updatable) {
  29244. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29245. this._data = data;
  29246. }
  29247. else {
  29248. this._buffer = this._engine.createVertexBuffer(data);
  29249. }
  29250. }
  29251. else if (this._updatable) { // update buffer
  29252. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29253. this._data = data;
  29254. }
  29255. };
  29256. Buffer.prototype._rebuild = function () {
  29257. this._buffer = null;
  29258. this.create(this._data);
  29259. };
  29260. Buffer.prototype.update = function (data) {
  29261. this.create(data);
  29262. };
  29263. /**
  29264. * Updates the data directly.
  29265. * @param data the new data
  29266. * @param offset the new offset
  29267. * @param vertexCount the vertex count (optional)
  29268. * @param useBytes set to true if the offset is in bytes
  29269. */
  29270. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29271. if (useBytes === void 0) { useBytes = false; }
  29272. if (!this._buffer) {
  29273. return;
  29274. }
  29275. if (this._updatable) { // update buffer
  29276. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29277. this._data = null;
  29278. }
  29279. };
  29280. Buffer.prototype.dispose = function () {
  29281. if (!this._buffer) {
  29282. return;
  29283. }
  29284. if (this._engine._releaseBuffer(this._buffer)) {
  29285. this._buffer = null;
  29286. }
  29287. };
  29288. return Buffer;
  29289. }());
  29290. BABYLON.Buffer = Buffer;
  29291. })(BABYLON || (BABYLON = {}));
  29292. //# sourceMappingURL=babylon.buffer.js.map
  29293. var BABYLON;
  29294. (function (BABYLON) {
  29295. var VertexBuffer = /** @class */ (function () {
  29296. /**
  29297. * Constructor
  29298. * @param engine the engine
  29299. * @param data the data to use for this vertex buffer
  29300. * @param kind the vertex buffer kind
  29301. * @param updatable whether the data is updatable
  29302. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29303. * @param stride the stride (optional)
  29304. * @param instanced whether the buffer is instanced (optional)
  29305. * @param offset the offset of the data (optional)
  29306. * @param size the number of components (optional)
  29307. * @param type the type of the component (optional)
  29308. * @param normalized whether the data contains normalized data (optional)
  29309. * @param useBytes set to true if stride and offset are in bytes (optional)
  29310. */
  29311. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29312. if (normalized === void 0) { normalized = false; }
  29313. if (useBytes === void 0) { useBytes = false; }
  29314. if (data instanceof BABYLON.Buffer) {
  29315. this._buffer = data;
  29316. this._ownsBuffer = false;
  29317. }
  29318. else {
  29319. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29320. this._ownsBuffer = true;
  29321. }
  29322. this._kind = kind;
  29323. if (type == undefined) {
  29324. var data_1 = this.getData();
  29325. this.type = VertexBuffer.FLOAT;
  29326. if (data_1 instanceof Int8Array)
  29327. this.type = VertexBuffer.BYTE;
  29328. else if (data_1 instanceof Uint8Array)
  29329. this.type = VertexBuffer.UNSIGNED_BYTE;
  29330. else if (data_1 instanceof Int16Array)
  29331. this.type = VertexBuffer.SHORT;
  29332. else if (data_1 instanceof Uint16Array)
  29333. this.type = VertexBuffer.UNSIGNED_SHORT;
  29334. else if (data_1 instanceof Int32Array)
  29335. this.type = VertexBuffer.INT;
  29336. else if (data_1 instanceof Uint32Array)
  29337. this.type = VertexBuffer.UNSIGNED_INT;
  29338. }
  29339. else {
  29340. this.type = type;
  29341. }
  29342. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29343. if (useBytes) {
  29344. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29345. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29346. this.byteOffset = offset || 0;
  29347. }
  29348. else {
  29349. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29350. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29351. this.byteOffset = (offset || 0) * typeByteLength;
  29352. }
  29353. this.normalized = normalized;
  29354. this._instanced = instanced !== undefined ? instanced : false;
  29355. this._instanceDivisor = instanced ? 1 : 0;
  29356. }
  29357. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29358. /**
  29359. * Gets or sets the instance divisor when in instanced mode
  29360. */
  29361. get: function () {
  29362. return this._instanceDivisor;
  29363. },
  29364. set: function (value) {
  29365. this._instanceDivisor = value;
  29366. if (value == 0) {
  29367. this._instanced = false;
  29368. }
  29369. else {
  29370. this._instanced = true;
  29371. }
  29372. },
  29373. enumerable: true,
  29374. configurable: true
  29375. });
  29376. VertexBuffer.prototype._rebuild = function () {
  29377. if (!this._buffer) {
  29378. return;
  29379. }
  29380. this._buffer._rebuild();
  29381. };
  29382. /**
  29383. * Returns the kind of the VertexBuffer (string).
  29384. */
  29385. VertexBuffer.prototype.getKind = function () {
  29386. return this._kind;
  29387. };
  29388. // Properties
  29389. /**
  29390. * Boolean : is the VertexBuffer updatable ?
  29391. */
  29392. VertexBuffer.prototype.isUpdatable = function () {
  29393. return this._buffer.isUpdatable();
  29394. };
  29395. /**
  29396. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29397. */
  29398. VertexBuffer.prototype.getData = function () {
  29399. return this._buffer.getData();
  29400. };
  29401. /**
  29402. * Returns the WebGLBuffer associated to the VertexBuffer.
  29403. */
  29404. VertexBuffer.prototype.getBuffer = function () {
  29405. return this._buffer.getBuffer();
  29406. };
  29407. /**
  29408. * Returns the stride as a multiple of the type byte length.
  29409. * DEPRECATED. Use byteStride instead.
  29410. */
  29411. VertexBuffer.prototype.getStrideSize = function () {
  29412. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29413. };
  29414. /**
  29415. * Returns the offset as a multiple of the type byte length.
  29416. * DEPRECATED. Use byteOffset instead.
  29417. */
  29418. VertexBuffer.prototype.getOffset = function () {
  29419. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29420. };
  29421. /**
  29422. * Returns the number of components per vertex attribute (integer).
  29423. */
  29424. VertexBuffer.prototype.getSize = function () {
  29425. return this._size;
  29426. };
  29427. /**
  29428. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29429. */
  29430. VertexBuffer.prototype.getIsInstanced = function () {
  29431. return this._instanced;
  29432. };
  29433. /**
  29434. * Returns the instancing divisor, zero for non-instanced (integer).
  29435. */
  29436. VertexBuffer.prototype.getInstanceDivisor = function () {
  29437. return this._instanceDivisor;
  29438. };
  29439. // Methods
  29440. /**
  29441. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29442. * Returns the created WebGLBuffer.
  29443. */
  29444. VertexBuffer.prototype.create = function (data) {
  29445. return this._buffer.create(data);
  29446. };
  29447. /**
  29448. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29449. * This function will create a new buffer if the current one is not updatable
  29450. * Returns the updated WebGLBuffer.
  29451. */
  29452. VertexBuffer.prototype.update = function (data) {
  29453. return this._buffer.update(data);
  29454. };
  29455. /**
  29456. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29457. * Returns the directly updated WebGLBuffer.
  29458. * @param data the new data
  29459. * @param offset the new offset
  29460. * @param useBytes set to true if the offset is in bytes
  29461. */
  29462. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29463. if (useBytes === void 0) { useBytes = false; }
  29464. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29465. };
  29466. /**
  29467. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29468. */
  29469. VertexBuffer.prototype.dispose = function () {
  29470. if (this._ownsBuffer) {
  29471. this._buffer.dispose();
  29472. }
  29473. };
  29474. /**
  29475. * Enumerates each value of this vertex buffer as numbers.
  29476. * @param count the number of values to enumerate
  29477. * @param callback the callback function called for each value
  29478. */
  29479. VertexBuffer.prototype.forEach = function (count, callback) {
  29480. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29481. };
  29482. Object.defineProperty(VertexBuffer, "PositionKind", {
  29483. get: function () {
  29484. return VertexBuffer._PositionKind;
  29485. },
  29486. enumerable: true,
  29487. configurable: true
  29488. });
  29489. Object.defineProperty(VertexBuffer, "NormalKind", {
  29490. get: function () {
  29491. return VertexBuffer._NormalKind;
  29492. },
  29493. enumerable: true,
  29494. configurable: true
  29495. });
  29496. Object.defineProperty(VertexBuffer, "TangentKind", {
  29497. get: function () {
  29498. return VertexBuffer._TangentKind;
  29499. },
  29500. enumerable: true,
  29501. configurable: true
  29502. });
  29503. Object.defineProperty(VertexBuffer, "UVKind", {
  29504. get: function () {
  29505. return VertexBuffer._UVKind;
  29506. },
  29507. enumerable: true,
  29508. configurable: true
  29509. });
  29510. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29511. get: function () {
  29512. return VertexBuffer._UV2Kind;
  29513. },
  29514. enumerable: true,
  29515. configurable: true
  29516. });
  29517. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29518. get: function () {
  29519. return VertexBuffer._UV3Kind;
  29520. },
  29521. enumerable: true,
  29522. configurable: true
  29523. });
  29524. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29525. get: function () {
  29526. return VertexBuffer._UV4Kind;
  29527. },
  29528. enumerable: true,
  29529. configurable: true
  29530. });
  29531. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29532. get: function () {
  29533. return VertexBuffer._UV5Kind;
  29534. },
  29535. enumerable: true,
  29536. configurable: true
  29537. });
  29538. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29539. get: function () {
  29540. return VertexBuffer._UV6Kind;
  29541. },
  29542. enumerable: true,
  29543. configurable: true
  29544. });
  29545. Object.defineProperty(VertexBuffer, "ColorKind", {
  29546. get: function () {
  29547. return VertexBuffer._ColorKind;
  29548. },
  29549. enumerable: true,
  29550. configurable: true
  29551. });
  29552. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29553. get: function () {
  29554. return VertexBuffer._MatricesIndicesKind;
  29555. },
  29556. enumerable: true,
  29557. configurable: true
  29558. });
  29559. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29560. get: function () {
  29561. return VertexBuffer._MatricesWeightsKind;
  29562. },
  29563. enumerable: true,
  29564. configurable: true
  29565. });
  29566. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29567. get: function () {
  29568. return VertexBuffer._MatricesIndicesExtraKind;
  29569. },
  29570. enumerable: true,
  29571. configurable: true
  29572. });
  29573. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29574. get: function () {
  29575. return VertexBuffer._MatricesWeightsExtraKind;
  29576. },
  29577. enumerable: true,
  29578. configurable: true
  29579. });
  29580. /**
  29581. * Deduces the stride given a kind.
  29582. * @param kind The kind string to deduce
  29583. * @returns The deduced stride
  29584. */
  29585. VertexBuffer.DeduceStride = function (kind) {
  29586. switch (kind) {
  29587. case VertexBuffer.UVKind:
  29588. case VertexBuffer.UV2Kind:
  29589. case VertexBuffer.UV3Kind:
  29590. case VertexBuffer.UV4Kind:
  29591. case VertexBuffer.UV5Kind:
  29592. case VertexBuffer.UV6Kind:
  29593. return 2;
  29594. case VertexBuffer.NormalKind:
  29595. case VertexBuffer.PositionKind:
  29596. return 3;
  29597. case VertexBuffer.ColorKind:
  29598. case VertexBuffer.MatricesIndicesKind:
  29599. case VertexBuffer.MatricesIndicesExtraKind:
  29600. case VertexBuffer.MatricesWeightsKind:
  29601. case VertexBuffer.MatricesWeightsExtraKind:
  29602. case VertexBuffer.TangentKind:
  29603. return 4;
  29604. default:
  29605. throw new Error("Invalid kind '" + kind + "'");
  29606. }
  29607. };
  29608. /**
  29609. * Gets the byte length of the given type.
  29610. * @param type the type
  29611. * @returns the number of bytes
  29612. */
  29613. VertexBuffer.GetTypeByteLength = function (type) {
  29614. switch (type) {
  29615. case VertexBuffer.BYTE:
  29616. case VertexBuffer.UNSIGNED_BYTE:
  29617. return 1;
  29618. case VertexBuffer.SHORT:
  29619. case VertexBuffer.UNSIGNED_SHORT:
  29620. return 2;
  29621. case VertexBuffer.INT:
  29622. case VertexBuffer.FLOAT:
  29623. return 4;
  29624. default:
  29625. throw new Error("Invalid type '" + type + "'");
  29626. }
  29627. };
  29628. /**
  29629. * Enumerates each value of the given parameters as numbers.
  29630. * @param data the data to enumerate
  29631. * @param byteOffset the byte offset of the data
  29632. * @param byteStride the byte stride of the data
  29633. * @param componentCount the number of components per element
  29634. * @param componentType the type of the component
  29635. * @param count the total number of components
  29636. * @param normalized whether the data is normalized
  29637. * @param callback the callback function called for each value
  29638. */
  29639. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29640. if (data instanceof Array) {
  29641. var offset = byteOffset / 4;
  29642. var stride = byteStride / 4;
  29643. for (var index = 0; index < count; index += componentCount) {
  29644. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29645. callback(data[offset + componentIndex], index + componentIndex);
  29646. }
  29647. offset += stride;
  29648. }
  29649. }
  29650. else {
  29651. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29652. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29653. for (var index = 0; index < count; index += componentCount) {
  29654. var componentByteOffset = byteOffset;
  29655. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29656. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29657. callback(value, index + componentIndex);
  29658. componentByteOffset += componentByteLength;
  29659. }
  29660. byteOffset += byteStride;
  29661. }
  29662. }
  29663. };
  29664. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29665. switch (type) {
  29666. case VertexBuffer.BYTE: {
  29667. var value = dataView.getInt8(byteOffset);
  29668. if (normalized) {
  29669. value = (value + 0.5) / 127.5;
  29670. }
  29671. return value;
  29672. }
  29673. case VertexBuffer.UNSIGNED_BYTE: {
  29674. var value = dataView.getUint8(byteOffset);
  29675. if (normalized) {
  29676. value = value / 255;
  29677. }
  29678. return value;
  29679. }
  29680. case VertexBuffer.SHORT: {
  29681. var value = dataView.getInt16(byteOffset, true);
  29682. if (normalized) {
  29683. value = (value + 0.5) / 16383.5;
  29684. }
  29685. return value;
  29686. }
  29687. case VertexBuffer.UNSIGNED_SHORT: {
  29688. var value = dataView.getUint16(byteOffset, true);
  29689. if (normalized) {
  29690. value = value / 65535;
  29691. }
  29692. return value;
  29693. }
  29694. case VertexBuffer.FLOAT: {
  29695. return dataView.getFloat32(byteOffset, true);
  29696. }
  29697. default: {
  29698. throw new Error("Invalid component type " + type);
  29699. }
  29700. }
  29701. };
  29702. /**
  29703. * The byte type.
  29704. */
  29705. VertexBuffer.BYTE = 5120;
  29706. /**
  29707. * The unsigned byte type.
  29708. */
  29709. VertexBuffer.UNSIGNED_BYTE = 5121;
  29710. /**
  29711. * The short type.
  29712. */
  29713. VertexBuffer.SHORT = 5122;
  29714. /**
  29715. * The unsigned short type.
  29716. */
  29717. VertexBuffer.UNSIGNED_SHORT = 5123;
  29718. /**
  29719. * The integer type.
  29720. */
  29721. VertexBuffer.INT = 5124;
  29722. /**
  29723. * The unsigned integer type.
  29724. */
  29725. VertexBuffer.UNSIGNED_INT = 5125;
  29726. /**
  29727. * The float type.
  29728. */
  29729. VertexBuffer.FLOAT = 5126;
  29730. // Enums
  29731. VertexBuffer._PositionKind = "position";
  29732. VertexBuffer._NormalKind = "normal";
  29733. VertexBuffer._TangentKind = "tangent";
  29734. VertexBuffer._UVKind = "uv";
  29735. VertexBuffer._UV2Kind = "uv2";
  29736. VertexBuffer._UV3Kind = "uv3";
  29737. VertexBuffer._UV4Kind = "uv4";
  29738. VertexBuffer._UV5Kind = "uv5";
  29739. VertexBuffer._UV6Kind = "uv6";
  29740. VertexBuffer._ColorKind = "color";
  29741. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29742. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29743. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29744. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29745. return VertexBuffer;
  29746. }());
  29747. BABYLON.VertexBuffer = VertexBuffer;
  29748. })(BABYLON || (BABYLON = {}));
  29749. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29750. var BABYLON;
  29751. (function (BABYLON) {
  29752. /**
  29753. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29754. */
  29755. var DummyInternalTextureTracker = /** @class */ (function () {
  29756. function DummyInternalTextureTracker() {
  29757. /**
  29758. * Gets or set the previous tracker in the list
  29759. */
  29760. this.previous = null;
  29761. /**
  29762. * Gets or set the next tracker in the list
  29763. */
  29764. this.next = null;
  29765. }
  29766. return DummyInternalTextureTracker;
  29767. }());
  29768. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29769. })(BABYLON || (BABYLON = {}));
  29770. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29771. var BABYLON;
  29772. (function (BABYLON) {
  29773. /**
  29774. * Class used to store data associated with WebGL texture data for the engine
  29775. * This class should not be used directly
  29776. */
  29777. var InternalTexture = /** @class */ (function () {
  29778. /**
  29779. * Creates a new InternalTexture
  29780. * @param engine defines the engine to use
  29781. * @param dataSource defines the type of data that will be used
  29782. */
  29783. function InternalTexture(engine, dataSource) {
  29784. /**
  29785. * Observable called when the texture is loaded
  29786. */
  29787. this.onLoadedObservable = new BABYLON.Observable();
  29788. /**
  29789. * Gets or set the previous tracker in the list
  29790. */
  29791. this.previous = null;
  29792. /**
  29793. * Gets or set the next tracker in the list
  29794. */
  29795. this.next = null;
  29796. // Private
  29797. /** @hidden */
  29798. this._initialSlot = -1;
  29799. /** @hidden */
  29800. this._designatedSlot = -1;
  29801. /** @hidden */
  29802. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29803. /** @hidden */
  29804. this._comparisonFunction = 0;
  29805. /** @hidden */
  29806. this._references = 1;
  29807. this._engine = engine;
  29808. this._dataSource = dataSource;
  29809. this._webGLTexture = engine._createTexture();
  29810. }
  29811. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29812. /**
  29813. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29814. */
  29815. get: function () {
  29816. return this._dataSource;
  29817. },
  29818. enumerable: true,
  29819. configurable: true
  29820. });
  29821. /**
  29822. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29823. */
  29824. InternalTexture.prototype.incrementReferences = function () {
  29825. this._references++;
  29826. };
  29827. /**
  29828. * Change the size of the texture (not the size of the content)
  29829. * @param width defines the new width
  29830. * @param height defines the new height
  29831. * @param depth defines the new depth (1 by default)
  29832. */
  29833. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29834. if (depth === void 0) { depth = 1; }
  29835. this.width = width;
  29836. this.height = height;
  29837. this.depth = depth;
  29838. this.baseWidth = width;
  29839. this.baseHeight = height;
  29840. this.baseDepth = depth;
  29841. this._size = width * height * depth;
  29842. };
  29843. /** @hidden */
  29844. InternalTexture.prototype._rebuild = function () {
  29845. var _this = this;
  29846. var proxy;
  29847. this.isReady = false;
  29848. this._cachedCoordinatesMode = null;
  29849. this._cachedWrapU = null;
  29850. this._cachedWrapV = null;
  29851. this._cachedAnisotropicFilteringLevel = null;
  29852. switch (this._dataSource) {
  29853. case InternalTexture.DATASOURCE_TEMP:
  29854. return;
  29855. case InternalTexture.DATASOURCE_URL:
  29856. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29857. _this.isReady = true;
  29858. }, null, this._buffer, undefined, this.format);
  29859. proxy._swapAndDie(this);
  29860. return;
  29861. case InternalTexture.DATASOURCE_RAW:
  29862. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29863. proxy._swapAndDie(this);
  29864. this.isReady = true;
  29865. return;
  29866. case InternalTexture.DATASOURCE_RAW3D:
  29867. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29868. proxy._swapAndDie(this);
  29869. this.isReady = true;
  29870. return;
  29871. case InternalTexture.DATASOURCE_DYNAMIC:
  29872. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29873. proxy._swapAndDie(this);
  29874. // The engine will make sure to update content so no need to flag it as isReady = true
  29875. return;
  29876. case InternalTexture.DATASOURCE_RENDERTARGET:
  29877. var options = new BABYLON.RenderTargetCreationOptions();
  29878. options.generateDepthBuffer = this._generateDepthBuffer;
  29879. options.generateMipMaps = this.generateMipMaps;
  29880. options.generateStencilBuffer = this._generateStencilBuffer;
  29881. options.samplingMode = this.samplingMode;
  29882. options.type = this.type;
  29883. if (this.isCube) {
  29884. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29885. }
  29886. else {
  29887. var size = {
  29888. width: this.width,
  29889. height: this.height
  29890. };
  29891. proxy = this._engine.createRenderTargetTexture(size, options);
  29892. }
  29893. proxy._swapAndDie(this);
  29894. this.isReady = true;
  29895. return;
  29896. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29897. var depthTextureOptions = {
  29898. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29899. comparisonFunction: this._comparisonFunction,
  29900. generateStencil: this._generateStencilBuffer,
  29901. isCube: this.isCube
  29902. };
  29903. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29904. proxy._swapAndDie(this);
  29905. this.isReady = true;
  29906. return;
  29907. case InternalTexture.DATASOURCE_CUBE:
  29908. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29909. _this.isReady = true;
  29910. }, null, this.format, this._extension);
  29911. proxy._swapAndDie(this);
  29912. return;
  29913. case InternalTexture.DATASOURCE_CUBERAW:
  29914. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29915. proxy._swapAndDie(this);
  29916. this.isReady = true;
  29917. return;
  29918. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29919. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29920. if (proxy) {
  29921. proxy._swapAndDie(_this);
  29922. }
  29923. _this.isReady = true;
  29924. }, null, this.format, this._extension);
  29925. return;
  29926. }
  29927. };
  29928. InternalTexture.prototype._swapAndDie = function (target) {
  29929. target._webGLTexture = this._webGLTexture;
  29930. if (this._framebuffer) {
  29931. target._framebuffer = this._framebuffer;
  29932. }
  29933. if (this._depthStencilBuffer) {
  29934. target._depthStencilBuffer = this._depthStencilBuffer;
  29935. }
  29936. if (this._lodTextureHigh) {
  29937. if (target._lodTextureHigh) {
  29938. target._lodTextureHigh.dispose();
  29939. }
  29940. target._lodTextureHigh = this._lodTextureHigh;
  29941. }
  29942. if (this._lodTextureMid) {
  29943. if (target._lodTextureMid) {
  29944. target._lodTextureMid.dispose();
  29945. }
  29946. target._lodTextureMid = this._lodTextureMid;
  29947. }
  29948. if (this._lodTextureLow) {
  29949. if (target._lodTextureLow) {
  29950. target._lodTextureLow.dispose();
  29951. }
  29952. target._lodTextureLow = this._lodTextureLow;
  29953. }
  29954. var cache = this._engine.getLoadedTexturesCache();
  29955. var index = cache.indexOf(this);
  29956. if (index !== -1) {
  29957. cache.splice(index, 1);
  29958. }
  29959. };
  29960. /**
  29961. * Dispose the current allocated resources
  29962. */
  29963. InternalTexture.prototype.dispose = function () {
  29964. if (!this._webGLTexture) {
  29965. return;
  29966. }
  29967. this._references--;
  29968. if (this._references === 0) {
  29969. this._engine._releaseTexture(this);
  29970. this._webGLTexture = null;
  29971. this.previous = null;
  29972. this.next = null;
  29973. }
  29974. };
  29975. /**
  29976. * The source of the texture data is unknown
  29977. */
  29978. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29979. /**
  29980. * Texture data comes from an URL
  29981. */
  29982. InternalTexture.DATASOURCE_URL = 1;
  29983. /**
  29984. * Texture data is only used for temporary storage
  29985. */
  29986. InternalTexture.DATASOURCE_TEMP = 2;
  29987. /**
  29988. * Texture data comes from raw data (ArrayBuffer)
  29989. */
  29990. InternalTexture.DATASOURCE_RAW = 3;
  29991. /**
  29992. * Texture content is dynamic (video or dynamic texture)
  29993. */
  29994. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29995. /**
  29996. * Texture content is generated by rendering to it
  29997. */
  29998. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29999. /**
  30000. * Texture content is part of a multi render target process
  30001. */
  30002. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30003. /**
  30004. * Texture data comes from a cube data file
  30005. */
  30006. InternalTexture.DATASOURCE_CUBE = 7;
  30007. /**
  30008. * Texture data comes from a raw cube data
  30009. */
  30010. InternalTexture.DATASOURCE_CUBERAW = 8;
  30011. /**
  30012. * Texture data come from a prefiltered cube data file
  30013. */
  30014. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30015. /**
  30016. * Texture content is raw 3D data
  30017. */
  30018. InternalTexture.DATASOURCE_RAW3D = 10;
  30019. /**
  30020. * Texture content is a depth texture
  30021. */
  30022. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30023. return InternalTexture;
  30024. }());
  30025. BABYLON.InternalTexture = InternalTexture;
  30026. })(BABYLON || (BABYLON = {}));
  30027. //# sourceMappingURL=babylon.internalTexture.js.map
  30028. var BABYLON;
  30029. (function (BABYLON) {
  30030. var BaseTexture = /** @class */ (function () {
  30031. function BaseTexture(scene) {
  30032. this._hasAlpha = false;
  30033. this.getAlphaFromRGB = false;
  30034. this.level = 1;
  30035. this.coordinatesIndex = 0;
  30036. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30037. /**
  30038. * | Value | Type | Description |
  30039. * | ----- | ------------------ | ----------- |
  30040. * | 0 | CLAMP_ADDRESSMODE | |
  30041. * | 1 | WRAP_ADDRESSMODE | |
  30042. * | 2 | MIRROR_ADDRESSMODE | |
  30043. */
  30044. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30045. /**
  30046. * | Value | Type | Description |
  30047. * | ----- | ------------------ | ----------- |
  30048. * | 0 | CLAMP_ADDRESSMODE | |
  30049. * | 1 | WRAP_ADDRESSMODE | |
  30050. * | 2 | MIRROR_ADDRESSMODE | |
  30051. */
  30052. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30053. /**
  30054. * | Value | Type | Description |
  30055. * | ----- | ------------------ | ----------- |
  30056. * | 0 | CLAMP_ADDRESSMODE | |
  30057. * | 1 | WRAP_ADDRESSMODE | |
  30058. * | 2 | MIRROR_ADDRESSMODE | |
  30059. */
  30060. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30061. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30062. this.isCube = false;
  30063. this.is3D = false;
  30064. this.gammaSpace = true;
  30065. this.invertZ = false;
  30066. this.lodLevelInAlpha = false;
  30067. this.lodGenerationOffset = 0.0;
  30068. this.lodGenerationScale = 0.8;
  30069. this.isRenderTarget = false;
  30070. this.animations = new Array();
  30071. /**
  30072. * An event triggered when the texture is disposed.
  30073. */
  30074. this.onDisposeObservable = new BABYLON.Observable();
  30075. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30076. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30077. if (this._scene) {
  30078. this._scene.textures.push(this);
  30079. }
  30080. this._uid = null;
  30081. }
  30082. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30083. get: function () {
  30084. return this._hasAlpha;
  30085. },
  30086. set: function (value) {
  30087. if (this._hasAlpha === value) {
  30088. return;
  30089. }
  30090. this._hasAlpha = value;
  30091. if (this._scene) {
  30092. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30093. }
  30094. },
  30095. enumerable: true,
  30096. configurable: true
  30097. });
  30098. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30099. get: function () {
  30100. return this._coordinatesMode;
  30101. },
  30102. /**
  30103. * How a texture is mapped.
  30104. *
  30105. * | Value | Type | Description |
  30106. * | ----- | ----------------------------------- | ----------- |
  30107. * | 0 | EXPLICIT_MODE | |
  30108. * | 1 | SPHERICAL_MODE | |
  30109. * | 2 | PLANAR_MODE | |
  30110. * | 3 | CUBIC_MODE | |
  30111. * | 4 | PROJECTION_MODE | |
  30112. * | 5 | SKYBOX_MODE | |
  30113. * | 6 | INVCUBIC_MODE | |
  30114. * | 7 | EQUIRECTANGULAR_MODE | |
  30115. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30116. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30117. */
  30118. set: function (value) {
  30119. if (this._coordinatesMode === value) {
  30120. return;
  30121. }
  30122. this._coordinatesMode = value;
  30123. if (this._scene) {
  30124. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30125. }
  30126. },
  30127. enumerable: true,
  30128. configurable: true
  30129. });
  30130. Object.defineProperty(BaseTexture.prototype, "uid", {
  30131. get: function () {
  30132. if (!this._uid) {
  30133. this._uid = BABYLON.Tools.RandomId();
  30134. }
  30135. return this._uid;
  30136. },
  30137. enumerable: true,
  30138. configurable: true
  30139. });
  30140. BaseTexture.prototype.toString = function () {
  30141. return this.name;
  30142. };
  30143. BaseTexture.prototype.getClassName = function () {
  30144. return "BaseTexture";
  30145. };
  30146. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30147. set: function (callback) {
  30148. if (this._onDisposeObserver) {
  30149. this.onDisposeObservable.remove(this._onDisposeObserver);
  30150. }
  30151. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30152. },
  30153. enumerable: true,
  30154. configurable: true
  30155. });
  30156. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30157. get: function () {
  30158. return true;
  30159. },
  30160. enumerable: true,
  30161. configurable: true
  30162. });
  30163. BaseTexture.prototype.getScene = function () {
  30164. return this._scene;
  30165. };
  30166. BaseTexture.prototype.getTextureMatrix = function () {
  30167. return BABYLON.Matrix.IdentityReadOnly;
  30168. };
  30169. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30170. return BABYLON.Matrix.IdentityReadOnly;
  30171. };
  30172. BaseTexture.prototype.getInternalTexture = function () {
  30173. return this._texture;
  30174. };
  30175. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30176. return !this.isBlocking || this.isReady();
  30177. };
  30178. BaseTexture.prototype.isReady = function () {
  30179. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30180. this.delayLoad();
  30181. return false;
  30182. }
  30183. if (this._texture) {
  30184. return this._texture.isReady;
  30185. }
  30186. return false;
  30187. };
  30188. BaseTexture.prototype.getSize = function () {
  30189. if (this._texture && this._texture.width) {
  30190. return new BABYLON.Size(this._texture.width, this._texture.height);
  30191. }
  30192. if (this._texture && this._texture._size) {
  30193. return new BABYLON.Size(this._texture._size, this._texture._size);
  30194. }
  30195. return BABYLON.Size.Zero();
  30196. };
  30197. BaseTexture.prototype.getBaseSize = function () {
  30198. if (!this.isReady() || !this._texture)
  30199. return BABYLON.Size.Zero();
  30200. if (this._texture._size) {
  30201. return new BABYLON.Size(this._texture._size, this._texture._size);
  30202. }
  30203. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30204. };
  30205. BaseTexture.prototype.scale = function (ratio) {
  30206. };
  30207. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30208. get: function () {
  30209. return false;
  30210. },
  30211. enumerable: true,
  30212. configurable: true
  30213. });
  30214. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30215. if (!this._scene) {
  30216. return null;
  30217. }
  30218. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30219. for (var index = 0; index < texturesCache.length; index++) {
  30220. var texturesCacheEntry = texturesCache[index];
  30221. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30222. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30223. texturesCacheEntry.incrementReferences();
  30224. return texturesCacheEntry;
  30225. }
  30226. }
  30227. }
  30228. return null;
  30229. };
  30230. BaseTexture.prototype._rebuild = function () {
  30231. };
  30232. BaseTexture.prototype.delayLoad = function () {
  30233. };
  30234. BaseTexture.prototype.clone = function () {
  30235. return null;
  30236. };
  30237. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30238. get: function () {
  30239. if (!this._texture) {
  30240. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30241. }
  30242. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30243. },
  30244. enumerable: true,
  30245. configurable: true
  30246. });
  30247. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30248. get: function () {
  30249. if (!this._texture) {
  30250. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30251. }
  30252. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30253. },
  30254. enumerable: true,
  30255. configurable: true
  30256. });
  30257. BaseTexture.prototype.readPixels = function (faceIndex) {
  30258. if (faceIndex === void 0) { faceIndex = 0; }
  30259. if (!this._texture) {
  30260. return null;
  30261. }
  30262. var size = this.getSize();
  30263. var scene = this.getScene();
  30264. if (!scene) {
  30265. return null;
  30266. }
  30267. var engine = scene.getEngine();
  30268. if (this._texture.isCube) {
  30269. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  30270. }
  30271. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  30272. };
  30273. BaseTexture.prototype.releaseInternalTexture = function () {
  30274. if (this._texture) {
  30275. this._texture.dispose();
  30276. this._texture = null;
  30277. }
  30278. };
  30279. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30280. get: function () {
  30281. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30282. return null;
  30283. }
  30284. if (!this._texture._sphericalPolynomial) {
  30285. this._texture._sphericalPolynomial =
  30286. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30287. }
  30288. return this._texture._sphericalPolynomial;
  30289. },
  30290. set: function (value) {
  30291. if (this._texture) {
  30292. this._texture._sphericalPolynomial = value;
  30293. }
  30294. },
  30295. enumerable: true,
  30296. configurable: true
  30297. });
  30298. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30299. get: function () {
  30300. if (this._texture) {
  30301. return this._texture._lodTextureHigh;
  30302. }
  30303. return null;
  30304. },
  30305. enumerable: true,
  30306. configurable: true
  30307. });
  30308. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30309. get: function () {
  30310. if (this._texture) {
  30311. return this._texture._lodTextureMid;
  30312. }
  30313. return null;
  30314. },
  30315. enumerable: true,
  30316. configurable: true
  30317. });
  30318. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30319. get: function () {
  30320. if (this._texture) {
  30321. return this._texture._lodTextureLow;
  30322. }
  30323. return null;
  30324. },
  30325. enumerable: true,
  30326. configurable: true
  30327. });
  30328. BaseTexture.prototype.dispose = function () {
  30329. if (!this._scene) {
  30330. return;
  30331. }
  30332. // Animations
  30333. this._scene.stopAnimation(this);
  30334. // Remove from scene
  30335. this._scene._removePendingData(this);
  30336. var index = this._scene.textures.indexOf(this);
  30337. if (index >= 0) {
  30338. this._scene.textures.splice(index, 1);
  30339. }
  30340. if (this._texture === undefined) {
  30341. return;
  30342. }
  30343. // Release
  30344. this.releaseInternalTexture();
  30345. // Callback
  30346. this.onDisposeObservable.notifyObservers(this);
  30347. this.onDisposeObservable.clear();
  30348. };
  30349. BaseTexture.prototype.serialize = function () {
  30350. if (!this.name) {
  30351. return null;
  30352. }
  30353. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30354. // Animations
  30355. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30356. return serializationObject;
  30357. };
  30358. BaseTexture.WhenAllReady = function (textures, callback) {
  30359. var numRemaining = textures.length;
  30360. if (numRemaining === 0) {
  30361. callback();
  30362. return;
  30363. }
  30364. var _loop_1 = function () {
  30365. texture = textures[i];
  30366. if (texture.isReady()) {
  30367. if (--numRemaining === 0) {
  30368. callback();
  30369. }
  30370. }
  30371. else {
  30372. onLoadObservable = texture.onLoadObservable;
  30373. var onLoadCallback_1 = function () {
  30374. onLoadObservable.removeCallback(onLoadCallback_1);
  30375. if (--numRemaining === 0) {
  30376. callback();
  30377. }
  30378. };
  30379. onLoadObservable.add(onLoadCallback_1);
  30380. }
  30381. };
  30382. var texture, onLoadObservable;
  30383. for (var i = 0; i < textures.length; i++) {
  30384. _loop_1();
  30385. }
  30386. };
  30387. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30388. __decorate([
  30389. BABYLON.serialize()
  30390. ], BaseTexture.prototype, "name", void 0);
  30391. __decorate([
  30392. BABYLON.serialize("hasAlpha")
  30393. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30394. __decorate([
  30395. BABYLON.serialize()
  30396. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30397. __decorate([
  30398. BABYLON.serialize()
  30399. ], BaseTexture.prototype, "level", void 0);
  30400. __decorate([
  30401. BABYLON.serialize()
  30402. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30403. __decorate([
  30404. BABYLON.serialize("coordinatesMode")
  30405. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30406. __decorate([
  30407. BABYLON.serialize()
  30408. ], BaseTexture.prototype, "wrapU", void 0);
  30409. __decorate([
  30410. BABYLON.serialize()
  30411. ], BaseTexture.prototype, "wrapV", void 0);
  30412. __decorate([
  30413. BABYLON.serialize()
  30414. ], BaseTexture.prototype, "wrapR", void 0);
  30415. __decorate([
  30416. BABYLON.serialize()
  30417. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30418. __decorate([
  30419. BABYLON.serialize()
  30420. ], BaseTexture.prototype, "isCube", void 0);
  30421. __decorate([
  30422. BABYLON.serialize()
  30423. ], BaseTexture.prototype, "is3D", void 0);
  30424. __decorate([
  30425. BABYLON.serialize()
  30426. ], BaseTexture.prototype, "gammaSpace", void 0);
  30427. __decorate([
  30428. BABYLON.serialize()
  30429. ], BaseTexture.prototype, "invertZ", void 0);
  30430. __decorate([
  30431. BABYLON.serialize()
  30432. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30433. __decorate([
  30434. BABYLON.serialize()
  30435. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  30436. __decorate([
  30437. BABYLON.serialize()
  30438. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  30439. __decorate([
  30440. BABYLON.serialize()
  30441. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30442. return BaseTexture;
  30443. }());
  30444. BABYLON.BaseTexture = BaseTexture;
  30445. })(BABYLON || (BABYLON = {}));
  30446. //# sourceMappingURL=babylon.baseTexture.js.map
  30447. var BABYLON;
  30448. (function (BABYLON) {
  30449. var Texture = /** @class */ (function (_super) {
  30450. __extends(Texture, _super);
  30451. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30452. if (noMipmap === void 0) { noMipmap = false; }
  30453. if (invertY === void 0) { invertY = true; }
  30454. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30455. if (onLoad === void 0) { onLoad = null; }
  30456. if (onError === void 0) { onError = null; }
  30457. if (buffer === void 0) { buffer = null; }
  30458. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30459. var _this = _super.call(this, scene) || this;
  30460. _this.uOffset = 0;
  30461. _this.vOffset = 0;
  30462. _this.uScale = 1.0;
  30463. _this.vScale = 1.0;
  30464. _this.uAng = 0;
  30465. _this.vAng = 0;
  30466. _this.wAng = 0;
  30467. _this._isBlocking = true;
  30468. _this.name = url || "";
  30469. _this.url = url;
  30470. _this._noMipmap = noMipmap;
  30471. _this._invertY = invertY;
  30472. _this._samplingMode = samplingMode;
  30473. _this._buffer = buffer;
  30474. _this._deleteBuffer = deleteBuffer;
  30475. if (format) {
  30476. _this._format = format;
  30477. }
  30478. scene = _this.getScene();
  30479. if (!scene) {
  30480. return _this;
  30481. }
  30482. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30483. var load = function () {
  30484. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30485. _this.onLoadObservable.notifyObservers(_this);
  30486. }
  30487. if (onLoad) {
  30488. onLoad();
  30489. }
  30490. if (!_this.isBlocking && scene) {
  30491. scene.resetCachedMaterial();
  30492. }
  30493. };
  30494. if (!_this.url) {
  30495. _this._delayedOnLoad = load;
  30496. _this._delayedOnError = onError;
  30497. return _this;
  30498. }
  30499. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30500. if (!_this._texture) {
  30501. if (!scene.useDelayedTextureLoading) {
  30502. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30503. if (deleteBuffer) {
  30504. delete _this._buffer;
  30505. }
  30506. }
  30507. else {
  30508. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30509. _this._delayedOnLoad = load;
  30510. _this._delayedOnError = onError;
  30511. }
  30512. }
  30513. else {
  30514. if (_this._texture.isReady) {
  30515. BABYLON.Tools.SetImmediate(function () { return load(); });
  30516. }
  30517. else {
  30518. _this._texture.onLoadedObservable.add(load);
  30519. }
  30520. }
  30521. return _this;
  30522. }
  30523. Object.defineProperty(Texture.prototype, "noMipmap", {
  30524. get: function () {
  30525. return this._noMipmap;
  30526. },
  30527. enumerable: true,
  30528. configurable: true
  30529. });
  30530. Object.defineProperty(Texture.prototype, "isBlocking", {
  30531. get: function () {
  30532. return this._isBlocking;
  30533. },
  30534. set: function (value) {
  30535. this._isBlocking = value;
  30536. },
  30537. enumerable: true,
  30538. configurable: true
  30539. });
  30540. Object.defineProperty(Texture.prototype, "samplingMode", {
  30541. get: function () {
  30542. return this._samplingMode;
  30543. },
  30544. enumerable: true,
  30545. configurable: true
  30546. });
  30547. Texture.prototype.updateURL = function (url) {
  30548. this.url = url;
  30549. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30550. this.delayLoad();
  30551. };
  30552. Texture.prototype.delayLoad = function () {
  30553. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30554. return;
  30555. }
  30556. var scene = this.getScene();
  30557. if (!scene) {
  30558. return;
  30559. }
  30560. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30561. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30562. if (!this._texture) {
  30563. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30564. if (this._deleteBuffer) {
  30565. delete this._buffer;
  30566. }
  30567. }
  30568. else {
  30569. if (this._delayedOnLoad) {
  30570. if (this._texture.isReady) {
  30571. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30572. }
  30573. else {
  30574. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30575. }
  30576. }
  30577. }
  30578. this._delayedOnLoad = null;
  30579. this._delayedOnError = null;
  30580. };
  30581. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30582. if (!this._texture) {
  30583. return;
  30584. }
  30585. var scene = this.getScene();
  30586. if (!scene) {
  30587. return;
  30588. }
  30589. this._samplingMode = samplingMode;
  30590. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30591. };
  30592. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30593. x *= this.uScale;
  30594. y *= this.vScale;
  30595. x -= 0.5 * this.uScale;
  30596. y -= 0.5 * this.vScale;
  30597. z -= 0.5;
  30598. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30599. t.x += 0.5 * this.uScale + this.uOffset;
  30600. t.y += 0.5 * this.vScale + this.vOffset;
  30601. t.z += 0.5;
  30602. };
  30603. Texture.prototype.getTextureMatrix = function () {
  30604. var _this = this;
  30605. if (this.uOffset === this._cachedUOffset &&
  30606. this.vOffset === this._cachedVOffset &&
  30607. this.uScale === this._cachedUScale &&
  30608. this.vScale === this._cachedVScale &&
  30609. this.uAng === this._cachedUAng &&
  30610. this.vAng === this._cachedVAng &&
  30611. this.wAng === this._cachedWAng) {
  30612. return this._cachedTextureMatrix;
  30613. }
  30614. this._cachedUOffset = this.uOffset;
  30615. this._cachedVOffset = this.vOffset;
  30616. this._cachedUScale = this.uScale;
  30617. this._cachedVScale = this.vScale;
  30618. this._cachedUAng = this.uAng;
  30619. this._cachedVAng = this.vAng;
  30620. this._cachedWAng = this.wAng;
  30621. if (!this._cachedTextureMatrix) {
  30622. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30623. this._rowGenerationMatrix = new BABYLON.Matrix();
  30624. this._t0 = BABYLON.Vector3.Zero();
  30625. this._t1 = BABYLON.Vector3.Zero();
  30626. this._t2 = BABYLON.Vector3.Zero();
  30627. }
  30628. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30629. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30630. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30631. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30632. this._t1.subtractInPlace(this._t0);
  30633. this._t2.subtractInPlace(this._t0);
  30634. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30635. this._cachedTextureMatrix.m[0] = this._t1.x;
  30636. this._cachedTextureMatrix.m[1] = this._t1.y;
  30637. this._cachedTextureMatrix.m[2] = this._t1.z;
  30638. this._cachedTextureMatrix.m[4] = this._t2.x;
  30639. this._cachedTextureMatrix.m[5] = this._t2.y;
  30640. this._cachedTextureMatrix.m[6] = this._t2.z;
  30641. this._cachedTextureMatrix.m[8] = this._t0.x;
  30642. this._cachedTextureMatrix.m[9] = this._t0.y;
  30643. this._cachedTextureMatrix.m[10] = this._t0.z;
  30644. var scene = this.getScene();
  30645. if (!scene) {
  30646. return this._cachedTextureMatrix;
  30647. }
  30648. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30649. return mat.hasTexture(_this);
  30650. });
  30651. return this._cachedTextureMatrix;
  30652. };
  30653. Texture.prototype.getReflectionTextureMatrix = function () {
  30654. var _this = this;
  30655. var scene = this.getScene();
  30656. if (!scene) {
  30657. return this._cachedTextureMatrix;
  30658. }
  30659. if (this.uOffset === this._cachedUOffset &&
  30660. this.vOffset === this._cachedVOffset &&
  30661. this.uScale === this._cachedUScale &&
  30662. this.vScale === this._cachedVScale &&
  30663. this.coordinatesMode === this._cachedCoordinatesMode) {
  30664. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30665. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30666. return this._cachedTextureMatrix;
  30667. }
  30668. }
  30669. else {
  30670. return this._cachedTextureMatrix;
  30671. }
  30672. }
  30673. if (!this._cachedTextureMatrix) {
  30674. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30675. }
  30676. if (!this._projectionModeMatrix) {
  30677. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30678. }
  30679. this._cachedUOffset = this.uOffset;
  30680. this._cachedVOffset = this.vOffset;
  30681. this._cachedUScale = this.uScale;
  30682. this._cachedVScale = this.vScale;
  30683. this._cachedCoordinatesMode = this.coordinatesMode;
  30684. switch (this.coordinatesMode) {
  30685. case Texture.PLANAR_MODE:
  30686. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30687. this._cachedTextureMatrix[0] = this.uScale;
  30688. this._cachedTextureMatrix[5] = this.vScale;
  30689. this._cachedTextureMatrix[12] = this.uOffset;
  30690. this._cachedTextureMatrix[13] = this.vOffset;
  30691. break;
  30692. case Texture.PROJECTION_MODE:
  30693. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30694. this._projectionModeMatrix.m[0] = 0.5;
  30695. this._projectionModeMatrix.m[5] = -0.5;
  30696. this._projectionModeMatrix.m[10] = 0.0;
  30697. this._projectionModeMatrix.m[12] = 0.5;
  30698. this._projectionModeMatrix.m[13] = 0.5;
  30699. this._projectionModeMatrix.m[14] = 1.0;
  30700. this._projectionModeMatrix.m[15] = 1.0;
  30701. var projectionMatrix = scene.getProjectionMatrix();
  30702. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30703. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30704. break;
  30705. default:
  30706. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30707. break;
  30708. }
  30709. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30710. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30711. });
  30712. return this._cachedTextureMatrix;
  30713. };
  30714. Texture.prototype.clone = function () {
  30715. var _this = this;
  30716. return BABYLON.SerializationHelper.Clone(function () {
  30717. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30718. }, this);
  30719. };
  30720. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30721. get: function () {
  30722. if (!this._onLoadObservable) {
  30723. this._onLoadObservable = new BABYLON.Observable();
  30724. }
  30725. return this._onLoadObservable;
  30726. },
  30727. enumerable: true,
  30728. configurable: true
  30729. });
  30730. Texture.prototype.serialize = function () {
  30731. var serializationObject = _super.prototype.serialize.call(this);
  30732. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30733. serializationObject.base64String = this._buffer;
  30734. serializationObject.name = serializationObject.name.replace("data:", "");
  30735. }
  30736. serializationObject.invertY = this._invertY;
  30737. serializationObject.samplingMode = this.samplingMode;
  30738. return serializationObject;
  30739. };
  30740. Texture.prototype.getClassName = function () {
  30741. return "Texture";
  30742. };
  30743. Texture.prototype.dispose = function () {
  30744. _super.prototype.dispose.call(this);
  30745. if (this.onLoadObservable) {
  30746. this.onLoadObservable.clear();
  30747. this._onLoadObservable = null;
  30748. }
  30749. this._delayedOnLoad = null;
  30750. this._delayedOnError = null;
  30751. };
  30752. // Statics
  30753. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30754. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30755. if (onLoad === void 0) { onLoad = null; }
  30756. if (onError === void 0) { onError = null; }
  30757. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30758. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30759. };
  30760. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30761. if (parsedTexture.customType) {
  30762. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30763. // Update Sampling Mode
  30764. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30765. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30766. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30767. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30768. }
  30769. }
  30770. return parsedCustomTexture;
  30771. }
  30772. if (parsedTexture.isCube) {
  30773. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30774. }
  30775. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30776. return null;
  30777. }
  30778. var texture = BABYLON.SerializationHelper.Parse(function () {
  30779. var generateMipMaps = true;
  30780. if (parsedTexture.noMipmap) {
  30781. generateMipMaps = false;
  30782. }
  30783. if (parsedTexture.mirrorPlane) {
  30784. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30785. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30786. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30787. return mirrorTexture;
  30788. }
  30789. else if (parsedTexture.isRenderTarget) {
  30790. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30791. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30792. return renderTargetTexture;
  30793. }
  30794. else {
  30795. var texture;
  30796. if (parsedTexture.base64String) {
  30797. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30798. }
  30799. else {
  30800. var url = rootUrl + parsedTexture.name;
  30801. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30802. url = parsedTexture.url;
  30803. }
  30804. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30805. }
  30806. return texture;
  30807. }
  30808. }, parsedTexture, scene);
  30809. // Update Sampling Mode
  30810. if (parsedTexture.samplingMode) {
  30811. var sampling = parsedTexture.samplingMode;
  30812. if (texture._samplingMode !== sampling) {
  30813. texture.updateSamplingMode(sampling);
  30814. }
  30815. }
  30816. // Animations
  30817. if (parsedTexture.animations) {
  30818. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30819. var parsedAnimation = parsedTexture.animations[animationIndex];
  30820. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30821. }
  30822. }
  30823. return texture;
  30824. };
  30825. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30826. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30827. if (noMipmap === void 0) { noMipmap = false; }
  30828. if (invertY === void 0) { invertY = true; }
  30829. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30830. if (onLoad === void 0) { onLoad = null; }
  30831. if (onError === void 0) { onError = null; }
  30832. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30833. if (name.substr(0, 5) !== "data:") {
  30834. name = "data:" + name;
  30835. }
  30836. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30837. };
  30838. // Constants
  30839. Texture.NEAREST_SAMPLINGMODE = 1;
  30840. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  30841. Texture.BILINEAR_SAMPLINGMODE = 2;
  30842. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  30843. Texture.TRILINEAR_SAMPLINGMODE = 3;
  30844. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  30845. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  30846. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  30847. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  30848. Texture.NEAREST_LINEAR = 7;
  30849. Texture.NEAREST_NEAREST = 8;
  30850. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  30851. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  30852. Texture.LINEAR_LINEAR = 11;
  30853. Texture.LINEAR_NEAREST = 12;
  30854. Texture.EXPLICIT_MODE = 0;
  30855. Texture.SPHERICAL_MODE = 1;
  30856. Texture.PLANAR_MODE = 2;
  30857. Texture.CUBIC_MODE = 3;
  30858. Texture.PROJECTION_MODE = 4;
  30859. Texture.SKYBOX_MODE = 5;
  30860. Texture.INVCUBIC_MODE = 6;
  30861. Texture.EQUIRECTANGULAR_MODE = 7;
  30862. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  30863. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  30864. Texture.CLAMP_ADDRESSMODE = 0;
  30865. Texture.WRAP_ADDRESSMODE = 1;
  30866. Texture.MIRROR_ADDRESSMODE = 2;
  30867. /**
  30868. * 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
  30869. */
  30870. Texture.UseSerializedUrlIfAny = false;
  30871. __decorate([
  30872. BABYLON.serialize()
  30873. ], Texture.prototype, "url", void 0);
  30874. __decorate([
  30875. BABYLON.serialize()
  30876. ], Texture.prototype, "uOffset", void 0);
  30877. __decorate([
  30878. BABYLON.serialize()
  30879. ], Texture.prototype, "vOffset", void 0);
  30880. __decorate([
  30881. BABYLON.serialize()
  30882. ], Texture.prototype, "uScale", void 0);
  30883. __decorate([
  30884. BABYLON.serialize()
  30885. ], Texture.prototype, "vScale", void 0);
  30886. __decorate([
  30887. BABYLON.serialize()
  30888. ], Texture.prototype, "uAng", void 0);
  30889. __decorate([
  30890. BABYLON.serialize()
  30891. ], Texture.prototype, "vAng", void 0);
  30892. __decorate([
  30893. BABYLON.serialize()
  30894. ], Texture.prototype, "wAng", void 0);
  30895. __decorate([
  30896. BABYLON.serialize()
  30897. ], Texture.prototype, "isBlocking", null);
  30898. return Texture;
  30899. }(BABYLON.BaseTexture));
  30900. BABYLON.Texture = Texture;
  30901. })(BABYLON || (BABYLON = {}));
  30902. //# sourceMappingURL=babylon.texture.js.map
  30903. var BABYLON;
  30904. (function (BABYLON) {
  30905. /**
  30906. * @hidden
  30907. **/
  30908. var _InstancesBatch = /** @class */ (function () {
  30909. function _InstancesBatch() {
  30910. this.mustReturn = false;
  30911. this.visibleInstances = new Array();
  30912. this.renderSelf = new Array();
  30913. }
  30914. return _InstancesBatch;
  30915. }());
  30916. BABYLON._InstancesBatch = _InstancesBatch;
  30917. var Mesh = /** @class */ (function (_super) {
  30918. __extends(Mesh, _super);
  30919. /**
  30920. * @constructor
  30921. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30922. * @param {Scene} scene The scene to add this mesh to.
  30923. * @param {Node} parent The parent of this mesh, if it has one
  30924. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30925. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30926. * When false, achieved by calling a clone(), also passing False.
  30927. * This will make creation of children, recursive.
  30928. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30929. */
  30930. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30931. if (scene === void 0) { scene = null; }
  30932. if (parent === void 0) { parent = null; }
  30933. if (source === void 0) { source = null; }
  30934. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30935. var _this = _super.call(this, name, scene) || this;
  30936. // Events
  30937. /**
  30938. * An event triggered before rendering the mesh
  30939. */
  30940. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30941. /**
  30942. * An event triggered after rendering the mesh
  30943. */
  30944. _this.onAfterRenderObservable = new BABYLON.Observable();
  30945. /**
  30946. * An event triggered before drawing the mesh
  30947. */
  30948. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30949. // Members
  30950. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30951. _this.instances = new Array();
  30952. _this._LODLevels = new Array();
  30953. _this._visibleInstances = {};
  30954. _this._renderIdForInstances = new Array();
  30955. _this._batchCache = new _InstancesBatch();
  30956. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30957. // Use by builder only to know what orientation were the mesh build in.
  30958. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30959. _this.overrideMaterialSideOrientation = null;
  30960. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30961. // Will be used to save a source mesh reference, If any
  30962. _this._source = null;
  30963. scene = _this.getScene();
  30964. if (source) {
  30965. // Source mesh
  30966. _this._source = source;
  30967. // Geometry
  30968. if (source._geometry) {
  30969. source._geometry.applyToMesh(_this);
  30970. }
  30971. // Deep copy
  30972. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30973. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  30974. // Metadata
  30975. if (source.metadata && source.metadata.clone) {
  30976. _this.metadata = source.metadata.clone();
  30977. }
  30978. else {
  30979. _this.metadata = source.metadata;
  30980. }
  30981. // Tags
  30982. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30983. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30984. }
  30985. // Parent
  30986. _this.parent = source.parent;
  30987. // Pivot
  30988. _this.setPivotMatrix(source.getPivotMatrix());
  30989. _this.id = name + "." + source.id;
  30990. // Material
  30991. _this.material = source.material;
  30992. var index;
  30993. if (!doNotCloneChildren) {
  30994. // Children
  30995. var directDescendants = source.getDescendants(true);
  30996. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30997. var child = directDescendants[index_1];
  30998. if (child.clone) {
  30999. child.clone(name + "." + child.name, _this);
  31000. }
  31001. }
  31002. }
  31003. // Physics clone
  31004. var physicsEngine = _this.getScene().getPhysicsEngine();
  31005. if (clonePhysicsImpostor && physicsEngine) {
  31006. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31007. if (impostor) {
  31008. _this.physicsImpostor = impostor.clone(_this);
  31009. }
  31010. }
  31011. // Particles
  31012. for (index = 0; index < scene.particleSystems.length; index++) {
  31013. var system = scene.particleSystems[index];
  31014. if (system.emitter === source) {
  31015. system.clone(system.name, _this);
  31016. }
  31017. }
  31018. _this.computeWorldMatrix(true);
  31019. }
  31020. // Parent
  31021. if (parent !== null) {
  31022. _this.parent = parent;
  31023. }
  31024. return _this;
  31025. }
  31026. Object.defineProperty(Mesh, "FRONTSIDE", {
  31027. /**
  31028. * Mesh side orientation : usually the external or front surface
  31029. */
  31030. get: function () {
  31031. return Mesh._FRONTSIDE;
  31032. },
  31033. enumerable: true,
  31034. configurable: true
  31035. });
  31036. Object.defineProperty(Mesh, "BACKSIDE", {
  31037. /**
  31038. * Mesh side orientation : usually the internal or back surface
  31039. */
  31040. get: function () {
  31041. return Mesh._BACKSIDE;
  31042. },
  31043. enumerable: true,
  31044. configurable: true
  31045. });
  31046. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31047. /**
  31048. * Mesh side orientation : both internal and external or front and back surfaces
  31049. */
  31050. get: function () {
  31051. return Mesh._DOUBLESIDE;
  31052. },
  31053. enumerable: true,
  31054. configurable: true
  31055. });
  31056. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31057. /**
  31058. * Mesh side orientation : by default, `FRONTSIDE`
  31059. */
  31060. get: function () {
  31061. return Mesh._DEFAULTSIDE;
  31062. },
  31063. enumerable: true,
  31064. configurable: true
  31065. });
  31066. Object.defineProperty(Mesh, "NO_CAP", {
  31067. /**
  31068. * Mesh cap setting : no cap
  31069. */
  31070. get: function () {
  31071. return Mesh._NO_CAP;
  31072. },
  31073. enumerable: true,
  31074. configurable: true
  31075. });
  31076. Object.defineProperty(Mesh, "CAP_START", {
  31077. /**
  31078. * Mesh cap setting : one cap at the beginning of the mesh
  31079. */
  31080. get: function () {
  31081. return Mesh._CAP_START;
  31082. },
  31083. enumerable: true,
  31084. configurable: true
  31085. });
  31086. Object.defineProperty(Mesh, "CAP_END", {
  31087. /**
  31088. * Mesh cap setting : one cap at the end of the mesh
  31089. */
  31090. get: function () {
  31091. return Mesh._CAP_END;
  31092. },
  31093. enumerable: true,
  31094. configurable: true
  31095. });
  31096. Object.defineProperty(Mesh, "CAP_ALL", {
  31097. /**
  31098. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31099. */
  31100. get: function () {
  31101. return Mesh._CAP_ALL;
  31102. },
  31103. enumerable: true,
  31104. configurable: true
  31105. });
  31106. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31107. set: function (callback) {
  31108. if (this._onBeforeDrawObserver) {
  31109. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31110. }
  31111. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31112. },
  31113. enumerable: true,
  31114. configurable: true
  31115. });
  31116. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31117. get: function () {
  31118. return this._morphTargetManager;
  31119. },
  31120. set: function (value) {
  31121. if (this._morphTargetManager === value) {
  31122. return;
  31123. }
  31124. this._morphTargetManager = value;
  31125. this._syncGeometryWithMorphTargetManager();
  31126. },
  31127. enumerable: true,
  31128. configurable: true
  31129. });
  31130. Object.defineProperty(Mesh.prototype, "source", {
  31131. get: function () {
  31132. return this._source;
  31133. },
  31134. enumerable: true,
  31135. configurable: true
  31136. });
  31137. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31138. get: function () {
  31139. return this._unIndexed;
  31140. },
  31141. set: function (value) {
  31142. if (this._unIndexed !== value) {
  31143. this._unIndexed = value;
  31144. this._markSubMeshesAsAttributesDirty();
  31145. }
  31146. },
  31147. enumerable: true,
  31148. configurable: true
  31149. });
  31150. // Methods
  31151. /**
  31152. * Returns the string "Mesh".
  31153. */
  31154. Mesh.prototype.getClassName = function () {
  31155. return "Mesh";
  31156. };
  31157. /**
  31158. * Returns a string.
  31159. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31160. */
  31161. Mesh.prototype.toString = function (fullDetails) {
  31162. var ret = _super.prototype.toString.call(this, fullDetails);
  31163. ret += ", n vertices: " + this.getTotalVertices();
  31164. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31165. if (this.animations) {
  31166. for (var i = 0; i < this.animations.length; i++) {
  31167. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31168. }
  31169. }
  31170. if (fullDetails) {
  31171. if (this._geometry) {
  31172. var ib = this.getIndices();
  31173. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31174. if (vb && ib) {
  31175. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31176. }
  31177. }
  31178. else {
  31179. ret += ", flat shading: UNKNOWN";
  31180. }
  31181. }
  31182. return ret;
  31183. };
  31184. Mesh.prototype._unBindEffect = function () {
  31185. _super.prototype._unBindEffect.call(this);
  31186. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31187. var instance = _a[_i];
  31188. instance._unBindEffect();
  31189. }
  31190. };
  31191. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31192. /**
  31193. * True if the mesh has some Levels Of Details (LOD).
  31194. * Returns a boolean.
  31195. */
  31196. get: function () {
  31197. return this._LODLevels.length > 0;
  31198. },
  31199. enumerable: true,
  31200. configurable: true
  31201. });
  31202. /**
  31203. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31204. * @returns an array of {BABYLON.MeshLODLevel}
  31205. */
  31206. Mesh.prototype.getLODLevels = function () {
  31207. return this._LODLevels;
  31208. };
  31209. Mesh.prototype._sortLODLevels = function () {
  31210. this._LODLevels.sort(function (a, b) {
  31211. if (a.distance < b.distance) {
  31212. return 1;
  31213. }
  31214. if (a.distance > b.distance) {
  31215. return -1;
  31216. }
  31217. return 0;
  31218. });
  31219. };
  31220. /**
  31221. * Add a mesh as LOD level triggered at the given distance.
  31222. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31223. * @param {number} distance The distance from the center of the object to show this level
  31224. * @param {Mesh} mesh The mesh to be added as LOD level
  31225. * @return {Mesh} This mesh (for chaining)
  31226. */
  31227. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31228. if (mesh && mesh._masterMesh) {
  31229. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31230. return this;
  31231. }
  31232. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31233. this._LODLevels.push(level);
  31234. if (mesh) {
  31235. mesh._masterMesh = this;
  31236. }
  31237. this._sortLODLevels();
  31238. return this;
  31239. };
  31240. /**
  31241. * Returns the LOD level mesh at the passed distance or null if not found.
  31242. * It is related to the method `addLODLevel(distance, mesh)`.
  31243. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31244. * Returns an object Mesh or `null`.
  31245. */
  31246. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31247. for (var index = 0; index < this._LODLevels.length; index++) {
  31248. var level = this._LODLevels[index];
  31249. if (level.distance === distance) {
  31250. return level.mesh;
  31251. }
  31252. }
  31253. return null;
  31254. };
  31255. /**
  31256. * Remove a mesh from the LOD array
  31257. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31258. * @param {Mesh} mesh The mesh to be removed.
  31259. * @return {Mesh} This mesh (for chaining)
  31260. */
  31261. Mesh.prototype.removeLODLevel = function (mesh) {
  31262. for (var index = 0; index < this._LODLevels.length; index++) {
  31263. if (this._LODLevels[index].mesh === mesh) {
  31264. this._LODLevels.splice(index, 1);
  31265. if (mesh) {
  31266. mesh._masterMesh = null;
  31267. }
  31268. }
  31269. }
  31270. this._sortLODLevels();
  31271. return this;
  31272. };
  31273. /**
  31274. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31275. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31276. */
  31277. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31278. if (!this._LODLevels || this._LODLevels.length === 0) {
  31279. return this;
  31280. }
  31281. var bSphere;
  31282. if (boundingSphere) {
  31283. bSphere = boundingSphere;
  31284. }
  31285. else {
  31286. var boundingInfo = this.getBoundingInfo();
  31287. bSphere = boundingInfo.boundingSphere;
  31288. }
  31289. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31290. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31291. if (this.onLODLevelSelection) {
  31292. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31293. }
  31294. return this;
  31295. }
  31296. for (var index = 0; index < this._LODLevels.length; index++) {
  31297. var level = this._LODLevels[index];
  31298. if (level.distance < distanceToCamera) {
  31299. if (level.mesh) {
  31300. level.mesh._preActivate();
  31301. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31302. }
  31303. if (this.onLODLevelSelection) {
  31304. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31305. }
  31306. return level.mesh;
  31307. }
  31308. }
  31309. if (this.onLODLevelSelection) {
  31310. this.onLODLevelSelection(distanceToCamera, this, this);
  31311. }
  31312. return this;
  31313. };
  31314. Object.defineProperty(Mesh.prototype, "geometry", {
  31315. /**
  31316. * Returns the mesh internal Geometry object.
  31317. */
  31318. get: function () {
  31319. return this._geometry;
  31320. },
  31321. enumerable: true,
  31322. configurable: true
  31323. });
  31324. /**
  31325. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31326. */
  31327. Mesh.prototype.getTotalVertices = function () {
  31328. if (this._geometry === null || this._geometry === undefined) {
  31329. return 0;
  31330. }
  31331. return this._geometry.getTotalVertices();
  31332. };
  31333. /**
  31334. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31335. * 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.
  31336. * You can force the copy with forceCopy === true
  31337. * Returns null if the mesh has no geometry or no vertex buffer.
  31338. * Possible `kind` values :
  31339. * - BABYLON.VertexBuffer.PositionKind
  31340. * - BABYLON.VertexBuffer.UVKind
  31341. * - BABYLON.VertexBuffer.UV2Kind
  31342. * - BABYLON.VertexBuffer.UV3Kind
  31343. * - BABYLON.VertexBuffer.UV4Kind
  31344. * - BABYLON.VertexBuffer.UV5Kind
  31345. * - BABYLON.VertexBuffer.UV6Kind
  31346. * - BABYLON.VertexBuffer.ColorKind
  31347. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31348. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31349. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31350. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31351. */
  31352. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31353. if (!this._geometry) {
  31354. return null;
  31355. }
  31356. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31357. };
  31358. /**
  31359. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31360. * Returns `null` if the mesh has no geometry.
  31361. * Possible `kind` values :
  31362. * - BABYLON.VertexBuffer.PositionKind
  31363. * - BABYLON.VertexBuffer.UVKind
  31364. * - BABYLON.VertexBuffer.UV2Kind
  31365. * - BABYLON.VertexBuffer.UV3Kind
  31366. * - BABYLON.VertexBuffer.UV4Kind
  31367. * - BABYLON.VertexBuffer.UV5Kind
  31368. * - BABYLON.VertexBuffer.UV6Kind
  31369. * - BABYLON.VertexBuffer.ColorKind
  31370. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31371. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31372. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31373. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31374. */
  31375. Mesh.prototype.getVertexBuffer = function (kind) {
  31376. if (!this._geometry) {
  31377. return null;
  31378. }
  31379. return this._geometry.getVertexBuffer(kind);
  31380. };
  31381. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31382. if (!this._geometry) {
  31383. if (this._delayInfo) {
  31384. return this._delayInfo.indexOf(kind) !== -1;
  31385. }
  31386. return false;
  31387. }
  31388. return this._geometry.isVerticesDataPresent(kind);
  31389. };
  31390. /**
  31391. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31392. * Possible `kind` values :
  31393. * - BABYLON.VertexBuffer.PositionKind
  31394. * - BABYLON.VertexBuffer.UVKind
  31395. * - BABYLON.VertexBuffer.UV2Kind
  31396. * - BABYLON.VertexBuffer.UV3Kind
  31397. * - BABYLON.VertexBuffer.UV4Kind
  31398. * - BABYLON.VertexBuffer.UV5Kind
  31399. * - BABYLON.VertexBuffer.UV6Kind
  31400. * - BABYLON.VertexBuffer.ColorKind
  31401. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31402. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31403. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31404. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31405. */
  31406. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31407. if (!this._geometry) {
  31408. if (this._delayInfo) {
  31409. return this._delayInfo.indexOf(kind) !== -1;
  31410. }
  31411. return false;
  31412. }
  31413. return this._geometry.isVertexBufferUpdatable(kind);
  31414. };
  31415. /**
  31416. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31417. * Possible `kind` values :
  31418. * - BABYLON.VertexBuffer.PositionKind
  31419. * - BABYLON.VertexBuffer.UVKind
  31420. * - BABYLON.VertexBuffer.UV2Kind
  31421. * - BABYLON.VertexBuffer.UV3Kind
  31422. * - BABYLON.VertexBuffer.UV4Kind
  31423. * - BABYLON.VertexBuffer.UV5Kind
  31424. * - BABYLON.VertexBuffer.UV6Kind
  31425. * - BABYLON.VertexBuffer.ColorKind
  31426. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31427. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31428. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31429. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31430. */
  31431. Mesh.prototype.getVerticesDataKinds = function () {
  31432. if (!this._geometry) {
  31433. var result = new Array();
  31434. if (this._delayInfo) {
  31435. this._delayInfo.forEach(function (kind, index, array) {
  31436. result.push(kind);
  31437. });
  31438. }
  31439. return result;
  31440. }
  31441. return this._geometry.getVerticesDataKinds();
  31442. };
  31443. /**
  31444. * Returns a positive integer : the total number of indices in this mesh geometry.
  31445. * Returns zero if the mesh has no geometry.
  31446. */
  31447. Mesh.prototype.getTotalIndices = function () {
  31448. if (!this._geometry) {
  31449. return 0;
  31450. }
  31451. return this._geometry.getTotalIndices();
  31452. };
  31453. /**
  31454. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31455. * 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.
  31456. * Returns an empty array if the mesh has no geometry.
  31457. */
  31458. Mesh.prototype.getIndices = function (copyWhenShared) {
  31459. if (!this._geometry) {
  31460. return [];
  31461. }
  31462. return this._geometry.getIndices(copyWhenShared);
  31463. };
  31464. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31465. get: function () {
  31466. return this._masterMesh !== null && this._masterMesh !== undefined;
  31467. },
  31468. enumerable: true,
  31469. configurable: true
  31470. });
  31471. /**
  31472. * Determine if the current mesh is ready to be rendered
  31473. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31474. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31475. * @returns true if all associated assets are ready (material, textures, shaders)
  31476. */
  31477. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31478. if (completeCheck === void 0) { completeCheck = false; }
  31479. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31480. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31481. return false;
  31482. }
  31483. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31484. return false;
  31485. }
  31486. if (!this.subMeshes || this.subMeshes.length === 0) {
  31487. return true;
  31488. }
  31489. if (!completeCheck) {
  31490. return true;
  31491. }
  31492. var engine = this.getEngine();
  31493. var scene = this.getScene();
  31494. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31495. this.computeWorldMatrix();
  31496. var mat = this.material || scene.defaultMaterial;
  31497. if (mat) {
  31498. if (mat.storeEffectOnSubMeshes) {
  31499. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31500. var subMesh = _a[_i];
  31501. var effectiveMaterial = subMesh.getMaterial();
  31502. if (effectiveMaterial) {
  31503. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31504. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31505. return false;
  31506. }
  31507. }
  31508. else {
  31509. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31510. return false;
  31511. }
  31512. }
  31513. }
  31514. }
  31515. }
  31516. else {
  31517. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31518. return false;
  31519. }
  31520. }
  31521. }
  31522. // Shadows
  31523. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31524. var light = _c[_b];
  31525. var generator = light.getShadowGenerator();
  31526. if (generator) {
  31527. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31528. var subMesh = _e[_d];
  31529. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31530. return false;
  31531. }
  31532. }
  31533. }
  31534. }
  31535. // LOD
  31536. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31537. var lod = _g[_f];
  31538. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31539. return false;
  31540. }
  31541. }
  31542. return true;
  31543. };
  31544. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31545. /**
  31546. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31547. * This property is pertinent only for updatable parametric shapes.
  31548. */
  31549. get: function () {
  31550. return this._areNormalsFrozen;
  31551. },
  31552. enumerable: true,
  31553. configurable: true
  31554. });
  31555. /**
  31556. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31557. * It has no effect at all on other shapes.
  31558. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31559. * Returns the Mesh.
  31560. */
  31561. Mesh.prototype.freezeNormals = function () {
  31562. this._areNormalsFrozen = true;
  31563. return this;
  31564. };
  31565. /**
  31566. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31567. * It has no effect at all on other shapes.
  31568. * It reactivates the mesh normals computation if it was previously frozen.
  31569. * Returns the Mesh.
  31570. */
  31571. Mesh.prototype.unfreezeNormals = function () {
  31572. this._areNormalsFrozen = false;
  31573. return this;
  31574. };
  31575. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31576. /**
  31577. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31578. */
  31579. set: function (count) {
  31580. this._overridenInstanceCount = count;
  31581. },
  31582. enumerable: true,
  31583. configurable: true
  31584. });
  31585. // Methods
  31586. Mesh.prototype._preActivate = function () {
  31587. var sceneRenderId = this.getScene().getRenderId();
  31588. if (this._preActivateId === sceneRenderId) {
  31589. return this;
  31590. }
  31591. this._preActivateId = sceneRenderId;
  31592. this._visibleInstances = null;
  31593. return this;
  31594. };
  31595. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31596. if (this._visibleInstances) {
  31597. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31598. }
  31599. return this;
  31600. };
  31601. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31602. if (!this._visibleInstances) {
  31603. this._visibleInstances = {};
  31604. this._visibleInstances.defaultRenderId = renderId;
  31605. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31606. }
  31607. if (!this._visibleInstances[renderId]) {
  31608. this._visibleInstances[renderId] = new Array();
  31609. }
  31610. this._visibleInstances[renderId].push(instance);
  31611. return this;
  31612. };
  31613. /**
  31614. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31615. * This means the mesh underlying bounding box and sphere are recomputed.
  31616. * Returns the Mesh.
  31617. */
  31618. Mesh.prototype.refreshBoundingInfo = function () {
  31619. return this._refreshBoundingInfo(false);
  31620. };
  31621. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31622. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31623. return this;
  31624. }
  31625. var data = this._getPositionData(applySkeleton);
  31626. if (data) {
  31627. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31628. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31629. }
  31630. if (this.subMeshes) {
  31631. for (var index = 0; index < this.subMeshes.length; index++) {
  31632. this.subMeshes[index].refreshBoundingInfo();
  31633. }
  31634. }
  31635. this._updateBoundingInfo();
  31636. return this;
  31637. };
  31638. Mesh.prototype._getPositionData = function (applySkeleton) {
  31639. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31640. if (data && applySkeleton && this.skeleton) {
  31641. data = BABYLON.Tools.Slice(data);
  31642. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31643. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31644. if (matricesWeightsData && matricesIndicesData) {
  31645. var needExtras = this.numBoneInfluencers > 4;
  31646. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31647. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31648. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31649. var tempVector = BABYLON.Tmp.Vector3[0];
  31650. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31651. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31652. var matWeightIdx = 0;
  31653. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31654. finalMatrix.reset();
  31655. var inf;
  31656. var weight;
  31657. for (inf = 0; inf < 4; inf++) {
  31658. weight = matricesWeightsData[matWeightIdx + inf];
  31659. if (weight <= 0)
  31660. break;
  31661. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31662. finalMatrix.addToSelf(tempMatrix);
  31663. }
  31664. if (needExtras) {
  31665. for (inf = 0; inf < 4; inf++) {
  31666. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31667. if (weight <= 0)
  31668. break;
  31669. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31670. finalMatrix.addToSelf(tempMatrix);
  31671. }
  31672. }
  31673. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31674. tempVector.toArray(data, index);
  31675. }
  31676. }
  31677. }
  31678. return data;
  31679. };
  31680. Mesh.prototype._createGlobalSubMesh = function (force) {
  31681. var totalVertices = this.getTotalVertices();
  31682. if (!totalVertices || !this.getIndices()) {
  31683. return null;
  31684. }
  31685. // Check if we need to recreate the submeshes
  31686. if (this.subMeshes && this.subMeshes.length > 0) {
  31687. var ib = this.getIndices();
  31688. if (!ib) {
  31689. return null;
  31690. }
  31691. var totalIndices = ib.length;
  31692. var needToRecreate = false;
  31693. if (force) {
  31694. needToRecreate = true;
  31695. }
  31696. else {
  31697. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31698. var submesh = _a[_i];
  31699. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31700. needToRecreate = true;
  31701. break;
  31702. }
  31703. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31704. needToRecreate = true;
  31705. break;
  31706. }
  31707. }
  31708. }
  31709. if (!needToRecreate) {
  31710. return this.subMeshes[0];
  31711. }
  31712. }
  31713. this.releaseSubMeshes();
  31714. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31715. };
  31716. Mesh.prototype.subdivide = function (count) {
  31717. if (count < 1) {
  31718. return;
  31719. }
  31720. var totalIndices = this.getTotalIndices();
  31721. var subdivisionSize = (totalIndices / count) | 0;
  31722. var offset = 0;
  31723. // Ensure that subdivisionSize is a multiple of 3
  31724. while (subdivisionSize % 3 !== 0) {
  31725. subdivisionSize++;
  31726. }
  31727. this.releaseSubMeshes();
  31728. for (var index = 0; index < count; index++) {
  31729. if (offset >= totalIndices) {
  31730. break;
  31731. }
  31732. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31733. offset += subdivisionSize;
  31734. }
  31735. this.synchronizeInstances();
  31736. };
  31737. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31738. if (updatable === void 0) { updatable = false; }
  31739. if (!this._geometry) {
  31740. var vertexData = new BABYLON.VertexData();
  31741. vertexData.set(data, kind);
  31742. var scene = this.getScene();
  31743. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31744. }
  31745. else {
  31746. this._geometry.setVerticesData(kind, data, updatable, stride);
  31747. }
  31748. return this;
  31749. };
  31750. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31751. if (updatable === void 0) { updatable = true; }
  31752. var vb = this.getVertexBuffer(kind);
  31753. if (!vb || vb.isUpdatable() === updatable) {
  31754. return;
  31755. }
  31756. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31757. };
  31758. /**
  31759. * Sets the mesh VertexBuffer.
  31760. * Returns the Mesh.
  31761. */
  31762. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31763. if (!this._geometry) {
  31764. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31765. }
  31766. this._geometry.setVerticesBuffer(buffer);
  31767. return this;
  31768. };
  31769. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31770. if (!this._geometry) {
  31771. return this;
  31772. }
  31773. if (!makeItUnique) {
  31774. this._geometry.updateVerticesData(kind, data, updateExtends);
  31775. }
  31776. else {
  31777. this.makeGeometryUnique();
  31778. this.updateVerticesData(kind, data, updateExtends, false);
  31779. }
  31780. return this;
  31781. };
  31782. /**
  31783. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31784. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31785. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31786. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31787. * Returns the Mesh.
  31788. */
  31789. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31790. if (computeNormals === void 0) { computeNormals = true; }
  31791. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31792. if (!positions) {
  31793. return this;
  31794. }
  31795. positionFunction(positions);
  31796. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31797. if (computeNormals) {
  31798. var indices = this.getIndices();
  31799. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31800. if (!normals) {
  31801. return this;
  31802. }
  31803. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31804. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31805. }
  31806. return this;
  31807. };
  31808. /**
  31809. * Creates a un-shared specific occurence of the geometry for the mesh.
  31810. * Returns the Mesh.
  31811. */
  31812. Mesh.prototype.makeGeometryUnique = function () {
  31813. if (!this._geometry) {
  31814. return this;
  31815. }
  31816. var oldGeometry = this._geometry;
  31817. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31818. oldGeometry.releaseForMesh(this, true);
  31819. geometry.applyToMesh(this);
  31820. return this;
  31821. };
  31822. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31823. if (totalVertices === void 0) { totalVertices = null; }
  31824. if (updatable === void 0) { updatable = false; }
  31825. if (!this._geometry) {
  31826. var vertexData = new BABYLON.VertexData();
  31827. vertexData.indices = indices;
  31828. var scene = this.getScene();
  31829. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31830. }
  31831. else {
  31832. this._geometry.setIndices(indices, totalVertices, updatable);
  31833. }
  31834. return this;
  31835. };
  31836. /**
  31837. * Update the current index buffer
  31838. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31839. * Returns the Mesh.
  31840. */
  31841. Mesh.prototype.updateIndices = function (indices, offset) {
  31842. if (!this._geometry) {
  31843. return this;
  31844. }
  31845. this._geometry.updateIndices(indices, offset);
  31846. return this;
  31847. };
  31848. /**
  31849. * Invert the geometry to move from a right handed system to a left handed one.
  31850. * Returns the Mesh.
  31851. */
  31852. Mesh.prototype.toLeftHanded = function () {
  31853. if (!this._geometry) {
  31854. return this;
  31855. }
  31856. this._geometry.toLeftHanded();
  31857. return this;
  31858. };
  31859. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31860. if (!this._geometry) {
  31861. return this;
  31862. }
  31863. var engine = this.getScene().getEngine();
  31864. // Wireframe
  31865. var indexToBind;
  31866. if (this._unIndexed) {
  31867. indexToBind = null;
  31868. }
  31869. else {
  31870. switch (fillMode) {
  31871. case BABYLON.Material.PointFillMode:
  31872. indexToBind = null;
  31873. break;
  31874. case BABYLON.Material.WireFrameFillMode:
  31875. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31876. break;
  31877. default:
  31878. case BABYLON.Material.TriangleFillMode:
  31879. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31880. break;
  31881. }
  31882. }
  31883. // VBOs
  31884. this._geometry._bind(effect, indexToBind);
  31885. return this;
  31886. };
  31887. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31888. if (alternate === void 0) { alternate = false; }
  31889. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31890. return this;
  31891. }
  31892. this.onBeforeDrawObservable.notifyObservers(this);
  31893. var scene = this.getScene();
  31894. var engine = scene.getEngine();
  31895. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31896. // or triangles as points
  31897. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31898. }
  31899. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31900. // Triangles as wireframe
  31901. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31902. }
  31903. else {
  31904. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31905. }
  31906. if (scene._isAlternateRenderingEnabled && !alternate) {
  31907. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31908. if (!effect || !scene.activeCamera) {
  31909. return this;
  31910. }
  31911. scene._switchToAlternateCameraConfiguration(true);
  31912. this._effectiveMaterial.bindView(effect);
  31913. this._effectiveMaterial.bindViewProjection(effect);
  31914. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31915. this._draw(subMesh, fillMode, instancesCount, true);
  31916. engine.setViewport(scene.activeCamera.viewport);
  31917. scene._switchToAlternateCameraConfiguration(false);
  31918. this._effectiveMaterial.bindView(effect);
  31919. this._effectiveMaterial.bindViewProjection(effect);
  31920. }
  31921. return this;
  31922. };
  31923. /**
  31924. * Registers for this mesh a javascript function called just before the rendering process.
  31925. * This function is passed the current mesh.
  31926. * Return the Mesh.
  31927. */
  31928. Mesh.prototype.registerBeforeRender = function (func) {
  31929. this.onBeforeRenderObservable.add(func);
  31930. return this;
  31931. };
  31932. /**
  31933. * Disposes a previously registered javascript function called before the rendering.
  31934. * This function is passed the current mesh.
  31935. * Returns the Mesh.
  31936. */
  31937. Mesh.prototype.unregisterBeforeRender = function (func) {
  31938. this.onBeforeRenderObservable.removeCallback(func);
  31939. return this;
  31940. };
  31941. /**
  31942. * Registers for this mesh a javascript function called just after the rendering is complete.
  31943. * This function is passed the current mesh.
  31944. * Returns the Mesh.
  31945. */
  31946. Mesh.prototype.registerAfterRender = function (func) {
  31947. this.onAfterRenderObservable.add(func);
  31948. return this;
  31949. };
  31950. /**
  31951. * Disposes a previously registered javascript function called after the rendering.
  31952. * This function is passed the current mesh.
  31953. * Return the Mesh.
  31954. */
  31955. Mesh.prototype.unregisterAfterRender = function (func) {
  31956. this.onAfterRenderObservable.removeCallback(func);
  31957. return this;
  31958. };
  31959. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31960. var scene = this.getScene();
  31961. this._batchCache.mustReturn = false;
  31962. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31963. this._batchCache.visibleInstances[subMeshId] = null;
  31964. if (this._visibleInstances) {
  31965. var currentRenderId = scene.getRenderId();
  31966. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31967. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31968. var selfRenderId = this._renderId;
  31969. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31970. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31971. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31972. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31973. }
  31974. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31975. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31976. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31977. this._batchCache.mustReturn = true;
  31978. return this._batchCache;
  31979. }
  31980. if (currentRenderId !== selfRenderId) {
  31981. this._batchCache.renderSelf[subMeshId] = false;
  31982. }
  31983. }
  31984. this._renderIdForInstances[subMeshId] = currentRenderId;
  31985. }
  31986. return this._batchCache;
  31987. };
  31988. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31989. var visibleInstances = batch.visibleInstances[subMesh._id];
  31990. if (!visibleInstances) {
  31991. return this;
  31992. }
  31993. var matricesCount = visibleInstances.length + 1;
  31994. var bufferSize = matricesCount * 16 * 4;
  31995. var currentInstancesBufferSize = this._instancesBufferSize;
  31996. var instancesBuffer = this._instancesBuffer;
  31997. while (this._instancesBufferSize < bufferSize) {
  31998. this._instancesBufferSize *= 2;
  31999. }
  32000. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32001. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32002. }
  32003. var offset = 0;
  32004. var instancesCount = 0;
  32005. var world = this.getWorldMatrix();
  32006. if (batch.renderSelf[subMesh._id]) {
  32007. world.copyToArray(this._instancesData, offset);
  32008. offset += 16;
  32009. instancesCount++;
  32010. }
  32011. if (visibleInstances) {
  32012. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32013. var instance = visibleInstances[instanceIndex];
  32014. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32015. offset += 16;
  32016. instancesCount++;
  32017. }
  32018. }
  32019. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32020. if (instancesBuffer) {
  32021. instancesBuffer.dispose();
  32022. }
  32023. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32024. this._instancesBuffer = instancesBuffer;
  32025. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32026. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32027. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32028. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32029. }
  32030. else {
  32031. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32032. }
  32033. this._bind(subMesh, effect, fillMode);
  32034. this._draw(subMesh, fillMode, instancesCount);
  32035. engine.unbindInstanceAttributes();
  32036. return this;
  32037. };
  32038. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32039. var scene = this.getScene();
  32040. var engine = scene.getEngine();
  32041. if (hardwareInstancedRendering) {
  32042. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32043. }
  32044. else {
  32045. if (batch.renderSelf[subMesh._id]) {
  32046. // Draw
  32047. if (onBeforeDraw) {
  32048. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32049. }
  32050. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32051. }
  32052. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32053. if (visibleInstancesForSubMesh) {
  32054. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32055. var instance = visibleInstancesForSubMesh[instanceIndex];
  32056. // World
  32057. var world = instance.getWorldMatrix();
  32058. if (onBeforeDraw) {
  32059. onBeforeDraw(true, world, effectiveMaterial);
  32060. }
  32061. // Draw
  32062. this._draw(subMesh, fillMode);
  32063. }
  32064. }
  32065. }
  32066. return this;
  32067. };
  32068. /**
  32069. * Triggers the draw call for the mesh.
  32070. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32071. * Returns the Mesh.
  32072. */
  32073. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32074. this._checkOcclusionQuery();
  32075. if (this._isOccluded) {
  32076. return this;
  32077. }
  32078. var scene = this.getScene();
  32079. // Managing instances
  32080. var batch = this._getInstancesRenderList(subMesh._id);
  32081. if (batch.mustReturn) {
  32082. return this;
  32083. }
  32084. // Checking geometry state
  32085. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32086. return this;
  32087. }
  32088. this.onBeforeRenderObservable.notifyObservers(this);
  32089. var engine = scene.getEngine();
  32090. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32091. // Material
  32092. var material = subMesh.getMaterial();
  32093. if (!material) {
  32094. return this;
  32095. }
  32096. this._effectiveMaterial = material;
  32097. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32098. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32099. return this;
  32100. }
  32101. }
  32102. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32103. return this;
  32104. }
  32105. // Alpha mode
  32106. if (enableAlphaMode) {
  32107. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32108. }
  32109. // Outline - step 1
  32110. var savedDepthWrite = engine.getDepthWrite();
  32111. if (this.renderOutline) {
  32112. engine.setDepthWrite(false);
  32113. scene.getOutlineRenderer().render(subMesh, batch);
  32114. engine.setDepthWrite(savedDepthWrite);
  32115. }
  32116. var effect;
  32117. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32118. effect = subMesh.effect;
  32119. }
  32120. else {
  32121. effect = this._effectiveMaterial.getEffect();
  32122. }
  32123. if (!effect) {
  32124. return this;
  32125. }
  32126. var sideOrientation = this.overrideMaterialSideOrientation;
  32127. if (sideOrientation == null) {
  32128. sideOrientation = this._effectiveMaterial.sideOrientation;
  32129. if (this._getWorldMatrixDeterminant() < 0) {
  32130. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32131. }
  32132. }
  32133. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32134. if (this._effectiveMaterial.forceDepthWrite) {
  32135. engine.setDepthWrite(true);
  32136. }
  32137. // Bind
  32138. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32139. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32140. this._bind(subMesh, effect, fillMode);
  32141. }
  32142. var world = this.getWorldMatrix();
  32143. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32144. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32145. }
  32146. else {
  32147. this._effectiveMaterial.bind(world, this);
  32148. }
  32149. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32150. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32151. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32152. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32153. }
  32154. // Draw
  32155. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32156. // Unbind
  32157. this._effectiveMaterial.unbind();
  32158. // Outline - step 2
  32159. if (this.renderOutline && savedDepthWrite) {
  32160. engine.setDepthWrite(true);
  32161. engine.setColorWrite(false);
  32162. scene.getOutlineRenderer().render(subMesh, batch);
  32163. engine.setColorWrite(true);
  32164. }
  32165. // Overlay
  32166. if (this.renderOverlay) {
  32167. var currentMode = engine.getAlphaMode();
  32168. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32169. scene.getOutlineRenderer().render(subMesh, batch, true);
  32170. engine.setAlphaMode(currentMode);
  32171. }
  32172. this.onAfterRenderObservable.notifyObservers(this);
  32173. return this;
  32174. };
  32175. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32176. if (isInstance && effectiveMaterial) {
  32177. effectiveMaterial.bindOnlyWorldMatrix(world);
  32178. }
  32179. };
  32180. /**
  32181. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32182. */
  32183. Mesh.prototype.getEmittedParticleSystems = function () {
  32184. var results = new Array();
  32185. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32186. var particleSystem = this.getScene().particleSystems[index];
  32187. if (particleSystem.emitter === this) {
  32188. results.push(particleSystem);
  32189. }
  32190. }
  32191. return results;
  32192. };
  32193. /**
  32194. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32195. */
  32196. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32197. var results = new Array();
  32198. var descendants = this.getDescendants();
  32199. descendants.push(this);
  32200. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32201. var particleSystem = this.getScene().particleSystems[index];
  32202. var emitter = particleSystem.emitter;
  32203. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32204. results.push(particleSystem);
  32205. }
  32206. }
  32207. return results;
  32208. };
  32209. Mesh.prototype._checkDelayState = function () {
  32210. var scene = this.getScene();
  32211. if (this._geometry) {
  32212. this._geometry.load(scene);
  32213. }
  32214. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32215. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32216. this._queueLoad(scene);
  32217. }
  32218. return this;
  32219. };
  32220. Mesh.prototype._queueLoad = function (scene) {
  32221. var _this = this;
  32222. scene._addPendingData(this);
  32223. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32224. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32225. if (data instanceof ArrayBuffer) {
  32226. _this._delayLoadingFunction(data, _this);
  32227. }
  32228. else {
  32229. _this._delayLoadingFunction(JSON.parse(data), _this);
  32230. }
  32231. _this.instances.forEach(function (instance) {
  32232. instance._syncSubMeshes();
  32233. });
  32234. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32235. scene._removePendingData(_this);
  32236. }, function () { }, scene.database, getBinaryData);
  32237. return this;
  32238. };
  32239. /**
  32240. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32241. */
  32242. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32243. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32244. return false;
  32245. }
  32246. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32247. return false;
  32248. }
  32249. this._checkDelayState();
  32250. return true;
  32251. };
  32252. /**
  32253. * Sets the mesh material by the material or multiMaterial `id` property.
  32254. * The material `id` is a string identifying the material or the multiMaterial.
  32255. * This method returns the Mesh.
  32256. */
  32257. Mesh.prototype.setMaterialByID = function (id) {
  32258. var materials = this.getScene().materials;
  32259. var index;
  32260. for (index = materials.length - 1; index > -1; index--) {
  32261. if (materials[index].id === id) {
  32262. this.material = materials[index];
  32263. return this;
  32264. }
  32265. }
  32266. // Multi
  32267. var multiMaterials = this.getScene().multiMaterials;
  32268. for (index = multiMaterials.length - 1; index > -1; index--) {
  32269. if (multiMaterials[index].id === id) {
  32270. this.material = multiMaterials[index];
  32271. return this;
  32272. }
  32273. }
  32274. return this;
  32275. };
  32276. /**
  32277. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32278. */
  32279. Mesh.prototype.getAnimatables = function () {
  32280. var results = new Array();
  32281. if (this.material) {
  32282. results.push(this.material);
  32283. }
  32284. if (this.skeleton) {
  32285. results.push(this.skeleton);
  32286. }
  32287. return results;
  32288. };
  32289. /**
  32290. * Modifies the mesh geometry according to the passed transformation matrix.
  32291. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32292. * The mesh normals are modified accordingly the same transformation.
  32293. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32294. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32295. * Returns the Mesh.
  32296. */
  32297. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32298. // Position
  32299. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32300. return this;
  32301. }
  32302. var submeshes = this.subMeshes.splice(0);
  32303. this._resetPointsArrayCache();
  32304. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32305. var temp = new Array();
  32306. var index;
  32307. for (index = 0; index < data.length; index += 3) {
  32308. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32309. }
  32310. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32311. // Normals
  32312. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32313. return this;
  32314. }
  32315. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32316. temp = [];
  32317. for (index = 0; index < data.length; index += 3) {
  32318. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32319. }
  32320. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32321. // flip faces?
  32322. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32323. this.flipFaces();
  32324. }
  32325. // Restore submeshes
  32326. this.releaseSubMeshes();
  32327. this.subMeshes = submeshes;
  32328. return this;
  32329. };
  32330. /**
  32331. * Modifies the mesh geometry according to its own current World Matrix.
  32332. * The mesh World Matrix is then reset.
  32333. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32334. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32335. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32336. * Returns the Mesh.
  32337. */
  32338. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32339. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32340. this.scaling.copyFromFloats(1, 1, 1);
  32341. this.position.copyFromFloats(0, 0, 0);
  32342. this.rotation.copyFromFloats(0, 0, 0);
  32343. //only if quaternion is already set
  32344. if (this.rotationQuaternion) {
  32345. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32346. }
  32347. this._worldMatrix = BABYLON.Matrix.Identity();
  32348. return this;
  32349. };
  32350. Object.defineProperty(Mesh.prototype, "_positions", {
  32351. // Cache
  32352. get: function () {
  32353. if (this._geometry) {
  32354. return this._geometry._positions;
  32355. }
  32356. return null;
  32357. },
  32358. enumerable: true,
  32359. configurable: true
  32360. });
  32361. Mesh.prototype._resetPointsArrayCache = function () {
  32362. if (this._geometry) {
  32363. this._geometry._resetPointsArrayCache();
  32364. }
  32365. return this;
  32366. };
  32367. Mesh.prototype._generatePointsArray = function () {
  32368. if (this._geometry) {
  32369. return this._geometry._generatePointsArray();
  32370. }
  32371. return false;
  32372. };
  32373. /**
  32374. * Returns a new Mesh object generated from the current mesh properties.
  32375. * This method must not get confused with createInstance().
  32376. * The parameter `name` is a string, the name given to the new mesh.
  32377. * The optional parameter `newParent` can be any Node object (default `null`).
  32378. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32379. * 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.
  32380. */
  32381. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32382. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32383. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32384. };
  32385. /**
  32386. * Releases resources associated with this mesh.
  32387. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32388. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32389. */
  32390. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32391. var _this = this;
  32392. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32393. this.morphTargetManager = null;
  32394. if (this._geometry) {
  32395. this._geometry.releaseForMesh(this, true);
  32396. }
  32397. // Sources
  32398. var meshes = this.getScene().meshes;
  32399. meshes.forEach(function (abstractMesh) {
  32400. var mesh = abstractMesh;
  32401. if (mesh._source && mesh._source === _this) {
  32402. mesh._source = null;
  32403. }
  32404. });
  32405. this._source = null;
  32406. // Instances
  32407. if (this._instancesBuffer) {
  32408. this._instancesBuffer.dispose();
  32409. this._instancesBuffer = null;
  32410. }
  32411. while (this.instances.length) {
  32412. this.instances[0].dispose();
  32413. }
  32414. // Effect layers.
  32415. var effectLayers = this.getScene().effectLayers;
  32416. for (var i = 0; i < effectLayers.length; i++) {
  32417. var effectLayer = effectLayers[i];
  32418. if (effectLayer) {
  32419. effectLayer._disposeMesh(this);
  32420. }
  32421. }
  32422. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32423. };
  32424. /**
  32425. * Modifies the mesh geometry according to a displacement map.
  32426. * 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.
  32427. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32428. * This method returns nothing.
  32429. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32430. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32431. * 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.
  32432. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32433. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32434. *
  32435. * Returns the Mesh.
  32436. */
  32437. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32438. var _this = this;
  32439. var scene = this.getScene();
  32440. var onload = function (img) {
  32441. // Getting height map data
  32442. var canvas = document.createElement("canvas");
  32443. var context = canvas.getContext("2d");
  32444. var heightMapWidth = img.width;
  32445. var heightMapHeight = img.height;
  32446. canvas.width = heightMapWidth;
  32447. canvas.height = heightMapHeight;
  32448. context.drawImage(img, 0, 0);
  32449. // Create VertexData from map data
  32450. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32451. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32452. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32453. //execute success callback, if set
  32454. if (onSuccess) {
  32455. onSuccess(_this);
  32456. }
  32457. };
  32458. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32459. return this;
  32460. };
  32461. /**
  32462. * Modifies the mesh geometry according to a displacementMap buffer.
  32463. * 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.
  32464. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32465. * This method returns nothing.
  32466. * 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.
  32467. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32468. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32469. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32470. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32471. *
  32472. * Returns the Mesh.
  32473. */
  32474. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32475. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32476. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32477. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32478. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32479. return this;
  32480. }
  32481. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32482. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32483. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32484. var position = BABYLON.Vector3.Zero();
  32485. var normal = BABYLON.Vector3.Zero();
  32486. var uv = BABYLON.Vector2.Zero();
  32487. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32488. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32489. for (var index = 0; index < positions.length; index += 3) {
  32490. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32491. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32492. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32493. // Compute height
  32494. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32495. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32496. var pos = (u + v * heightMapWidth) * 4;
  32497. var r = buffer[pos] / 255.0;
  32498. var g = buffer[pos + 1] / 255.0;
  32499. var b = buffer[pos + 2] / 255.0;
  32500. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32501. normal.normalize();
  32502. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32503. position = position.add(normal);
  32504. position.toArray(positions, index);
  32505. }
  32506. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32507. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32508. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32509. return this;
  32510. };
  32511. /**
  32512. * Modify the mesh to get a flat shading rendering.
  32513. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32514. * This method returns the Mesh.
  32515. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32516. */
  32517. Mesh.prototype.convertToFlatShadedMesh = function () {
  32518. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32519. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32520. var kinds = this.getVerticesDataKinds();
  32521. var vbs = {};
  32522. var data = {};
  32523. var newdata = {};
  32524. var updatableNormals = false;
  32525. var kindIndex;
  32526. var kind;
  32527. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32528. kind = kinds[kindIndex];
  32529. var vertexBuffer = this.getVertexBuffer(kind);
  32530. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32531. updatableNormals = vertexBuffer.isUpdatable();
  32532. kinds.splice(kindIndex, 1);
  32533. kindIndex--;
  32534. continue;
  32535. }
  32536. vbs[kind] = vertexBuffer;
  32537. data[kind] = vbs[kind].getData();
  32538. newdata[kind] = [];
  32539. }
  32540. // Save previous submeshes
  32541. var previousSubmeshes = this.subMeshes.slice(0);
  32542. var indices = this.getIndices();
  32543. var totalIndices = this.getTotalIndices();
  32544. // Generating unique vertices per face
  32545. var index;
  32546. for (index = 0; index < totalIndices; index++) {
  32547. var vertexIndex = indices[index];
  32548. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32549. kind = kinds[kindIndex];
  32550. var stride = vbs[kind].getStrideSize();
  32551. for (var offset = 0; offset < stride; offset++) {
  32552. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32553. }
  32554. }
  32555. }
  32556. // Updating faces & normal
  32557. var normals = [];
  32558. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32559. for (index = 0; index < totalIndices; index += 3) {
  32560. indices[index] = index;
  32561. indices[index + 1] = index + 1;
  32562. indices[index + 2] = index + 2;
  32563. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32564. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32565. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32566. var p1p2 = p1.subtract(p2);
  32567. var p3p2 = p3.subtract(p2);
  32568. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32569. // Store same normals for every vertex
  32570. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32571. normals.push(normal.x);
  32572. normals.push(normal.y);
  32573. normals.push(normal.z);
  32574. }
  32575. }
  32576. this.setIndices(indices);
  32577. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32578. // Updating vertex buffers
  32579. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32580. kind = kinds[kindIndex];
  32581. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32582. }
  32583. // Updating submeshes
  32584. this.releaseSubMeshes();
  32585. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32586. var previousOne = previousSubmeshes[submeshIndex];
  32587. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32588. }
  32589. this.synchronizeInstances();
  32590. return this;
  32591. };
  32592. /**
  32593. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32594. * In other words, more vertices, no more indices and a single bigger VBO.
  32595. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32596. * Returns the Mesh.
  32597. */
  32598. Mesh.prototype.convertToUnIndexedMesh = function () {
  32599. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32600. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32601. var kinds = this.getVerticesDataKinds();
  32602. var vbs = {};
  32603. var data = {};
  32604. var newdata = {};
  32605. var kindIndex;
  32606. var kind;
  32607. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32608. kind = kinds[kindIndex];
  32609. var vertexBuffer = this.getVertexBuffer(kind);
  32610. vbs[kind] = vertexBuffer;
  32611. data[kind] = vbs[kind].getData();
  32612. newdata[kind] = [];
  32613. }
  32614. // Save previous submeshes
  32615. var previousSubmeshes = this.subMeshes.slice(0);
  32616. var indices = this.getIndices();
  32617. var totalIndices = this.getTotalIndices();
  32618. // Generating unique vertices per face
  32619. var index;
  32620. for (index = 0; index < totalIndices; index++) {
  32621. var vertexIndex = indices[index];
  32622. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32623. kind = kinds[kindIndex];
  32624. var stride = vbs[kind].getStrideSize();
  32625. for (var offset = 0; offset < stride; offset++) {
  32626. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32627. }
  32628. }
  32629. }
  32630. // Updating indices
  32631. for (index = 0; index < totalIndices; index += 3) {
  32632. indices[index] = index;
  32633. indices[index + 1] = index + 1;
  32634. indices[index + 2] = index + 2;
  32635. }
  32636. this.setIndices(indices);
  32637. // Updating vertex buffers
  32638. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32639. kind = kinds[kindIndex];
  32640. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32641. }
  32642. // Updating submeshes
  32643. this.releaseSubMeshes();
  32644. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32645. var previousOne = previousSubmeshes[submeshIndex];
  32646. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32647. }
  32648. this._unIndexed = true;
  32649. this.synchronizeInstances();
  32650. return this;
  32651. };
  32652. /**
  32653. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32654. * This method returns the Mesh.
  32655. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32656. */
  32657. Mesh.prototype.flipFaces = function (flipNormals) {
  32658. if (flipNormals === void 0) { flipNormals = false; }
  32659. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32660. var i;
  32661. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32662. for (i = 0; i < vertex_data.normals.length; i++) {
  32663. vertex_data.normals[i] *= -1;
  32664. }
  32665. }
  32666. if (vertex_data.indices) {
  32667. var temp;
  32668. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32669. // reassign indices
  32670. temp = vertex_data.indices[i + 1];
  32671. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32672. vertex_data.indices[i + 2] = temp;
  32673. }
  32674. }
  32675. vertex_data.applyToMesh(this);
  32676. return this;
  32677. };
  32678. // Instances
  32679. /**
  32680. * Creates a new InstancedMesh object from the mesh model.
  32681. * An instance shares the same properties and the same material than its model.
  32682. * Only these properties of each instance can then be set individually :
  32683. * - position
  32684. * - rotation
  32685. * - rotationQuaternion
  32686. * - setPivotMatrix
  32687. * - scaling
  32688. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32689. * Warning : this method is not supported for Line mesh and LineSystem
  32690. */
  32691. Mesh.prototype.createInstance = function (name) {
  32692. return new BABYLON.InstancedMesh(name, this);
  32693. };
  32694. /**
  32695. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32696. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32697. * This method returns the Mesh.
  32698. */
  32699. Mesh.prototype.synchronizeInstances = function () {
  32700. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32701. var instance = this.instances[instanceIndex];
  32702. instance._syncSubMeshes();
  32703. }
  32704. return this;
  32705. };
  32706. /**
  32707. * Simplify the mesh according to the given array of settings.
  32708. * Function will return immediately and will simplify async. It returns the Mesh.
  32709. * @param settings a collection of simplification settings.
  32710. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32711. * @param type the type of simplification to run.
  32712. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32713. */
  32714. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32715. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32716. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32717. this.getScene().simplificationQueue.addTask({
  32718. settings: settings,
  32719. parallelProcessing: parallelProcessing,
  32720. mesh: this,
  32721. simplificationType: simplificationType,
  32722. successCallback: successCallback
  32723. });
  32724. return this;
  32725. };
  32726. /**
  32727. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32728. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32729. * This should be used together with the simplification to avoid disappearing triangles.
  32730. * Returns the Mesh.
  32731. * @param successCallback an optional success callback to be called after the optimization finished.
  32732. */
  32733. Mesh.prototype.optimizeIndices = function (successCallback) {
  32734. var _this = this;
  32735. var indices = this.getIndices();
  32736. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32737. if (!positions || !indices) {
  32738. return this;
  32739. }
  32740. var vectorPositions = new Array();
  32741. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32742. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32743. }
  32744. var dupes = new Array();
  32745. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32746. var realPos = vectorPositions.length - 1 - iteration;
  32747. var testedPosition = vectorPositions[realPos];
  32748. for (var j = 0; j < realPos; ++j) {
  32749. var againstPosition = vectorPositions[j];
  32750. if (testedPosition.equals(againstPosition)) {
  32751. dupes[realPos] = j;
  32752. break;
  32753. }
  32754. }
  32755. }, function () {
  32756. for (var i = 0; i < indices.length; ++i) {
  32757. indices[i] = dupes[indices[i]] || indices[i];
  32758. }
  32759. //indices are now reordered
  32760. var originalSubMeshes = _this.subMeshes.slice(0);
  32761. _this.setIndices(indices);
  32762. _this.subMeshes = originalSubMeshes;
  32763. if (successCallback) {
  32764. successCallback(_this);
  32765. }
  32766. });
  32767. return this;
  32768. };
  32769. Mesh.prototype.serialize = function (serializationObject) {
  32770. serializationObject.name = this.name;
  32771. serializationObject.id = this.id;
  32772. serializationObject.type = this.getClassName();
  32773. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32774. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32775. }
  32776. serializationObject.position = this.position.asArray();
  32777. if (this.rotationQuaternion) {
  32778. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32779. }
  32780. else if (this.rotation) {
  32781. serializationObject.rotation = this.rotation.asArray();
  32782. }
  32783. serializationObject.scaling = this.scaling.asArray();
  32784. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32785. serializationObject.isEnabled = this.isEnabled(false);
  32786. serializationObject.isVisible = this.isVisible;
  32787. serializationObject.infiniteDistance = this.infiniteDistance;
  32788. serializationObject.pickable = this.isPickable;
  32789. serializationObject.receiveShadows = this.receiveShadows;
  32790. serializationObject.billboardMode = this.billboardMode;
  32791. serializationObject.visibility = this.visibility;
  32792. serializationObject.checkCollisions = this.checkCollisions;
  32793. serializationObject.isBlocker = this.isBlocker;
  32794. // Parent
  32795. if (this.parent) {
  32796. serializationObject.parentId = this.parent.id;
  32797. }
  32798. // Geometry
  32799. serializationObject.isUnIndexed = this.isUnIndexed;
  32800. var geometry = this._geometry;
  32801. if (geometry) {
  32802. var geometryId = geometry.id;
  32803. serializationObject.geometryId = geometryId;
  32804. // SubMeshes
  32805. serializationObject.subMeshes = [];
  32806. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32807. var subMesh = this.subMeshes[subIndex];
  32808. serializationObject.subMeshes.push({
  32809. materialIndex: subMesh.materialIndex,
  32810. verticesStart: subMesh.verticesStart,
  32811. verticesCount: subMesh.verticesCount,
  32812. indexStart: subMesh.indexStart,
  32813. indexCount: subMesh.indexCount
  32814. });
  32815. }
  32816. }
  32817. // Material
  32818. if (this.material) {
  32819. serializationObject.materialId = this.material.id;
  32820. }
  32821. else {
  32822. this.material = null;
  32823. }
  32824. // Morph targets
  32825. if (this.morphTargetManager) {
  32826. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32827. }
  32828. // Skeleton
  32829. if (this.skeleton) {
  32830. serializationObject.skeletonId = this.skeleton.id;
  32831. }
  32832. // Physics
  32833. //TODO implement correct serialization for physics impostors.
  32834. var impostor = this.getPhysicsImpostor();
  32835. if (impostor) {
  32836. serializationObject.physicsMass = impostor.getParam("mass");
  32837. serializationObject.physicsFriction = impostor.getParam("friction");
  32838. serializationObject.physicsRestitution = impostor.getParam("mass");
  32839. serializationObject.physicsImpostor = impostor.type;
  32840. }
  32841. // Metadata
  32842. if (this.metadata) {
  32843. serializationObject.metadata = this.metadata;
  32844. }
  32845. // Instances
  32846. serializationObject.instances = [];
  32847. for (var index = 0; index < this.instances.length; index++) {
  32848. var instance = this.instances[index];
  32849. var serializationInstance = {
  32850. name: instance.name,
  32851. id: instance.id,
  32852. position: instance.position.asArray(),
  32853. scaling: instance.scaling.asArray()
  32854. };
  32855. if (instance.rotationQuaternion) {
  32856. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32857. }
  32858. else if (instance.rotation) {
  32859. serializationInstance.rotation = instance.rotation.asArray();
  32860. }
  32861. serializationObject.instances.push(serializationInstance);
  32862. // Animations
  32863. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32864. serializationInstance.ranges = instance.serializeAnimationRanges();
  32865. }
  32866. //
  32867. // Animations
  32868. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32869. serializationObject.ranges = this.serializeAnimationRanges();
  32870. // Layer mask
  32871. serializationObject.layerMask = this.layerMask;
  32872. // Alpha
  32873. serializationObject.alphaIndex = this.alphaIndex;
  32874. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32875. // Overlay
  32876. serializationObject.overlayAlpha = this.overlayAlpha;
  32877. serializationObject.overlayColor = this.overlayColor.asArray();
  32878. serializationObject.renderOverlay = this.renderOverlay;
  32879. // Fog
  32880. serializationObject.applyFog = this.applyFog;
  32881. // Action Manager
  32882. if (this.actionManager) {
  32883. serializationObject.actions = this.actionManager.serialize(this.name);
  32884. }
  32885. };
  32886. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32887. if (!this.geometry) {
  32888. return;
  32889. }
  32890. this._markSubMeshesAsAttributesDirty();
  32891. var morphTargetManager = this._morphTargetManager;
  32892. if (morphTargetManager && morphTargetManager.vertexCount) {
  32893. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32894. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32895. this.morphTargetManager = null;
  32896. return;
  32897. }
  32898. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32899. var morphTarget = morphTargetManager.getActiveTarget(index);
  32900. var positions = morphTarget.getPositions();
  32901. if (!positions) {
  32902. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32903. return;
  32904. }
  32905. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32906. var normals = morphTarget.getNormals();
  32907. if (normals) {
  32908. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32909. }
  32910. var tangents = morphTarget.getTangents();
  32911. if (tangents) {
  32912. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32913. }
  32914. }
  32915. }
  32916. else {
  32917. var index = 0;
  32918. // Positions
  32919. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32920. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32921. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32922. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32923. }
  32924. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32925. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32926. }
  32927. index++;
  32928. }
  32929. }
  32930. };
  32931. // Statics
  32932. /**
  32933. * Returns a new Mesh object parsed from the source provided.
  32934. * The parameter `parsedMesh` is the source.
  32935. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32936. */
  32937. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32938. var mesh;
  32939. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32940. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32941. }
  32942. else {
  32943. mesh = new Mesh(parsedMesh.name, scene);
  32944. }
  32945. mesh.id = parsedMesh.id;
  32946. if (BABYLON.Tags) {
  32947. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32948. }
  32949. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32950. if (parsedMesh.metadata !== undefined) {
  32951. mesh.metadata = parsedMesh.metadata;
  32952. }
  32953. if (parsedMesh.rotationQuaternion) {
  32954. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32955. }
  32956. else if (parsedMesh.rotation) {
  32957. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32958. }
  32959. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32960. if (parsedMesh.localMatrix) {
  32961. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32962. }
  32963. else if (parsedMesh.pivotMatrix) {
  32964. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32965. }
  32966. mesh.setEnabled(parsedMesh.isEnabled);
  32967. mesh.isVisible = parsedMesh.isVisible;
  32968. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32969. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32970. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32971. if (parsedMesh.applyFog !== undefined) {
  32972. mesh.applyFog = parsedMesh.applyFog;
  32973. }
  32974. if (parsedMesh.pickable !== undefined) {
  32975. mesh.isPickable = parsedMesh.pickable;
  32976. }
  32977. if (parsedMesh.alphaIndex !== undefined) {
  32978. mesh.alphaIndex = parsedMesh.alphaIndex;
  32979. }
  32980. mesh.receiveShadows = parsedMesh.receiveShadows;
  32981. mesh.billboardMode = parsedMesh.billboardMode;
  32982. if (parsedMesh.visibility !== undefined) {
  32983. mesh.visibility = parsedMesh.visibility;
  32984. }
  32985. mesh.checkCollisions = parsedMesh.checkCollisions;
  32986. if (parsedMesh.isBlocker !== undefined) {
  32987. mesh.isBlocker = parsedMesh.isBlocker;
  32988. }
  32989. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32990. // freezeWorldMatrix
  32991. if (parsedMesh.freezeWorldMatrix) {
  32992. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32993. }
  32994. // Parent
  32995. if (parsedMesh.parentId) {
  32996. mesh._waitingParentId = parsedMesh.parentId;
  32997. }
  32998. // Actions
  32999. if (parsedMesh.actions !== undefined) {
  33000. mesh._waitingActions = parsedMesh.actions;
  33001. }
  33002. // Overlay
  33003. if (parsedMesh.overlayAlpha !== undefined) {
  33004. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33005. }
  33006. if (parsedMesh.overlayColor !== undefined) {
  33007. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33008. }
  33009. if (parsedMesh.renderOverlay !== undefined) {
  33010. mesh.renderOverlay = parsedMesh.renderOverlay;
  33011. }
  33012. // Geometry
  33013. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33014. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33015. if (parsedMesh.delayLoadingFile) {
  33016. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33017. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33018. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33019. if (parsedMesh._binaryInfo) {
  33020. mesh._binaryInfo = parsedMesh._binaryInfo;
  33021. }
  33022. mesh._delayInfo = [];
  33023. if (parsedMesh.hasUVs) {
  33024. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33025. }
  33026. if (parsedMesh.hasUVs2) {
  33027. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33028. }
  33029. if (parsedMesh.hasUVs3) {
  33030. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33031. }
  33032. if (parsedMesh.hasUVs4) {
  33033. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33034. }
  33035. if (parsedMesh.hasUVs5) {
  33036. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33037. }
  33038. if (parsedMesh.hasUVs6) {
  33039. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33040. }
  33041. if (parsedMesh.hasColors) {
  33042. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33043. }
  33044. if (parsedMesh.hasMatricesIndices) {
  33045. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33046. }
  33047. if (parsedMesh.hasMatricesWeights) {
  33048. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33049. }
  33050. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33051. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33052. mesh._checkDelayState();
  33053. }
  33054. }
  33055. else {
  33056. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33057. }
  33058. // Material
  33059. if (parsedMesh.materialId) {
  33060. mesh.setMaterialByID(parsedMesh.materialId);
  33061. }
  33062. else {
  33063. mesh.material = null;
  33064. }
  33065. // Morph targets
  33066. if (parsedMesh.morphTargetManagerId > -1) {
  33067. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33068. }
  33069. // Skeleton
  33070. if (parsedMesh.skeletonId > -1) {
  33071. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33072. if (parsedMesh.numBoneInfluencers) {
  33073. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33074. }
  33075. }
  33076. // Animations
  33077. if (parsedMesh.animations) {
  33078. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33079. var parsedAnimation = parsedMesh.animations[animationIndex];
  33080. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33081. }
  33082. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33083. }
  33084. if (parsedMesh.autoAnimate) {
  33085. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33086. }
  33087. // Layer Mask
  33088. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33089. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33090. }
  33091. else {
  33092. mesh.layerMask = 0x0FFFFFFF;
  33093. }
  33094. // Physics
  33095. if (parsedMesh.physicsImpostor) {
  33096. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33097. mass: parsedMesh.physicsMass,
  33098. friction: parsedMesh.physicsFriction,
  33099. restitution: parsedMesh.physicsRestitution
  33100. }, scene);
  33101. }
  33102. // Instances
  33103. if (parsedMesh.instances) {
  33104. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33105. var parsedInstance = parsedMesh.instances[index];
  33106. var instance = mesh.createInstance(parsedInstance.name);
  33107. if (parsedInstance.id) {
  33108. instance.id = parsedInstance.id;
  33109. }
  33110. if (BABYLON.Tags) {
  33111. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33112. }
  33113. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33114. if (parsedInstance.parentId) {
  33115. instance._waitingParentId = parsedInstance.parentId;
  33116. }
  33117. if (parsedInstance.rotationQuaternion) {
  33118. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33119. }
  33120. else if (parsedInstance.rotation) {
  33121. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33122. }
  33123. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33124. instance.checkCollisions = mesh.checkCollisions;
  33125. if (parsedMesh.animations) {
  33126. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33127. parsedAnimation = parsedMesh.animations[animationIndex];
  33128. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33129. }
  33130. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33131. }
  33132. }
  33133. }
  33134. return mesh;
  33135. };
  33136. /**
  33137. * Creates a ribbon mesh.
  33138. * Please consider using the same method from the MeshBuilder class instead.
  33139. * 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.
  33140. *
  33141. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33142. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33143. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33144. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33145. * 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.
  33146. * 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.
  33147. * 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
  33148. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33149. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33150. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33151. */
  33152. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33153. if (closeArray === void 0) { closeArray = false; }
  33154. if (updatable === void 0) { updatable = false; }
  33155. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33156. pathArray: pathArray,
  33157. closeArray: closeArray,
  33158. closePath: closePath,
  33159. offset: offset,
  33160. updatable: updatable,
  33161. sideOrientation: sideOrientation,
  33162. instance: instance
  33163. }, scene);
  33164. };
  33165. /**
  33166. * Creates a plane polygonal mesh. By default, this is a disc.
  33167. * Please consider using the same method from the MeshBuilder class instead.
  33168. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33169. * 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.
  33170. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33171. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33172. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33173. */
  33174. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33175. if (scene === void 0) { scene = null; }
  33176. var options = {
  33177. radius: radius,
  33178. tessellation: tessellation,
  33179. sideOrientation: sideOrientation,
  33180. updatable: updatable
  33181. };
  33182. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33183. };
  33184. /**
  33185. * Creates a box mesh.
  33186. * Please consider using the same method from the MeshBuilder class instead.
  33187. * The parameter `size` sets the size (float) of each box side (default 1).
  33188. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33189. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33190. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33191. */
  33192. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33193. if (scene === void 0) { scene = null; }
  33194. var options = {
  33195. size: size,
  33196. sideOrientation: sideOrientation,
  33197. updatable: updatable
  33198. };
  33199. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33200. };
  33201. /**
  33202. * Creates a sphere mesh.
  33203. * Please consider using the same method from the MeshBuilder class instead.
  33204. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33205. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33206. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33207. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33208. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33209. */
  33210. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33211. var options = {
  33212. segments: segments,
  33213. diameterX: diameter,
  33214. diameterY: diameter,
  33215. diameterZ: diameter,
  33216. sideOrientation: sideOrientation,
  33217. updatable: updatable
  33218. };
  33219. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33220. };
  33221. /**
  33222. * Creates a cylinder or a cone mesh.
  33223. * Please consider using the same method from the MeshBuilder class instead.
  33224. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33225. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33226. * 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.
  33227. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33228. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33229. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33230. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33231. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33232. */
  33233. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33234. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33235. if (scene !== undefined) {
  33236. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33237. updatable = scene;
  33238. }
  33239. scene = subdivisions;
  33240. subdivisions = 1;
  33241. }
  33242. var options = {
  33243. height: height,
  33244. diameterTop: diameterTop,
  33245. diameterBottom: diameterBottom,
  33246. tessellation: tessellation,
  33247. subdivisions: subdivisions,
  33248. sideOrientation: sideOrientation,
  33249. updatable: updatable
  33250. };
  33251. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33252. };
  33253. // Torus (Code from SharpDX.org)
  33254. /**
  33255. * Creates a torus mesh.
  33256. * Please consider using the same method from the MeshBuilder class instead.
  33257. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33258. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33259. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33260. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33261. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33262. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33263. */
  33264. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33265. var options = {
  33266. diameter: diameter,
  33267. thickness: thickness,
  33268. tessellation: tessellation,
  33269. sideOrientation: sideOrientation,
  33270. updatable: updatable
  33271. };
  33272. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33273. };
  33274. /**
  33275. * Creates a torus knot mesh.
  33276. * Please consider using the same method from the MeshBuilder class instead.
  33277. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33278. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33279. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33280. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33281. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33282. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33283. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33284. */
  33285. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33286. var options = {
  33287. radius: radius,
  33288. tube: tube,
  33289. radialSegments: radialSegments,
  33290. tubularSegments: tubularSegments,
  33291. p: p,
  33292. q: q,
  33293. sideOrientation: sideOrientation,
  33294. updatable: updatable
  33295. };
  33296. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33297. };
  33298. /**
  33299. * Creates a line mesh.
  33300. * Please consider using the same method from the MeshBuilder class instead.
  33301. * 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.
  33302. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33303. * The parameter `points` is an array successive Vector3.
  33304. * 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
  33305. * When updating an instance, remember that only point positions can change, not the number of points.
  33306. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33307. */
  33308. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33309. if (scene === void 0) { scene = null; }
  33310. if (updatable === void 0) { updatable = false; }
  33311. if (instance === void 0) { instance = null; }
  33312. var options = {
  33313. points: points,
  33314. updatable: updatable,
  33315. instance: instance
  33316. };
  33317. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33318. };
  33319. /**
  33320. * Creates a dashed line mesh.
  33321. * Please consider using the same method from the MeshBuilder class instead.
  33322. * 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.
  33323. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33324. * The parameter `points` is an array successive Vector3.
  33325. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33326. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33327. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33328. * 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
  33329. * When updating an instance, remember that only point positions can change, not the number of points.
  33330. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33331. */
  33332. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33333. if (scene === void 0) { scene = null; }
  33334. var options = {
  33335. points: points,
  33336. dashSize: dashSize,
  33337. gapSize: gapSize,
  33338. dashNb: dashNb,
  33339. updatable: updatable,
  33340. instance: instance
  33341. };
  33342. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33343. };
  33344. /**
  33345. * Creates a polygon mesh.
  33346. * Please consider using the same method from the MeshBuilder class instead.
  33347. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33348. * 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.
  33349. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33350. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33351. * Remember you can only change the shape positions, not their number when updating a polygon.
  33352. */
  33353. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33354. var options = {
  33355. shape: shape,
  33356. holes: holes,
  33357. updatable: updatable,
  33358. sideOrientation: sideOrientation
  33359. };
  33360. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33361. };
  33362. /**
  33363. * Creates an extruded polygon mesh, with depth in the Y direction.
  33364. * Please consider using the same method from the MeshBuilder class instead.
  33365. */
  33366. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33367. var options = {
  33368. shape: shape,
  33369. holes: holes,
  33370. depth: depth,
  33371. updatable: updatable,
  33372. sideOrientation: sideOrientation
  33373. };
  33374. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33375. };
  33376. /**
  33377. * Creates an extruded shape mesh.
  33378. * 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.
  33379. * Please consider using the same method from the MeshBuilder class instead.
  33380. *
  33381. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33382. * 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
  33383. * extruded along the Z axis.
  33384. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33385. * 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.
  33386. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33387. * 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
  33388. * 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
  33389. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33390. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33391. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33392. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33393. */
  33394. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33395. if (scene === void 0) { scene = null; }
  33396. var options = {
  33397. shape: shape,
  33398. path: path,
  33399. scale: scale,
  33400. rotation: rotation,
  33401. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33402. sideOrientation: sideOrientation,
  33403. instance: instance,
  33404. updatable: updatable
  33405. };
  33406. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33407. };
  33408. /**
  33409. * Creates an custom extruded shape mesh.
  33410. * 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.
  33411. * Please consider using the same method from the MeshBuilder class instead.
  33412. *
  33413. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33414. * 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
  33415. * extruded along the Z axis.
  33416. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33417. * 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
  33418. * and the distance of this point from the begining of the path :
  33419. * ```javascript
  33420. * var rotationFunction = function(i, distance) {
  33421. * // do things
  33422. * return rotationValue; }
  33423. * ```
  33424. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33425. * 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
  33426. * and the distance of this point from the begining of the path :
  33427. * ```javascript
  33428. * var scaleFunction = function(i, distance) {
  33429. * // do things
  33430. * return scaleValue;}
  33431. * ```
  33432. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33433. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33434. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33435. * 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
  33436. * 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
  33437. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33438. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33439. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33440. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33441. */
  33442. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33443. var options = {
  33444. shape: shape,
  33445. path: path,
  33446. scaleFunction: scaleFunction,
  33447. rotationFunction: rotationFunction,
  33448. ribbonCloseArray: ribbonCloseArray,
  33449. ribbonClosePath: ribbonClosePath,
  33450. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33451. sideOrientation: sideOrientation,
  33452. instance: instance,
  33453. updatable: updatable
  33454. };
  33455. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33456. };
  33457. /**
  33458. * Creates lathe mesh.
  33459. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33460. * Please consider using the same method from the MeshBuilder class instead.
  33461. * 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
  33462. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33463. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33464. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33465. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33466. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33467. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33468. */
  33469. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33470. var options = {
  33471. shape: shape,
  33472. radius: radius,
  33473. tessellation: tessellation,
  33474. sideOrientation: sideOrientation,
  33475. updatable: updatable
  33476. };
  33477. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33478. };
  33479. /**
  33480. * Creates a plane mesh.
  33481. * Please consider using the same method from the MeshBuilder class instead.
  33482. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33483. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33484. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33485. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33486. */
  33487. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33488. var options = {
  33489. size: size,
  33490. width: size,
  33491. height: size,
  33492. sideOrientation: sideOrientation,
  33493. updatable: updatable
  33494. };
  33495. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33496. };
  33497. /**
  33498. * Creates a ground mesh.
  33499. * Please consider using the same method from the MeshBuilder class instead.
  33500. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33501. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33502. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33503. */
  33504. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33505. var options = {
  33506. width: width,
  33507. height: height,
  33508. subdivisions: subdivisions,
  33509. updatable: updatable
  33510. };
  33511. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33512. };
  33513. /**
  33514. * Creates a tiled ground mesh.
  33515. * Please consider using the same method from the MeshBuilder class instead.
  33516. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33517. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33518. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33519. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33520. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33521. * numbers of subdivisions on the ground width and height of each tile.
  33522. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33523. */
  33524. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33525. var options = {
  33526. xmin: xmin,
  33527. zmin: zmin,
  33528. xmax: xmax,
  33529. zmax: zmax,
  33530. subdivisions: subdivisions,
  33531. precision: precision,
  33532. updatable: updatable
  33533. };
  33534. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33535. };
  33536. /**
  33537. * Creates a ground mesh from a height map.
  33538. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33539. * Please consider using the same method from the MeshBuilder class instead.
  33540. * The parameter `url` sets the URL of the height map image resource.
  33541. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33542. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33543. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33544. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33545. * 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).
  33546. * This function is passed the newly built mesh :
  33547. * ```javascript
  33548. * function(mesh) { // do things
  33549. * return; }
  33550. * ```
  33551. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33552. */
  33553. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33554. var options = {
  33555. width: width,
  33556. height: height,
  33557. subdivisions: subdivisions,
  33558. minHeight: minHeight,
  33559. maxHeight: maxHeight,
  33560. updatable: updatable,
  33561. onReady: onReady
  33562. };
  33563. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33564. };
  33565. /**
  33566. * Creates a tube mesh.
  33567. * 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.
  33568. * Please consider using the same method from the MeshBuilder class instead.
  33569. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33570. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33571. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33572. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33573. * 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.
  33574. * It must return a radius value (positive float) :
  33575. * ```javascript
  33576. * var radiusFunction = function(i, distance) {
  33577. * // do things
  33578. * return radius; }
  33579. * ```
  33580. * 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
  33581. * 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
  33582. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33583. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33584. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33585. */
  33586. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33587. var options = {
  33588. path: path,
  33589. radius: radius,
  33590. tessellation: tessellation,
  33591. radiusFunction: radiusFunction,
  33592. arc: 1,
  33593. cap: cap,
  33594. updatable: updatable,
  33595. sideOrientation: sideOrientation,
  33596. instance: instance
  33597. };
  33598. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33599. };
  33600. /**
  33601. * Creates a polyhedron mesh.
  33602. * Please consider using the same method from the MeshBuilder class instead.
  33603. * 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
  33604. * to choose the wanted type.
  33605. * The parameter `size` (positive float, default 1) sets the polygon size.
  33606. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33607. * 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`.
  33608. * 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
  33609. * 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)`).
  33610. * 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
  33611. * 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.
  33612. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33613. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33614. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33615. */
  33616. Mesh.CreatePolyhedron = function (name, options, scene) {
  33617. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33618. };
  33619. /**
  33620. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33621. * Please consider using the same method from the MeshBuilder class instead.
  33622. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33623. * 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`).
  33624. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33625. * 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.
  33626. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33627. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33628. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33629. */
  33630. Mesh.CreateIcoSphere = function (name, options, scene) {
  33631. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33632. };
  33633. /**
  33634. * Creates a decal mesh.
  33635. * Please consider using the same method from the MeshBuilder class instead.
  33636. * 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.
  33637. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33638. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33639. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33640. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33641. */
  33642. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33643. var options = {
  33644. position: position,
  33645. normal: normal,
  33646. size: size,
  33647. angle: angle
  33648. };
  33649. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33650. };
  33651. // Skeletons
  33652. /**
  33653. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33654. */
  33655. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33656. if (!this._sourcePositions) {
  33657. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33658. if (!source) {
  33659. return this._sourcePositions;
  33660. }
  33661. this._sourcePositions = new Float32Array(source);
  33662. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33663. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33664. }
  33665. }
  33666. return this._sourcePositions;
  33667. };
  33668. /**
  33669. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33670. */
  33671. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33672. if (!this._sourceNormals) {
  33673. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33674. if (!source) {
  33675. return this._sourceNormals;
  33676. }
  33677. this._sourceNormals = new Float32Array(source);
  33678. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33679. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33680. }
  33681. }
  33682. return this._sourceNormals;
  33683. };
  33684. /**
  33685. * Updates the vertex buffer by applying transformation from the bones.
  33686. * Returns the Mesh.
  33687. *
  33688. * @param {skeleton} skeleton to apply
  33689. */
  33690. Mesh.prototype.applySkeleton = function (skeleton) {
  33691. if (!this.geometry) {
  33692. return this;
  33693. }
  33694. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33695. return this;
  33696. }
  33697. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33698. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33699. return this;
  33700. }
  33701. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33702. return this;
  33703. }
  33704. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33705. return this;
  33706. }
  33707. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33708. return this;
  33709. }
  33710. if (!this._sourcePositions) {
  33711. var submeshes = this.subMeshes.slice();
  33712. this.setPositionsForCPUSkinning();
  33713. this.subMeshes = submeshes;
  33714. }
  33715. if (!this._sourceNormals) {
  33716. this.setNormalsForCPUSkinning();
  33717. }
  33718. // positionsData checks for not being Float32Array will only pass at most once
  33719. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33720. if (!positionsData) {
  33721. return this;
  33722. }
  33723. if (!(positionsData instanceof Float32Array)) {
  33724. positionsData = new Float32Array(positionsData);
  33725. }
  33726. // normalsData checks for not being Float32Array will only pass at most once
  33727. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33728. if (!normalsData) {
  33729. return this;
  33730. }
  33731. if (!(normalsData instanceof Float32Array)) {
  33732. normalsData = new Float32Array(normalsData);
  33733. }
  33734. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33735. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33736. if (!matricesWeightsData || !matricesIndicesData) {
  33737. return this;
  33738. }
  33739. var needExtras = this.numBoneInfluencers > 4;
  33740. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33741. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33742. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33743. var tempVector3 = BABYLON.Vector3.Zero();
  33744. var finalMatrix = new BABYLON.Matrix();
  33745. var tempMatrix = new BABYLON.Matrix();
  33746. var matWeightIdx = 0;
  33747. var inf;
  33748. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33749. var weight;
  33750. for (inf = 0; inf < 4; inf++) {
  33751. weight = matricesWeightsData[matWeightIdx + inf];
  33752. if (weight > 0) {
  33753. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33754. finalMatrix.addToSelf(tempMatrix);
  33755. }
  33756. else
  33757. break;
  33758. }
  33759. if (needExtras) {
  33760. for (inf = 0; inf < 4; inf++) {
  33761. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33762. if (weight > 0) {
  33763. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33764. finalMatrix.addToSelf(tempMatrix);
  33765. }
  33766. else
  33767. break;
  33768. }
  33769. }
  33770. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33771. tempVector3.toArray(positionsData, index);
  33772. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33773. tempVector3.toArray(normalsData, index);
  33774. finalMatrix.reset();
  33775. }
  33776. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33777. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33778. return this;
  33779. };
  33780. // Tools
  33781. /**
  33782. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33783. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33784. */
  33785. Mesh.MinMax = function (meshes) {
  33786. var minVector = null;
  33787. var maxVector = null;
  33788. meshes.forEach(function (mesh, index, array) {
  33789. var boundingInfo = mesh.getBoundingInfo();
  33790. var boundingBox = boundingInfo.boundingBox;
  33791. if (!minVector || !maxVector) {
  33792. minVector = boundingBox.minimumWorld;
  33793. maxVector = boundingBox.maximumWorld;
  33794. }
  33795. else {
  33796. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33797. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33798. }
  33799. });
  33800. if (!minVector || !maxVector) {
  33801. return {
  33802. min: BABYLON.Vector3.Zero(),
  33803. max: BABYLON.Vector3.Zero()
  33804. };
  33805. }
  33806. return {
  33807. min: minVector,
  33808. max: maxVector
  33809. };
  33810. };
  33811. /**
  33812. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33813. */
  33814. Mesh.Center = function (meshesOrMinMaxVector) {
  33815. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33816. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33817. };
  33818. /**
  33819. * Merge the array of meshes into a single mesh for performance reasons.
  33820. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33821. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33822. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33823. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33824. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33825. */
  33826. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33827. if (disposeSource === void 0) { disposeSource = true; }
  33828. var index;
  33829. if (!allow32BitsIndices) {
  33830. var totalVertices = 0;
  33831. // Counting vertices
  33832. for (index = 0; index < meshes.length; index++) {
  33833. if (meshes[index]) {
  33834. totalVertices += meshes[index].getTotalVertices();
  33835. if (totalVertices > 65536) {
  33836. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33837. return null;
  33838. }
  33839. }
  33840. }
  33841. }
  33842. // Merge
  33843. var vertexData = null;
  33844. var otherVertexData;
  33845. var indiceArray = new Array();
  33846. var source = null;
  33847. for (index = 0; index < meshes.length; index++) {
  33848. if (meshes[index]) {
  33849. meshes[index].computeWorldMatrix(true);
  33850. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  33851. otherVertexData.transform(meshes[index].getWorldMatrix());
  33852. if (vertexData) {
  33853. vertexData.merge(otherVertexData);
  33854. }
  33855. else {
  33856. vertexData = otherVertexData;
  33857. source = meshes[index];
  33858. }
  33859. if (subdivideWithSubMeshes) {
  33860. indiceArray.push(meshes[index].getTotalIndices());
  33861. }
  33862. }
  33863. }
  33864. source = source;
  33865. if (!meshSubclass) {
  33866. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33867. }
  33868. vertexData.applyToMesh(meshSubclass);
  33869. // Setting properties
  33870. meshSubclass.material = source.material;
  33871. meshSubclass.checkCollisions = source.checkCollisions;
  33872. // Cleaning
  33873. if (disposeSource) {
  33874. for (index = 0; index < meshes.length; index++) {
  33875. if (meshes[index]) {
  33876. meshes[index].dispose();
  33877. }
  33878. }
  33879. }
  33880. // Subdivide
  33881. if (subdivideWithSubMeshes) {
  33882. //-- Suppresions du submesh global
  33883. meshSubclass.releaseSubMeshes();
  33884. index = 0;
  33885. var offset = 0;
  33886. //-- aplique la subdivision en fonction du tableau d'indices
  33887. while (index < indiceArray.length) {
  33888. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33889. offset += indiceArray[index];
  33890. index++;
  33891. }
  33892. }
  33893. return meshSubclass;
  33894. };
  33895. // Consts
  33896. Mesh._FRONTSIDE = 0;
  33897. Mesh._BACKSIDE = 1;
  33898. Mesh._DOUBLESIDE = 2;
  33899. Mesh._DEFAULTSIDE = 0;
  33900. Mesh._NO_CAP = 0;
  33901. Mesh._CAP_START = 1;
  33902. Mesh._CAP_END = 2;
  33903. Mesh._CAP_ALL = 3;
  33904. return Mesh;
  33905. }(BABYLON.AbstractMesh));
  33906. BABYLON.Mesh = Mesh;
  33907. })(BABYLON || (BABYLON = {}));
  33908. //# sourceMappingURL=babylon.mesh.js.map
  33909. var BABYLON;
  33910. (function (BABYLON) {
  33911. var BaseSubMesh = /** @class */ (function () {
  33912. function BaseSubMesh() {
  33913. }
  33914. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33915. get: function () {
  33916. return this._materialEffect;
  33917. },
  33918. enumerable: true,
  33919. configurable: true
  33920. });
  33921. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33922. if (defines === void 0) { defines = null; }
  33923. if (this._materialEffect === effect) {
  33924. if (!effect) {
  33925. this._materialDefines = null;
  33926. }
  33927. return;
  33928. }
  33929. this._materialDefines = defines;
  33930. this._materialEffect = effect;
  33931. };
  33932. return BaseSubMesh;
  33933. }());
  33934. BABYLON.BaseSubMesh = BaseSubMesh;
  33935. var SubMesh = /** @class */ (function (_super) {
  33936. __extends(SubMesh, _super);
  33937. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33938. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33939. var _this = _super.call(this) || this;
  33940. _this.materialIndex = materialIndex;
  33941. _this.verticesStart = verticesStart;
  33942. _this.verticesCount = verticesCount;
  33943. _this.indexStart = indexStart;
  33944. _this.indexCount = indexCount;
  33945. _this._renderId = 0;
  33946. _this._mesh = mesh;
  33947. _this._renderingMesh = renderingMesh || mesh;
  33948. mesh.subMeshes.push(_this);
  33949. _this._trianglePlanes = [];
  33950. _this._id = mesh.subMeshes.length - 1;
  33951. if (createBoundingBox) {
  33952. _this.refreshBoundingInfo();
  33953. mesh.computeWorldMatrix(true);
  33954. }
  33955. return _this;
  33956. }
  33957. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33958. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33959. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33960. };
  33961. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33962. get: function () {
  33963. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  33964. },
  33965. enumerable: true,
  33966. configurable: true
  33967. });
  33968. /**
  33969. * Returns the submesh BoudingInfo object.
  33970. */
  33971. SubMesh.prototype.getBoundingInfo = function () {
  33972. if (this.IsGlobal) {
  33973. return this._mesh.getBoundingInfo();
  33974. }
  33975. return this._boundingInfo;
  33976. };
  33977. /**
  33978. * Sets the submesh BoundingInfo.
  33979. * Return the SubMesh.
  33980. */
  33981. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33982. this._boundingInfo = boundingInfo;
  33983. return this;
  33984. };
  33985. /**
  33986. * Returns the mesh of the current submesh.
  33987. */
  33988. SubMesh.prototype.getMesh = function () {
  33989. return this._mesh;
  33990. };
  33991. /**
  33992. * Returns the rendering mesh of the submesh.
  33993. */
  33994. SubMesh.prototype.getRenderingMesh = function () {
  33995. return this._renderingMesh;
  33996. };
  33997. /**
  33998. * Returns the submesh material.
  33999. */
  34000. SubMesh.prototype.getMaterial = function () {
  34001. var rootMaterial = this._renderingMesh.material;
  34002. if (rootMaterial === null || rootMaterial === undefined) {
  34003. return this._mesh.getScene().defaultMaterial;
  34004. }
  34005. else if (rootMaterial.getSubMaterial) {
  34006. var multiMaterial = rootMaterial;
  34007. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34008. if (this._currentMaterial !== effectiveMaterial) {
  34009. this._currentMaterial = effectiveMaterial;
  34010. this._materialDefines = null;
  34011. }
  34012. return effectiveMaterial;
  34013. }
  34014. return rootMaterial;
  34015. };
  34016. // Methods
  34017. /**
  34018. * Sets a new updated BoundingInfo object to the submesh.
  34019. * Returns the SubMesh.
  34020. */
  34021. SubMesh.prototype.refreshBoundingInfo = function () {
  34022. this._lastColliderWorldVertices = null;
  34023. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34024. return this;
  34025. }
  34026. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34027. if (!data) {
  34028. this._boundingInfo = this._mesh.getBoundingInfo();
  34029. return this;
  34030. }
  34031. var indices = this._renderingMesh.getIndices();
  34032. var extend;
  34033. //is this the only submesh?
  34034. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34035. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34036. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34037. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34038. }
  34039. else {
  34040. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34041. }
  34042. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34043. return this;
  34044. };
  34045. SubMesh.prototype._checkCollision = function (collider) {
  34046. var boundingInfo = this.getBoundingInfo();
  34047. return boundingInfo._checkCollision(collider);
  34048. };
  34049. /**
  34050. * Updates the submesh BoundingInfo.
  34051. * Returns the Submesh.
  34052. */
  34053. SubMesh.prototype.updateBoundingInfo = function (world) {
  34054. var boundingInfo = this.getBoundingInfo();
  34055. if (!boundingInfo) {
  34056. this.refreshBoundingInfo();
  34057. boundingInfo = this.getBoundingInfo();
  34058. }
  34059. boundingInfo.update(world);
  34060. return this;
  34061. };
  34062. /**
  34063. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34064. * Boolean returned.
  34065. */
  34066. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34067. var boundingInfo = this.getBoundingInfo();
  34068. if (!boundingInfo) {
  34069. return false;
  34070. }
  34071. return boundingInfo.isInFrustum(frustumPlanes);
  34072. };
  34073. /**
  34074. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34075. * Boolean returned.
  34076. */
  34077. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34078. var boundingInfo = this.getBoundingInfo();
  34079. if (!boundingInfo) {
  34080. return false;
  34081. }
  34082. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34083. };
  34084. /**
  34085. * Renders the submesh.
  34086. * Returns it.
  34087. */
  34088. SubMesh.prototype.render = function (enableAlphaMode) {
  34089. this._renderingMesh.render(this, enableAlphaMode);
  34090. return this;
  34091. };
  34092. /**
  34093. * Returns a new Index Buffer.
  34094. * Type returned : WebGLBuffer.
  34095. */
  34096. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34097. if (!this._linesIndexBuffer) {
  34098. var linesIndices = [];
  34099. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34100. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34101. }
  34102. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34103. this.linesIndexCount = linesIndices.length;
  34104. }
  34105. return this._linesIndexBuffer;
  34106. };
  34107. /**
  34108. * True is the passed Ray intersects the submesh bounding box.
  34109. * Boolean returned.
  34110. */
  34111. SubMesh.prototype.canIntersects = function (ray) {
  34112. var boundingInfo = this.getBoundingInfo();
  34113. if (!boundingInfo) {
  34114. return false;
  34115. }
  34116. return ray.intersectsBox(boundingInfo.boundingBox);
  34117. };
  34118. /**
  34119. * Returns an object IntersectionInfo.
  34120. */
  34121. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34122. var intersectInfo = null;
  34123. var material = this.getMaterial();
  34124. if (!material) {
  34125. return null;
  34126. }
  34127. switch (material.fillMode) {
  34128. case BABYLON.Material.PointListDrawMode:
  34129. case BABYLON.Material.LineListDrawMode:
  34130. case BABYLON.Material.LineLoopDrawMode:
  34131. case BABYLON.Material.LineStripDrawMode:
  34132. case BABYLON.Material.TriangleFanDrawMode:
  34133. case BABYLON.Material.TriangleStripDrawMode:
  34134. return null;
  34135. }
  34136. // LineMesh first as it's also a Mesh...
  34137. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34138. var lineMesh = this._mesh;
  34139. // Line test
  34140. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34141. var p0 = positions[indices[index]];
  34142. var p1 = positions[indices[index + 1]];
  34143. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34144. if (length < 0) {
  34145. continue;
  34146. }
  34147. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34148. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34149. if (fastCheck) {
  34150. break;
  34151. }
  34152. }
  34153. }
  34154. }
  34155. else {
  34156. // Triangles test
  34157. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34158. var p0 = positions[indices[index]];
  34159. var p1 = positions[indices[index + 1]];
  34160. var p2 = positions[indices[index + 2]];
  34161. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34162. if (currentIntersectInfo) {
  34163. if (currentIntersectInfo.distance < 0) {
  34164. continue;
  34165. }
  34166. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34167. intersectInfo = currentIntersectInfo;
  34168. intersectInfo.faceId = index / 3;
  34169. if (fastCheck) {
  34170. break;
  34171. }
  34172. }
  34173. }
  34174. }
  34175. }
  34176. return intersectInfo;
  34177. };
  34178. SubMesh.prototype._rebuild = function () {
  34179. if (this._linesIndexBuffer) {
  34180. this._linesIndexBuffer = null;
  34181. }
  34182. };
  34183. // Clone
  34184. /**
  34185. * Creates a new Submesh from the passed Mesh.
  34186. */
  34187. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34188. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34189. if (!this.IsGlobal) {
  34190. var boundingInfo = this.getBoundingInfo();
  34191. if (!boundingInfo) {
  34192. return result;
  34193. }
  34194. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34195. }
  34196. return result;
  34197. };
  34198. // Dispose
  34199. /**
  34200. * Disposes the Submesh.
  34201. * Returns nothing.
  34202. */
  34203. SubMesh.prototype.dispose = function () {
  34204. if (this._linesIndexBuffer) {
  34205. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34206. this._linesIndexBuffer = null;
  34207. }
  34208. // Remove from mesh
  34209. var index = this._mesh.subMeshes.indexOf(this);
  34210. this._mesh.subMeshes.splice(index, 1);
  34211. };
  34212. // Statics
  34213. /**
  34214. * Creates a new Submesh from the passed parameters :
  34215. * - materialIndex (integer) : the index of the main mesh material.
  34216. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34217. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34218. * - mesh (Mesh) : the main mesh to create the submesh from.
  34219. * - renderingMesh (optional Mesh) : rendering mesh.
  34220. */
  34221. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34222. var minVertexIndex = Number.MAX_VALUE;
  34223. var maxVertexIndex = -Number.MAX_VALUE;
  34224. renderingMesh = (renderingMesh || mesh);
  34225. var indices = renderingMesh.getIndices();
  34226. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34227. var vertexIndex = indices[index];
  34228. if (vertexIndex < minVertexIndex)
  34229. minVertexIndex = vertexIndex;
  34230. if (vertexIndex > maxVertexIndex)
  34231. maxVertexIndex = vertexIndex;
  34232. }
  34233. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34234. };
  34235. return SubMesh;
  34236. }(BaseSubMesh));
  34237. BABYLON.SubMesh = SubMesh;
  34238. })(BABYLON || (BABYLON = {}));
  34239. //# sourceMappingURL=babylon.subMesh.js.map
  34240. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34241. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34242. s = arguments[i];
  34243. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34244. t[p] = s[p];
  34245. }
  34246. return t;
  34247. };
  34248. var BABYLON;
  34249. (function (BABYLON) {
  34250. /**
  34251. * Manages the defines for the Material
  34252. */
  34253. var MaterialDefines = /** @class */ (function () {
  34254. function MaterialDefines() {
  34255. this._isDirty = true;
  34256. /** @hidden */
  34257. this._areLightsDirty = true;
  34258. /** @hidden */
  34259. this._areAttributesDirty = true;
  34260. /** @hidden */
  34261. this._areTexturesDirty = true;
  34262. /** @hidden */
  34263. this._areFresnelDirty = true;
  34264. /** @hidden */
  34265. this._areMiscDirty = true;
  34266. /** @hidden */
  34267. this._areImageProcessingDirty = true;
  34268. /** @hidden */
  34269. this._normals = false;
  34270. /** @hidden */
  34271. this._uvs = false;
  34272. /** @hidden */
  34273. this._needNormals = false;
  34274. /** @hidden */
  34275. this._needUVs = false;
  34276. }
  34277. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34278. /**
  34279. * Specifies if the material needs to be re-calculated
  34280. */
  34281. get: function () {
  34282. return this._isDirty;
  34283. },
  34284. enumerable: true,
  34285. configurable: true
  34286. });
  34287. /**
  34288. * Marks the material to indicate that it has been re-calculated
  34289. */
  34290. MaterialDefines.prototype.markAsProcessed = function () {
  34291. this._isDirty = false;
  34292. this._areAttributesDirty = false;
  34293. this._areTexturesDirty = false;
  34294. this._areFresnelDirty = false;
  34295. this._areLightsDirty = false;
  34296. this._areMiscDirty = false;
  34297. this._areImageProcessingDirty = false;
  34298. };
  34299. /**
  34300. * Marks the material to indicate that it needs to be re-calculated
  34301. */
  34302. MaterialDefines.prototype.markAsUnprocessed = function () {
  34303. this._isDirty = true;
  34304. };
  34305. /**
  34306. * Marks the material to indicate all of its defines need to be re-calculated
  34307. */
  34308. MaterialDefines.prototype.markAllAsDirty = function () {
  34309. this._areTexturesDirty = true;
  34310. this._areAttributesDirty = true;
  34311. this._areLightsDirty = true;
  34312. this._areFresnelDirty = true;
  34313. this._areMiscDirty = true;
  34314. this._areImageProcessingDirty = true;
  34315. this._isDirty = true;
  34316. };
  34317. /**
  34318. * Marks the material to indicate that image processing needs to be re-calculated
  34319. */
  34320. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34321. this._areImageProcessingDirty = true;
  34322. this._isDirty = true;
  34323. };
  34324. /**
  34325. * Marks the material to indicate the lights need to be re-calculated
  34326. */
  34327. MaterialDefines.prototype.markAsLightDirty = function () {
  34328. this._areLightsDirty = true;
  34329. this._isDirty = true;
  34330. };
  34331. /**
  34332. * Marks the attribute state as changed
  34333. */
  34334. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34335. this._areAttributesDirty = true;
  34336. this._isDirty = true;
  34337. };
  34338. /**
  34339. * Marks the texture state as changed
  34340. */
  34341. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34342. this._areTexturesDirty = true;
  34343. this._isDirty = true;
  34344. };
  34345. /**
  34346. * Marks the fresnel state as changed
  34347. */
  34348. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34349. this._areFresnelDirty = true;
  34350. this._isDirty = true;
  34351. };
  34352. /**
  34353. * Marks the misc state as changed
  34354. */
  34355. MaterialDefines.prototype.markAsMiscDirty = function () {
  34356. this._areMiscDirty = true;
  34357. this._isDirty = true;
  34358. };
  34359. /**
  34360. * Rebuilds the material defines
  34361. */
  34362. MaterialDefines.prototype.rebuild = function () {
  34363. if (this._keys) {
  34364. delete this._keys;
  34365. }
  34366. this._keys = [];
  34367. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34368. var key = _a[_i];
  34369. if (key[0] === "_") {
  34370. continue;
  34371. }
  34372. this._keys.push(key);
  34373. }
  34374. };
  34375. /**
  34376. * Specifies if two material defines are equal
  34377. * @param other - A material define instance to compare to
  34378. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34379. */
  34380. MaterialDefines.prototype.isEqual = function (other) {
  34381. if (this._keys.length !== other._keys.length) {
  34382. return false;
  34383. }
  34384. for (var index = 0; index < this._keys.length; index++) {
  34385. var prop = this._keys[index];
  34386. if (this[prop] !== other[prop]) {
  34387. return false;
  34388. }
  34389. }
  34390. return true;
  34391. };
  34392. /**
  34393. * Clones this instance's defines to another instance
  34394. * @param other - material defines to clone values to
  34395. */
  34396. MaterialDefines.prototype.cloneTo = function (other) {
  34397. if (this._keys.length !== other._keys.length) {
  34398. other._keys = this._keys.slice(0);
  34399. }
  34400. for (var index = 0; index < this._keys.length; index++) {
  34401. var prop = this._keys[index];
  34402. other[prop] = this[prop];
  34403. }
  34404. };
  34405. /**
  34406. * Resets the material define values
  34407. */
  34408. MaterialDefines.prototype.reset = function () {
  34409. for (var index = 0; index < this._keys.length; index++) {
  34410. var prop = this._keys[index];
  34411. var type = typeof this[prop];
  34412. switch (type) {
  34413. case "number":
  34414. this[prop] = 0;
  34415. break;
  34416. case "string":
  34417. this[prop] = "";
  34418. break;
  34419. default:
  34420. this[prop] = false;
  34421. break;
  34422. }
  34423. }
  34424. };
  34425. /**
  34426. * Converts the material define values to a string
  34427. * @returns - String of material define information
  34428. */
  34429. MaterialDefines.prototype.toString = function () {
  34430. var result = "";
  34431. for (var index = 0; index < this._keys.length; index++) {
  34432. var prop = this._keys[index];
  34433. var value = this[prop];
  34434. var type = typeof value;
  34435. switch (type) {
  34436. case "number":
  34437. case "string":
  34438. result += "#define " + prop + " " + value + "\n";
  34439. break;
  34440. default:
  34441. if (value) {
  34442. result += "#define " + prop + "\n";
  34443. }
  34444. break;
  34445. }
  34446. }
  34447. return result;
  34448. };
  34449. return MaterialDefines;
  34450. }());
  34451. BABYLON.MaterialDefines = MaterialDefines;
  34452. /**
  34453. * Base class for the main features of a material in Babylon.js
  34454. */
  34455. var Material = /** @class */ (function () {
  34456. /**
  34457. * Creates a material instance
  34458. * @param name defines the name of the material
  34459. * @param scene defines the scene to reference
  34460. * @param doNotAdd specifies if the material should be added to the scene
  34461. */
  34462. function Material(name, scene, doNotAdd) {
  34463. /**
  34464. * Specifies if the ready state should be checked on each call
  34465. */
  34466. this.checkReadyOnEveryCall = false;
  34467. /**
  34468. * Specifies if the ready state should be checked once
  34469. */
  34470. this.checkReadyOnlyOnce = false;
  34471. /**
  34472. * The state of the material
  34473. */
  34474. this.state = "";
  34475. /**
  34476. * The alpha value of the material
  34477. */
  34478. this._alpha = 1.0;
  34479. /**
  34480. * Specifies if back face culling is enabled
  34481. */
  34482. this._backFaceCulling = true;
  34483. /**
  34484. * Specifies if the material should be serialized
  34485. */
  34486. this.doNotSerialize = false;
  34487. /**
  34488. * Specifies if the effect should be stored on sub meshes
  34489. */
  34490. this.storeEffectOnSubMeshes = false;
  34491. /**
  34492. * An event triggered when the material is disposed
  34493. */
  34494. this.onDisposeObservable = new BABYLON.Observable();
  34495. /**
  34496. * An event triggered when the material is bound
  34497. */
  34498. this.onBindObservable = new BABYLON.Observable();
  34499. /**
  34500. * An event triggered when the material is unbound
  34501. */
  34502. this.onUnBindObservable = new BABYLON.Observable();
  34503. /**
  34504. * Stores the value of the alpha mode
  34505. */
  34506. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34507. /**
  34508. * Stores the state of the need depth pre-pass value
  34509. */
  34510. this._needDepthPrePass = false;
  34511. /**
  34512. * Specifies if depth writing should be disabled
  34513. */
  34514. this.disableDepthWrite = false;
  34515. /**
  34516. * Specifies if depth writing should be forced
  34517. */
  34518. this.forceDepthWrite = false;
  34519. /**
  34520. * Specifies if there should be a separate pass for culling
  34521. */
  34522. this.separateCullingPass = false;
  34523. /**
  34524. * Stores the state specifing if fog should be enabled
  34525. */
  34526. this._fogEnabled = true;
  34527. /**
  34528. * Stores the size of points
  34529. */
  34530. this.pointSize = 1.0;
  34531. /**
  34532. * Stores the z offset value
  34533. */
  34534. this.zOffset = 0;
  34535. /**
  34536. * Specifies if the material was previously ready
  34537. */
  34538. this._wasPreviouslyReady = false;
  34539. /**
  34540. * Stores the fill mode state
  34541. */
  34542. this._fillMode = Material.TriangleFillMode;
  34543. this.name = name;
  34544. this.id = name || BABYLON.Tools.RandomId();
  34545. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34546. if (this._scene.useRightHandedSystem) {
  34547. this.sideOrientation = Material.ClockWiseSideOrientation;
  34548. }
  34549. else {
  34550. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34551. }
  34552. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34553. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34554. if (!doNotAdd) {
  34555. this._scene.materials.push(this);
  34556. }
  34557. }
  34558. Object.defineProperty(Material, "TriangleFillMode", {
  34559. /**
  34560. * Returns the triangle fill mode
  34561. */
  34562. get: function () {
  34563. return Material._TriangleFillMode;
  34564. },
  34565. enumerable: true,
  34566. configurable: true
  34567. });
  34568. Object.defineProperty(Material, "WireFrameFillMode", {
  34569. /**
  34570. * Returns the wireframe mode
  34571. */
  34572. get: function () {
  34573. return Material._WireFrameFillMode;
  34574. },
  34575. enumerable: true,
  34576. configurable: true
  34577. });
  34578. Object.defineProperty(Material, "PointFillMode", {
  34579. /**
  34580. * Returns the point fill mode
  34581. */
  34582. get: function () {
  34583. return Material._PointFillMode;
  34584. },
  34585. enumerable: true,
  34586. configurable: true
  34587. });
  34588. Object.defineProperty(Material, "PointListDrawMode", {
  34589. /**
  34590. * Returns the point list draw mode
  34591. */
  34592. get: function () {
  34593. return Material._PointListDrawMode;
  34594. },
  34595. enumerable: true,
  34596. configurable: true
  34597. });
  34598. Object.defineProperty(Material, "LineListDrawMode", {
  34599. /**
  34600. * Returns the line list draw mode
  34601. */
  34602. get: function () {
  34603. return Material._LineListDrawMode;
  34604. },
  34605. enumerable: true,
  34606. configurable: true
  34607. });
  34608. Object.defineProperty(Material, "LineLoopDrawMode", {
  34609. /**
  34610. * Returns the line loop draw mode
  34611. */
  34612. get: function () {
  34613. return Material._LineLoopDrawMode;
  34614. },
  34615. enumerable: true,
  34616. configurable: true
  34617. });
  34618. Object.defineProperty(Material, "LineStripDrawMode", {
  34619. /**
  34620. * Returns the line strip draw mode
  34621. */
  34622. get: function () {
  34623. return Material._LineStripDrawMode;
  34624. },
  34625. enumerable: true,
  34626. configurable: true
  34627. });
  34628. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34629. /**
  34630. * Returns the triangle strip draw mode
  34631. */
  34632. get: function () {
  34633. return Material._TriangleStripDrawMode;
  34634. },
  34635. enumerable: true,
  34636. configurable: true
  34637. });
  34638. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34639. /**
  34640. * Returns the triangle fan draw mode
  34641. */
  34642. get: function () {
  34643. return Material._TriangleFanDrawMode;
  34644. },
  34645. enumerable: true,
  34646. configurable: true
  34647. });
  34648. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34649. /**
  34650. * Returns the clock-wise side orientation
  34651. */
  34652. get: function () {
  34653. return Material._ClockWiseSideOrientation;
  34654. },
  34655. enumerable: true,
  34656. configurable: true
  34657. });
  34658. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34659. /**
  34660. * Returns the counter clock-wise side orientation
  34661. */
  34662. get: function () {
  34663. return Material._CounterClockWiseSideOrientation;
  34664. },
  34665. enumerable: true,
  34666. configurable: true
  34667. });
  34668. Object.defineProperty(Material, "TextureDirtyFlag", {
  34669. /**
  34670. * Returns the dirty texture flag value
  34671. */
  34672. get: function () {
  34673. return Material._TextureDirtyFlag;
  34674. },
  34675. enumerable: true,
  34676. configurable: true
  34677. });
  34678. Object.defineProperty(Material, "LightDirtyFlag", {
  34679. /**
  34680. * Returns the dirty light flag value
  34681. */
  34682. get: function () {
  34683. return Material._LightDirtyFlag;
  34684. },
  34685. enumerable: true,
  34686. configurable: true
  34687. });
  34688. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34689. /**
  34690. * Returns the dirty fresnel flag value
  34691. */
  34692. get: function () {
  34693. return Material._FresnelDirtyFlag;
  34694. },
  34695. enumerable: true,
  34696. configurable: true
  34697. });
  34698. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34699. /**
  34700. * Returns the dirty attributes flag value
  34701. */
  34702. get: function () {
  34703. return Material._AttributesDirtyFlag;
  34704. },
  34705. enumerable: true,
  34706. configurable: true
  34707. });
  34708. Object.defineProperty(Material, "MiscDirtyFlag", {
  34709. /**
  34710. * Returns the dirty misc flag value
  34711. */
  34712. get: function () {
  34713. return Material._MiscDirtyFlag;
  34714. },
  34715. enumerable: true,
  34716. configurable: true
  34717. });
  34718. Object.defineProperty(Material.prototype, "alpha", {
  34719. /**
  34720. * Gets the alpha value of the material
  34721. */
  34722. get: function () {
  34723. return this._alpha;
  34724. },
  34725. /**
  34726. * Sets the alpha value of the material
  34727. */
  34728. set: function (value) {
  34729. if (this._alpha === value) {
  34730. return;
  34731. }
  34732. this._alpha = value;
  34733. this.markAsDirty(Material.MiscDirtyFlag);
  34734. },
  34735. enumerable: true,
  34736. configurable: true
  34737. });
  34738. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34739. /**
  34740. * Gets the back-face culling state
  34741. */
  34742. get: function () {
  34743. return this._backFaceCulling;
  34744. },
  34745. /**
  34746. * Sets the back-face culling state
  34747. */
  34748. set: function (value) {
  34749. if (this._backFaceCulling === value) {
  34750. return;
  34751. }
  34752. this._backFaceCulling = value;
  34753. this.markAsDirty(Material.TextureDirtyFlag);
  34754. },
  34755. enumerable: true,
  34756. configurable: true
  34757. });
  34758. Object.defineProperty(Material.prototype, "onDispose", {
  34759. /**
  34760. * Called during a dispose event
  34761. */
  34762. set: function (callback) {
  34763. if (this._onDisposeObserver) {
  34764. this.onDisposeObservable.remove(this._onDisposeObserver);
  34765. }
  34766. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34767. },
  34768. enumerable: true,
  34769. configurable: true
  34770. });
  34771. Object.defineProperty(Material.prototype, "onBind", {
  34772. /**
  34773. * Called during a bind event
  34774. */
  34775. set: function (callback) {
  34776. if (this._onBindObserver) {
  34777. this.onBindObservable.remove(this._onBindObserver);
  34778. }
  34779. this._onBindObserver = this.onBindObservable.add(callback);
  34780. },
  34781. enumerable: true,
  34782. configurable: true
  34783. });
  34784. Object.defineProperty(Material.prototype, "alphaMode", {
  34785. /**
  34786. * Gets the value of the alpha mode
  34787. */
  34788. get: function () {
  34789. return this._alphaMode;
  34790. },
  34791. /**
  34792. * Sets the value of the alpha mode.
  34793. *
  34794. * | Value | Type | Description |
  34795. * | --- | --- | --- |
  34796. * | 0 | ALPHA_DISABLE | |
  34797. * | 1 | ALPHA_ADD | |
  34798. * | 2 | ALPHA_COMBINE | |
  34799. * | 3 | ALPHA_SUBTRACT | |
  34800. * | 4 | ALPHA_MULTIPLY | |
  34801. * | 5 | ALPHA_MAXIMIZED | |
  34802. * | 6 | ALPHA_ONEONE | |
  34803. * | 7 | ALPHA_PREMULTIPLIED | |
  34804. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34805. * | 9 | ALPHA_INTERPOLATE | |
  34806. * | 10 | ALPHA_SCREENMODE | |
  34807. *
  34808. */
  34809. set: function (value) {
  34810. if (this._alphaMode === value) {
  34811. return;
  34812. }
  34813. this._alphaMode = value;
  34814. this.markAsDirty(Material.TextureDirtyFlag);
  34815. },
  34816. enumerable: true,
  34817. configurable: true
  34818. });
  34819. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34820. /**
  34821. * Gets the depth pre-pass value
  34822. */
  34823. get: function () {
  34824. return this._needDepthPrePass;
  34825. },
  34826. /**
  34827. * Sets the need depth pre-pass value
  34828. */
  34829. set: function (value) {
  34830. if (this._needDepthPrePass === value) {
  34831. return;
  34832. }
  34833. this._needDepthPrePass = value;
  34834. if (this._needDepthPrePass) {
  34835. this.checkReadyOnEveryCall = true;
  34836. }
  34837. },
  34838. enumerable: true,
  34839. configurable: true
  34840. });
  34841. Object.defineProperty(Material.prototype, "fogEnabled", {
  34842. /**
  34843. * Gets the value of the fog enabled state
  34844. */
  34845. get: function () {
  34846. return this._fogEnabled;
  34847. },
  34848. /**
  34849. * Sets the state for enabling fog
  34850. */
  34851. set: function (value) {
  34852. if (this._fogEnabled === value) {
  34853. return;
  34854. }
  34855. this._fogEnabled = value;
  34856. this.markAsDirty(Material.MiscDirtyFlag);
  34857. },
  34858. enumerable: true,
  34859. configurable: true
  34860. });
  34861. Object.defineProperty(Material.prototype, "wireframe", {
  34862. /**
  34863. * Gets a value specifying if wireframe mode is enabled
  34864. */
  34865. get: function () {
  34866. switch (this._fillMode) {
  34867. case Material.WireFrameFillMode:
  34868. case Material.LineListDrawMode:
  34869. case Material.LineLoopDrawMode:
  34870. case Material.LineStripDrawMode:
  34871. return true;
  34872. }
  34873. return this._scene.forceWireframe;
  34874. },
  34875. /**
  34876. * Sets the state of wireframe mode
  34877. */
  34878. set: function (value) {
  34879. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34880. },
  34881. enumerable: true,
  34882. configurable: true
  34883. });
  34884. Object.defineProperty(Material.prototype, "pointsCloud", {
  34885. /**
  34886. * Gets the value specifying if point clouds are enabled
  34887. */
  34888. get: function () {
  34889. switch (this._fillMode) {
  34890. case Material.PointFillMode:
  34891. case Material.PointListDrawMode:
  34892. return true;
  34893. }
  34894. return this._scene.forcePointsCloud;
  34895. },
  34896. /**
  34897. * Sets the state of point cloud mode
  34898. */
  34899. set: function (value) {
  34900. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34901. },
  34902. enumerable: true,
  34903. configurable: true
  34904. });
  34905. Object.defineProperty(Material.prototype, "fillMode", {
  34906. /**
  34907. * Gets the material fill mode
  34908. */
  34909. get: function () {
  34910. return this._fillMode;
  34911. },
  34912. /**
  34913. * Sets the material fill mode
  34914. */
  34915. set: function (value) {
  34916. if (this._fillMode === value) {
  34917. return;
  34918. }
  34919. this._fillMode = value;
  34920. this.markAsDirty(Material.MiscDirtyFlag);
  34921. },
  34922. enumerable: true,
  34923. configurable: true
  34924. });
  34925. /**
  34926. * Returns a string representation of the current material
  34927. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34928. * @returns a string with material information
  34929. */
  34930. Material.prototype.toString = function (fullDetails) {
  34931. var ret = "Name: " + this.name;
  34932. if (fullDetails) {
  34933. }
  34934. return ret;
  34935. };
  34936. /**
  34937. * Gets the class name of the material
  34938. * @returns a string with the class name of the material
  34939. */
  34940. Material.prototype.getClassName = function () {
  34941. return "Material";
  34942. };
  34943. Object.defineProperty(Material.prototype, "isFrozen", {
  34944. /**
  34945. * Specifies if updates for the material been locked
  34946. */
  34947. get: function () {
  34948. return this.checkReadyOnlyOnce;
  34949. },
  34950. enumerable: true,
  34951. configurable: true
  34952. });
  34953. /**
  34954. * Locks updates for the material
  34955. */
  34956. Material.prototype.freeze = function () {
  34957. this.checkReadyOnlyOnce = true;
  34958. };
  34959. /**
  34960. * Unlocks updates for the material
  34961. */
  34962. Material.prototype.unfreeze = function () {
  34963. this.checkReadyOnlyOnce = false;
  34964. };
  34965. /**
  34966. * Specifies if the material is ready to be used
  34967. * @param mesh defines the mesh to check
  34968. * @param useInstances specifies if instances should be used
  34969. * @returns a boolean indicating if the material is ready to be used
  34970. */
  34971. Material.prototype.isReady = function (mesh, useInstances) {
  34972. return true;
  34973. };
  34974. /**
  34975. * Specifies that the submesh is ready to be used
  34976. * @param mesh defines the mesh to check
  34977. * @param subMesh defines which submesh to check
  34978. * @param useInstances specifies that instances should be used
  34979. * @returns a boolean indicating that the submesh is ready or not
  34980. */
  34981. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34982. return false;
  34983. };
  34984. /**
  34985. * Returns the material effect
  34986. * @returns the effect associated with the material
  34987. */
  34988. Material.prototype.getEffect = function () {
  34989. return this._effect;
  34990. };
  34991. /**
  34992. * Returns the current scene
  34993. * @returns a Scene
  34994. */
  34995. Material.prototype.getScene = function () {
  34996. return this._scene;
  34997. };
  34998. /**
  34999. * Specifies if the material will require alpha blending
  35000. * @returns a boolean specifying if alpha blending is needed
  35001. */
  35002. Material.prototype.needAlphaBlending = function () {
  35003. return (this.alpha < 1.0);
  35004. };
  35005. /**
  35006. * Specifies if the mesh will require alpha blending
  35007. * @param mesh defines the mesh to check
  35008. * @returns a boolean specifying if alpha blending is needed for the mesh
  35009. */
  35010. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35011. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35012. };
  35013. /**
  35014. * Specifies if this material should be rendered in alpha test mode
  35015. * @returns a boolean specifying if an alpha test is needed.
  35016. */
  35017. Material.prototype.needAlphaTesting = function () {
  35018. return false;
  35019. };
  35020. /**
  35021. * Gets the texture used for the alpha test
  35022. * @returns the texture to use for alpha testing
  35023. */
  35024. Material.prototype.getAlphaTestTexture = function () {
  35025. return null;
  35026. };
  35027. /**
  35028. * Marks the material to indicate that it needs to be re-calculated
  35029. */
  35030. Material.prototype.markDirty = function () {
  35031. this._wasPreviouslyReady = false;
  35032. };
  35033. /** @hidden */
  35034. Material.prototype._preBind = function (effect, overrideOrientation) {
  35035. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35036. var engine = this._scene.getEngine();
  35037. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35038. var reverse = orientation === Material.ClockWiseSideOrientation;
  35039. engine.enableEffect(effect ? effect : this._effect);
  35040. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35041. return reverse;
  35042. };
  35043. /**
  35044. * Binds the material to the mesh
  35045. * @param world defines the world transformation matrix
  35046. * @param mesh defines the mesh to bind the material to
  35047. */
  35048. Material.prototype.bind = function (world, mesh) {
  35049. };
  35050. /**
  35051. * Binds the submesh to the material
  35052. * @param world defines the world transformation matrix
  35053. * @param mesh defines the mesh containing the submesh
  35054. * @param subMesh defines the submesh to bind the material to
  35055. */
  35056. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35057. };
  35058. /**
  35059. * Binds the world matrix to the material
  35060. * @param world defines the world transformation matrix
  35061. */
  35062. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35063. };
  35064. /**
  35065. * Binds the scene's uniform buffer to the effect.
  35066. * @param effect defines the effect to bind to the scene uniform buffer
  35067. * @param sceneUbo defines the uniform buffer storing scene data
  35068. */
  35069. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35070. sceneUbo.bindToEffect(effect, "Scene");
  35071. };
  35072. /**
  35073. * Binds the view matrix to the effect
  35074. * @param effect defines the effect to bind the view matrix to
  35075. */
  35076. Material.prototype.bindView = function (effect) {
  35077. if (!this._useUBO) {
  35078. effect.setMatrix("view", this.getScene().getViewMatrix());
  35079. }
  35080. else {
  35081. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35082. }
  35083. };
  35084. /**
  35085. * Binds the view projection matrix to the effect
  35086. * @param effect defines the effect to bind the view projection matrix to
  35087. */
  35088. Material.prototype.bindViewProjection = function (effect) {
  35089. if (!this._useUBO) {
  35090. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35091. }
  35092. else {
  35093. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35094. }
  35095. };
  35096. /**
  35097. * Specifies if material alpha testing should be turned on for the mesh
  35098. * @param mesh defines the mesh to check
  35099. */
  35100. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35101. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35102. };
  35103. /**
  35104. * Processes to execute after binding the material to a mesh
  35105. * @param mesh defines the rendered mesh
  35106. */
  35107. Material.prototype._afterBind = function (mesh) {
  35108. this._scene._cachedMaterial = this;
  35109. if (mesh) {
  35110. this._scene._cachedVisibility = mesh.visibility;
  35111. }
  35112. else {
  35113. this._scene._cachedVisibility = 1;
  35114. }
  35115. if (mesh) {
  35116. this.onBindObservable.notifyObservers(mesh);
  35117. }
  35118. if (this.disableDepthWrite) {
  35119. var engine = this._scene.getEngine();
  35120. this._cachedDepthWriteState = engine.getDepthWrite();
  35121. engine.setDepthWrite(false);
  35122. }
  35123. };
  35124. /**
  35125. * Unbinds the material from the mesh
  35126. */
  35127. Material.prototype.unbind = function () {
  35128. this.onUnBindObservable.notifyObservers(this);
  35129. if (this.disableDepthWrite) {
  35130. var engine = this._scene.getEngine();
  35131. engine.setDepthWrite(this._cachedDepthWriteState);
  35132. }
  35133. };
  35134. /**
  35135. * Gets the active textures from the material
  35136. * @returns an array of textures
  35137. */
  35138. Material.prototype.getActiveTextures = function () {
  35139. return [];
  35140. };
  35141. /**
  35142. * Specifies if the material uses a texture
  35143. * @param texture defines the texture to check against the material
  35144. * @returns a boolean specifying if the material uses the texture
  35145. */
  35146. Material.prototype.hasTexture = function (texture) {
  35147. return false;
  35148. };
  35149. /**
  35150. * Makes a duplicate of the material, and gives it a new name
  35151. * @param name defines the new name for the duplicated material
  35152. * @returns the cloned material
  35153. */
  35154. Material.prototype.clone = function (name) {
  35155. return null;
  35156. };
  35157. /**
  35158. * Gets the meshes bound to the material
  35159. * @returns an array of meshes bound to the material
  35160. */
  35161. Material.prototype.getBindedMeshes = function () {
  35162. var result = new Array();
  35163. for (var index = 0; index < this._scene.meshes.length; index++) {
  35164. var mesh = this._scene.meshes[index];
  35165. if (mesh.material === this) {
  35166. result.push(mesh);
  35167. }
  35168. }
  35169. return result;
  35170. };
  35171. /**
  35172. * Force shader compilation
  35173. * @param mesh defines the mesh associated with this material
  35174. * @param onCompiled defines a function to execute once the material is compiled
  35175. * @param options defines the options to configure the compilation
  35176. */
  35177. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35178. var _this = this;
  35179. var localOptions = __assign({ clipPlane: false }, options);
  35180. var subMesh = new BABYLON.BaseSubMesh();
  35181. var scene = this.getScene();
  35182. var checkReady = function () {
  35183. if (!_this._scene || !_this._scene.getEngine()) {
  35184. return;
  35185. }
  35186. if (subMesh._materialDefines) {
  35187. subMesh._materialDefines._renderId = -1;
  35188. }
  35189. var clipPlaneState = scene.clipPlane;
  35190. if (localOptions.clipPlane) {
  35191. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35192. }
  35193. if (_this.storeEffectOnSubMeshes) {
  35194. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35195. if (onCompiled) {
  35196. onCompiled(_this);
  35197. }
  35198. }
  35199. else {
  35200. setTimeout(checkReady, 16);
  35201. }
  35202. }
  35203. else {
  35204. if (_this.isReady(mesh)) {
  35205. if (onCompiled) {
  35206. onCompiled(_this);
  35207. }
  35208. }
  35209. else {
  35210. setTimeout(checkReady, 16);
  35211. }
  35212. }
  35213. if (localOptions.clipPlane) {
  35214. scene.clipPlane = clipPlaneState;
  35215. }
  35216. };
  35217. checkReady();
  35218. };
  35219. /**
  35220. * Force shader compilation
  35221. * @param mesh defines the mesh that will use this material
  35222. * @param options defines additional options for compiling the shaders
  35223. * @returns a promise that resolves when the compilation completes
  35224. */
  35225. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35226. var _this = this;
  35227. return new Promise(function (resolve) {
  35228. _this.forceCompilation(mesh, function () {
  35229. resolve();
  35230. }, options);
  35231. });
  35232. };
  35233. /**
  35234. * Marks a define in the material to indicate that it needs to be re-computed
  35235. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35236. */
  35237. Material.prototype.markAsDirty = function (flag) {
  35238. if (flag & Material.TextureDirtyFlag) {
  35239. this._markAllSubMeshesAsTexturesDirty();
  35240. }
  35241. if (flag & Material.LightDirtyFlag) {
  35242. this._markAllSubMeshesAsLightsDirty();
  35243. }
  35244. if (flag & Material.FresnelDirtyFlag) {
  35245. this._markAllSubMeshesAsFresnelDirty();
  35246. }
  35247. if (flag & Material.AttributesDirtyFlag) {
  35248. this._markAllSubMeshesAsAttributesDirty();
  35249. }
  35250. if (flag & Material.MiscDirtyFlag) {
  35251. this._markAllSubMeshesAsMiscDirty();
  35252. }
  35253. this.getScene().resetCachedMaterial();
  35254. };
  35255. /**
  35256. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35257. * @param func defines a function which checks material defines against the submeshes
  35258. */
  35259. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35260. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35261. var mesh = _a[_i];
  35262. if (!mesh.subMeshes) {
  35263. continue;
  35264. }
  35265. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35266. var subMesh = _c[_b];
  35267. if (subMesh.getMaterial() !== this) {
  35268. continue;
  35269. }
  35270. if (!subMesh._materialDefines) {
  35271. continue;
  35272. }
  35273. func(subMesh._materialDefines);
  35274. }
  35275. }
  35276. };
  35277. /**
  35278. * Indicates that image processing needs to be re-calculated for all submeshes
  35279. */
  35280. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35281. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35282. };
  35283. /**
  35284. * Indicates that textures need to be re-calculated for all submeshes
  35285. */
  35286. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35287. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35288. };
  35289. /**
  35290. * Indicates that fresnel needs to be re-calculated for all submeshes
  35291. */
  35292. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35293. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35294. };
  35295. /**
  35296. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35297. */
  35298. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35299. this._markAllSubMeshesAsDirty(function (defines) {
  35300. defines.markAsFresnelDirty();
  35301. defines.markAsMiscDirty();
  35302. });
  35303. };
  35304. /**
  35305. * Indicates that lights need to be re-calculated for all submeshes
  35306. */
  35307. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35308. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35309. };
  35310. /**
  35311. * Indicates that attributes need to be re-calculated for all submeshes
  35312. */
  35313. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35314. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35315. };
  35316. /**
  35317. * Indicates that misc needs to be re-calculated for all submeshes
  35318. */
  35319. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35320. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35321. };
  35322. /**
  35323. * Indicates that textures and misc need to be re-calculated for all submeshes
  35324. */
  35325. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35326. this._markAllSubMeshesAsDirty(function (defines) {
  35327. defines.markAsTexturesDirty();
  35328. defines.markAsMiscDirty();
  35329. });
  35330. };
  35331. /**
  35332. * Disposes the material
  35333. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35334. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35335. */
  35336. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35337. // Animations
  35338. this.getScene().stopAnimation(this);
  35339. this.getScene().freeProcessedMaterials();
  35340. // Remove from scene
  35341. var index = this._scene.materials.indexOf(this);
  35342. if (index >= 0) {
  35343. this._scene.materials.splice(index, 1);
  35344. }
  35345. // Remove from meshes
  35346. for (index = 0; index < this._scene.meshes.length; index++) {
  35347. var mesh = this._scene.meshes[index];
  35348. if (mesh.material === this) {
  35349. mesh.material = null;
  35350. if (mesh.geometry) {
  35351. var geometry = (mesh.geometry);
  35352. if (this.storeEffectOnSubMeshes) {
  35353. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35354. var subMesh = _a[_i];
  35355. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35356. if (forceDisposeEffect && subMesh._materialEffect) {
  35357. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35358. }
  35359. }
  35360. }
  35361. else {
  35362. geometry._releaseVertexArrayObject(this._effect);
  35363. }
  35364. }
  35365. }
  35366. }
  35367. this._uniformBuffer.dispose();
  35368. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35369. if (forceDisposeEffect && this._effect) {
  35370. if (!this.storeEffectOnSubMeshes) {
  35371. this._scene.getEngine()._releaseEffect(this._effect);
  35372. }
  35373. this._effect = null;
  35374. }
  35375. // Callback
  35376. this.onDisposeObservable.notifyObservers(this);
  35377. this.onDisposeObservable.clear();
  35378. this.onBindObservable.clear();
  35379. this.onUnBindObservable.clear();
  35380. };
  35381. /**
  35382. * Serializes this material
  35383. * @returns the serialized material object
  35384. */
  35385. Material.prototype.serialize = function () {
  35386. return BABYLON.SerializationHelper.Serialize(this);
  35387. };
  35388. /**
  35389. * Creates a MultiMaterial from parsed MultiMaterial data.
  35390. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35391. * @param scene defines the hosting scene
  35392. * @returns a new MultiMaterial
  35393. */
  35394. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35395. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35396. multiMaterial.id = parsedMultiMaterial.id;
  35397. if (BABYLON.Tags) {
  35398. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35399. }
  35400. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35401. var subMatId = parsedMultiMaterial.materials[matIndex];
  35402. if (subMatId) {
  35403. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35404. }
  35405. else {
  35406. multiMaterial.subMaterials.push(null);
  35407. }
  35408. }
  35409. return multiMaterial;
  35410. };
  35411. /**
  35412. * Creates a material from parsed material data
  35413. * @param parsedMaterial defines parsed material data
  35414. * @param scene defines the hosting scene
  35415. * @param rootUrl defines the root URL to use to load textures
  35416. * @returns a new material
  35417. */
  35418. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35419. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35420. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35421. }
  35422. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35423. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35424. if (!BABYLON.LegacyPBRMaterial) {
  35425. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35426. return;
  35427. }
  35428. }
  35429. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35430. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35431. ;
  35432. };
  35433. // Triangle views
  35434. Material._TriangleFillMode = 0;
  35435. Material._WireFrameFillMode = 1;
  35436. Material._PointFillMode = 2;
  35437. // Draw modes
  35438. Material._PointListDrawMode = 3;
  35439. Material._LineListDrawMode = 4;
  35440. Material._LineLoopDrawMode = 5;
  35441. Material._LineStripDrawMode = 6;
  35442. Material._TriangleStripDrawMode = 7;
  35443. Material._TriangleFanDrawMode = 8;
  35444. /**
  35445. * Stores the clock-wise side orientation
  35446. */
  35447. Material._ClockWiseSideOrientation = 0;
  35448. /**
  35449. * Stores the counter clock-wise side orientation
  35450. */
  35451. Material._CounterClockWiseSideOrientation = 1;
  35452. /**
  35453. * The dirty texture flag value
  35454. */
  35455. Material._TextureDirtyFlag = 1;
  35456. /**
  35457. * The dirty light flag value
  35458. */
  35459. Material._LightDirtyFlag = 2;
  35460. /**
  35461. * The dirty fresnel flag value
  35462. */
  35463. Material._FresnelDirtyFlag = 4;
  35464. /**
  35465. * The dirty attribute flag value
  35466. */
  35467. Material._AttributesDirtyFlag = 8;
  35468. /**
  35469. * The dirty misc flag value
  35470. */
  35471. Material._MiscDirtyFlag = 16;
  35472. __decorate([
  35473. BABYLON.serialize()
  35474. ], Material.prototype, "id", void 0);
  35475. __decorate([
  35476. BABYLON.serialize()
  35477. ], Material.prototype, "name", void 0);
  35478. __decorate([
  35479. BABYLON.serialize()
  35480. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35481. __decorate([
  35482. BABYLON.serialize()
  35483. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35484. __decorate([
  35485. BABYLON.serialize()
  35486. ], Material.prototype, "state", void 0);
  35487. __decorate([
  35488. BABYLON.serialize("alpha")
  35489. ], Material.prototype, "_alpha", void 0);
  35490. __decorate([
  35491. BABYLON.serialize("backFaceCulling")
  35492. ], Material.prototype, "_backFaceCulling", void 0);
  35493. __decorate([
  35494. BABYLON.serialize()
  35495. ], Material.prototype, "sideOrientation", void 0);
  35496. __decorate([
  35497. BABYLON.serialize("alphaMode")
  35498. ], Material.prototype, "_alphaMode", void 0);
  35499. __decorate([
  35500. BABYLON.serialize()
  35501. ], Material.prototype, "_needDepthPrePass", void 0);
  35502. __decorate([
  35503. BABYLON.serialize()
  35504. ], Material.prototype, "disableDepthWrite", void 0);
  35505. __decorate([
  35506. BABYLON.serialize()
  35507. ], Material.prototype, "forceDepthWrite", void 0);
  35508. __decorate([
  35509. BABYLON.serialize()
  35510. ], Material.prototype, "separateCullingPass", void 0);
  35511. __decorate([
  35512. BABYLON.serialize("fogEnabled")
  35513. ], Material.prototype, "_fogEnabled", void 0);
  35514. __decorate([
  35515. BABYLON.serialize()
  35516. ], Material.prototype, "pointSize", void 0);
  35517. __decorate([
  35518. BABYLON.serialize()
  35519. ], Material.prototype, "zOffset", void 0);
  35520. __decorate([
  35521. BABYLON.serialize()
  35522. ], Material.prototype, "wireframe", null);
  35523. __decorate([
  35524. BABYLON.serialize()
  35525. ], Material.prototype, "pointsCloud", null);
  35526. __decorate([
  35527. BABYLON.serialize()
  35528. ], Material.prototype, "fillMode", null);
  35529. return Material;
  35530. }());
  35531. BABYLON.Material = Material;
  35532. })(BABYLON || (BABYLON = {}));
  35533. //# sourceMappingURL=babylon.material.js.map
  35534. var BABYLON;
  35535. (function (BABYLON) {
  35536. var UniformBuffer = /** @class */ (function () {
  35537. /**
  35538. * Uniform buffer objects.
  35539. *
  35540. * Handles blocks of uniform on the GPU.
  35541. *
  35542. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35543. *
  35544. * For more information, please refer to :
  35545. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35546. */
  35547. function UniformBuffer(engine, data, dynamic) {
  35548. this._engine = engine;
  35549. this._noUBO = !engine.supportsUniformBuffers;
  35550. this._dynamic = dynamic;
  35551. this._data = data || [];
  35552. this._uniformLocations = {};
  35553. this._uniformSizes = {};
  35554. this._uniformLocationPointer = 0;
  35555. this._needSync = false;
  35556. if (this._noUBO) {
  35557. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35558. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35559. this.updateFloat = this._updateFloatForEffect;
  35560. this.updateFloat2 = this._updateFloat2ForEffect;
  35561. this.updateFloat3 = this._updateFloat3ForEffect;
  35562. this.updateFloat4 = this._updateFloat4ForEffect;
  35563. this.updateMatrix = this._updateMatrixForEffect;
  35564. this.updateVector3 = this._updateVector3ForEffect;
  35565. this.updateVector4 = this._updateVector4ForEffect;
  35566. this.updateColor3 = this._updateColor3ForEffect;
  35567. this.updateColor4 = this._updateColor4ForEffect;
  35568. }
  35569. else {
  35570. this._engine._uniformBuffers.push(this);
  35571. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35572. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35573. this.updateFloat = this._updateFloatForUniform;
  35574. this.updateFloat2 = this._updateFloat2ForUniform;
  35575. this.updateFloat3 = this._updateFloat3ForUniform;
  35576. this.updateFloat4 = this._updateFloat4ForUniform;
  35577. this.updateMatrix = this._updateMatrixForUniform;
  35578. this.updateVector3 = this._updateVector3ForUniform;
  35579. this.updateVector4 = this._updateVector4ForUniform;
  35580. this.updateColor3 = this._updateColor3ForUniform;
  35581. this.updateColor4 = this._updateColor4ForUniform;
  35582. }
  35583. }
  35584. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35585. // Properties
  35586. /**
  35587. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35588. * or just falling back on setUniformXXX calls.
  35589. */
  35590. get: function () {
  35591. return !this._noUBO;
  35592. },
  35593. enumerable: true,
  35594. configurable: true
  35595. });
  35596. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35597. /**
  35598. * Indicates if the WebGL underlying uniform buffer is in sync
  35599. * with the javascript cache data.
  35600. */
  35601. get: function () {
  35602. return !this._needSync;
  35603. },
  35604. enumerable: true,
  35605. configurable: true
  35606. });
  35607. /**
  35608. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35609. * Also, a dynamic UniformBuffer will disable cache verification and always
  35610. * update the underlying WebGL uniform buffer to the GPU.
  35611. */
  35612. UniformBuffer.prototype.isDynamic = function () {
  35613. return this._dynamic !== undefined;
  35614. };
  35615. /**
  35616. * The data cache on JS side.
  35617. */
  35618. UniformBuffer.prototype.getData = function () {
  35619. return this._bufferData;
  35620. };
  35621. /**
  35622. * The underlying WebGL Uniform buffer.
  35623. */
  35624. UniformBuffer.prototype.getBuffer = function () {
  35625. return this._buffer;
  35626. };
  35627. /**
  35628. * std140 layout specifies how to align data within an UBO structure.
  35629. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35630. * for specs.
  35631. */
  35632. UniformBuffer.prototype._fillAlignment = function (size) {
  35633. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35634. // and 4x4 matrices
  35635. // TODO : change if other types are used
  35636. var alignment;
  35637. if (size <= 2) {
  35638. alignment = size;
  35639. }
  35640. else {
  35641. alignment = 4;
  35642. }
  35643. if ((this._uniformLocationPointer % alignment) !== 0) {
  35644. var oldPointer = this._uniformLocationPointer;
  35645. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35646. var diff = this._uniformLocationPointer - oldPointer;
  35647. for (var i = 0; i < diff; i++) {
  35648. this._data.push(0);
  35649. }
  35650. }
  35651. };
  35652. /**
  35653. * Adds an uniform in the buffer.
  35654. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35655. * for the layout to be correct !
  35656. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35657. * @param {number|number[]} size Data size, or data directly.
  35658. */
  35659. UniformBuffer.prototype.addUniform = function (name, size) {
  35660. if (this._noUBO) {
  35661. return;
  35662. }
  35663. if (this._uniformLocations[name] !== undefined) {
  35664. // Already existing uniform
  35665. return;
  35666. }
  35667. // This function must be called in the order of the shader layout !
  35668. // size can be the size of the uniform, or data directly
  35669. var data;
  35670. if (size instanceof Array) {
  35671. data = size;
  35672. size = data.length;
  35673. }
  35674. else {
  35675. size = size;
  35676. data = [];
  35677. // Fill with zeros
  35678. for (var i = 0; i < size; i++) {
  35679. data.push(0);
  35680. }
  35681. }
  35682. this._fillAlignment(size);
  35683. this._uniformSizes[name] = size;
  35684. this._uniformLocations[name] = this._uniformLocationPointer;
  35685. this._uniformLocationPointer += size;
  35686. for (var i = 0; i < size; i++) {
  35687. this._data.push(data[i]);
  35688. }
  35689. this._needSync = true;
  35690. };
  35691. /**
  35692. * Wrapper for addUniform.
  35693. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35694. * @param {Matrix} mat A 4x4 matrix.
  35695. */
  35696. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35697. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35698. };
  35699. /**
  35700. * Wrapper for addUniform.
  35701. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35702. * @param {number} x
  35703. * @param {number} y
  35704. */
  35705. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35706. var temp = [x, y];
  35707. this.addUniform(name, temp);
  35708. };
  35709. /**
  35710. * Wrapper for addUniform.
  35711. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35712. * @param {number} x
  35713. * @param {number} y
  35714. * @param {number} z
  35715. */
  35716. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35717. var temp = [x, y, z];
  35718. this.addUniform(name, temp);
  35719. };
  35720. /**
  35721. * Wrapper for addUniform.
  35722. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35723. * @param {Color3} color
  35724. */
  35725. UniformBuffer.prototype.addColor3 = function (name, color) {
  35726. var temp = new Array();
  35727. color.toArray(temp);
  35728. this.addUniform(name, temp);
  35729. };
  35730. /**
  35731. * Wrapper for addUniform.
  35732. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35733. * @param {Color3} color
  35734. * @param {number} alpha
  35735. */
  35736. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35737. var temp = new Array();
  35738. color.toArray(temp);
  35739. temp.push(alpha);
  35740. this.addUniform(name, temp);
  35741. };
  35742. /**
  35743. * Wrapper for addUniform.
  35744. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35745. * @param {Vector3} vector
  35746. */
  35747. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35748. var temp = new Array();
  35749. vector.toArray(temp);
  35750. this.addUniform(name, temp);
  35751. };
  35752. /**
  35753. * Wrapper for addUniform.
  35754. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35755. */
  35756. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35757. this.addUniform(name, 12);
  35758. };
  35759. /**
  35760. * Wrapper for addUniform.
  35761. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35762. */
  35763. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35764. this.addUniform(name, 8);
  35765. };
  35766. /**
  35767. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35768. */
  35769. UniformBuffer.prototype.create = function () {
  35770. if (this._noUBO) {
  35771. return;
  35772. }
  35773. if (this._buffer) {
  35774. return; // nothing to do
  35775. }
  35776. // See spec, alignment must be filled as a vec4
  35777. this._fillAlignment(4);
  35778. this._bufferData = new Float32Array(this._data);
  35779. this._rebuild();
  35780. this._needSync = true;
  35781. };
  35782. UniformBuffer.prototype._rebuild = function () {
  35783. if (this._noUBO) {
  35784. return;
  35785. }
  35786. if (this._dynamic) {
  35787. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35788. }
  35789. else {
  35790. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35791. }
  35792. };
  35793. /**
  35794. * Updates the WebGL Uniform Buffer on the GPU.
  35795. * If the `dynamic` flag is set to true, no cache comparison is done.
  35796. * Otherwise, the buffer will be updated only if the cache differs.
  35797. */
  35798. UniformBuffer.prototype.update = function () {
  35799. if (!this._buffer) {
  35800. this.create();
  35801. return;
  35802. }
  35803. if (!this._dynamic && !this._needSync) {
  35804. return;
  35805. }
  35806. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35807. this._needSync = false;
  35808. };
  35809. /**
  35810. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35811. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35812. * @param {number[]|Float32Array} data Flattened data
  35813. * @param {number} size Size of the data.
  35814. */
  35815. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35816. var location = this._uniformLocations[uniformName];
  35817. if (location === undefined) {
  35818. if (this._buffer) {
  35819. // Cannot add an uniform if the buffer is already created
  35820. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35821. return;
  35822. }
  35823. this.addUniform(uniformName, size);
  35824. location = this._uniformLocations[uniformName];
  35825. }
  35826. if (!this._buffer) {
  35827. this.create();
  35828. }
  35829. if (!this._dynamic) {
  35830. // Cache for static uniform buffers
  35831. var changed = false;
  35832. for (var i = 0; i < size; i++) {
  35833. if (this._bufferData[location + i] !== data[i]) {
  35834. changed = true;
  35835. this._bufferData[location + i] = data[i];
  35836. }
  35837. }
  35838. this._needSync = this._needSync || changed;
  35839. }
  35840. else {
  35841. // No cache for dynamic
  35842. for (var i = 0; i < size; i++) {
  35843. this._bufferData[location + i] = data[i];
  35844. }
  35845. }
  35846. };
  35847. // Update methods
  35848. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35849. // To match std140, matrix must be realigned
  35850. for (var i = 0; i < 3; i++) {
  35851. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35852. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35853. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35854. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35855. }
  35856. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35857. };
  35858. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35859. this._currentEffect.setMatrix3x3(name, matrix);
  35860. };
  35861. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35862. this._currentEffect.setMatrix2x2(name, matrix);
  35863. };
  35864. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35865. // To match std140, matrix must be realigned
  35866. for (var i = 0; i < 2; i++) {
  35867. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35868. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35869. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35870. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35871. }
  35872. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35873. };
  35874. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35875. this._currentEffect.setFloat(name, x);
  35876. };
  35877. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35878. UniformBuffer._tempBuffer[0] = x;
  35879. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35880. };
  35881. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35882. if (suffix === void 0) { suffix = ""; }
  35883. this._currentEffect.setFloat2(name + suffix, x, y);
  35884. };
  35885. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35886. if (suffix === void 0) { suffix = ""; }
  35887. UniformBuffer._tempBuffer[0] = x;
  35888. UniformBuffer._tempBuffer[1] = y;
  35889. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35890. };
  35891. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35892. if (suffix === void 0) { suffix = ""; }
  35893. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35894. };
  35895. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35896. if (suffix === void 0) { suffix = ""; }
  35897. UniformBuffer._tempBuffer[0] = x;
  35898. UniformBuffer._tempBuffer[1] = y;
  35899. UniformBuffer._tempBuffer[2] = z;
  35900. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35901. };
  35902. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35903. if (suffix === void 0) { suffix = ""; }
  35904. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35905. };
  35906. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35907. if (suffix === void 0) { suffix = ""; }
  35908. UniformBuffer._tempBuffer[0] = x;
  35909. UniformBuffer._tempBuffer[1] = y;
  35910. UniformBuffer._tempBuffer[2] = z;
  35911. UniformBuffer._tempBuffer[3] = w;
  35912. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35913. };
  35914. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35915. this._currentEffect.setMatrix(name, mat);
  35916. };
  35917. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35918. this.updateUniform(name, mat.toArray(), 16);
  35919. };
  35920. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35921. this._currentEffect.setVector3(name, vector);
  35922. };
  35923. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35924. vector.toArray(UniformBuffer._tempBuffer);
  35925. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35926. };
  35927. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35928. this._currentEffect.setVector4(name, vector);
  35929. };
  35930. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35931. vector.toArray(UniformBuffer._tempBuffer);
  35932. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35933. };
  35934. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35935. if (suffix === void 0) { suffix = ""; }
  35936. this._currentEffect.setColor3(name + suffix, color);
  35937. };
  35938. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35939. if (suffix === void 0) { suffix = ""; }
  35940. color.toArray(UniformBuffer._tempBuffer);
  35941. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35942. };
  35943. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35944. if (suffix === void 0) { suffix = ""; }
  35945. this._currentEffect.setColor4(name + suffix, color, alpha);
  35946. };
  35947. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35948. if (suffix === void 0) { suffix = ""; }
  35949. color.toArray(UniformBuffer._tempBuffer);
  35950. UniformBuffer._tempBuffer[3] = alpha;
  35951. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35952. };
  35953. /**
  35954. * Sets a sampler uniform on the effect.
  35955. * @param {string} name Name of the sampler.
  35956. * @param {Texture} texture
  35957. */
  35958. UniformBuffer.prototype.setTexture = function (name, texture) {
  35959. this._currentEffect.setTexture(name, texture);
  35960. };
  35961. /**
  35962. * Directly updates the value of the uniform in the cache AND on the GPU.
  35963. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35964. * @param {number[]|Float32Array} data Flattened data
  35965. */
  35966. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  35967. this.updateUniform(uniformName, data, data.length);
  35968. this.update();
  35969. };
  35970. /**
  35971. * Binds this uniform buffer to an effect.
  35972. * @param {Effect} effect
  35973. * @param {string} name Name of the uniform block in the shader.
  35974. */
  35975. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  35976. this._currentEffect = effect;
  35977. if (this._noUBO || !this._buffer) {
  35978. return;
  35979. }
  35980. effect.bindUniformBuffer(this._buffer, name);
  35981. };
  35982. /**
  35983. * Disposes the uniform buffer.
  35984. */
  35985. UniformBuffer.prototype.dispose = function () {
  35986. if (this._noUBO) {
  35987. return;
  35988. }
  35989. var index = this._engine._uniformBuffers.indexOf(this);
  35990. if (index !== -1) {
  35991. this._engine._uniformBuffers.splice(index, 1);
  35992. }
  35993. if (!this._buffer) {
  35994. return;
  35995. }
  35996. if (this._engine._releaseBuffer(this._buffer)) {
  35997. this._buffer = null;
  35998. }
  35999. };
  36000. // Pool for avoiding memory leaks
  36001. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36002. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36003. return UniformBuffer;
  36004. }());
  36005. BABYLON.UniformBuffer = UniformBuffer;
  36006. })(BABYLON || (BABYLON = {}));
  36007. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36008. var BABYLON;
  36009. (function (BABYLON) {
  36010. /**
  36011. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36012. */
  36013. var VertexData = /** @class */ (function () {
  36014. function VertexData() {
  36015. }
  36016. /**
  36017. * Uses the passed data array to set the set the values for the specified kind of data
  36018. * @param data a linear array of floating numbers
  36019. * @param kind the type of data that is being set, eg positions, colors etc
  36020. */
  36021. VertexData.prototype.set = function (data, kind) {
  36022. switch (kind) {
  36023. case BABYLON.VertexBuffer.PositionKind:
  36024. this.positions = data;
  36025. break;
  36026. case BABYLON.VertexBuffer.NormalKind:
  36027. this.normals = data;
  36028. break;
  36029. case BABYLON.VertexBuffer.TangentKind:
  36030. this.tangents = data;
  36031. break;
  36032. case BABYLON.VertexBuffer.UVKind:
  36033. this.uvs = data;
  36034. break;
  36035. case BABYLON.VertexBuffer.UV2Kind:
  36036. this.uvs2 = data;
  36037. break;
  36038. case BABYLON.VertexBuffer.UV3Kind:
  36039. this.uvs3 = data;
  36040. break;
  36041. case BABYLON.VertexBuffer.UV4Kind:
  36042. this.uvs4 = data;
  36043. break;
  36044. case BABYLON.VertexBuffer.UV5Kind:
  36045. this.uvs5 = data;
  36046. break;
  36047. case BABYLON.VertexBuffer.UV6Kind:
  36048. this.uvs6 = data;
  36049. break;
  36050. case BABYLON.VertexBuffer.ColorKind:
  36051. this.colors = data;
  36052. break;
  36053. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36054. this.matricesIndices = data;
  36055. break;
  36056. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36057. this.matricesWeights = data;
  36058. break;
  36059. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36060. this.matricesIndicesExtra = data;
  36061. break;
  36062. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36063. this.matricesWeightsExtra = data;
  36064. break;
  36065. }
  36066. };
  36067. /**
  36068. * Associates the vertexData to the passed Mesh.
  36069. * Sets it as updatable or not (default `false`)
  36070. * @param mesh the mesh the vertexData is applied to
  36071. * @param updatable when used and having the value true allows new data to update the vertexData
  36072. * @returns the VertexData
  36073. */
  36074. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36075. this._applyTo(mesh, updatable);
  36076. return this;
  36077. };
  36078. /**
  36079. * Associates the vertexData to the passed Geometry.
  36080. * Sets it as updatable or not (default `false`)
  36081. * @param geometry the geometry the vertexData is applied to
  36082. * @param updatable when used and having the value true allows new data to update the vertexData
  36083. * @returns VertexData
  36084. */
  36085. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36086. this._applyTo(geometry, updatable);
  36087. return this;
  36088. };
  36089. /**
  36090. * Updates the associated mesh
  36091. * @param mesh the mesh to be updated
  36092. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36093. * @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
  36094. * @returns VertexData
  36095. */
  36096. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36097. this._update(mesh);
  36098. return this;
  36099. };
  36100. /**
  36101. * Updates the associated geometry
  36102. * @param geometry the geometry to be updated
  36103. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36104. * @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
  36105. * @returns VertexData.
  36106. */
  36107. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36108. this._update(geometry);
  36109. return this;
  36110. };
  36111. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36112. if (updatable === void 0) { updatable = false; }
  36113. if (this.positions) {
  36114. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36115. }
  36116. if (this.normals) {
  36117. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36118. }
  36119. if (this.tangents) {
  36120. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36121. }
  36122. if (this.uvs) {
  36123. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36124. }
  36125. if (this.uvs2) {
  36126. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36127. }
  36128. if (this.uvs3) {
  36129. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36130. }
  36131. if (this.uvs4) {
  36132. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36133. }
  36134. if (this.uvs5) {
  36135. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36136. }
  36137. if (this.uvs6) {
  36138. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36139. }
  36140. if (this.colors) {
  36141. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36142. }
  36143. if (this.matricesIndices) {
  36144. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36145. }
  36146. if (this.matricesWeights) {
  36147. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36148. }
  36149. if (this.matricesIndicesExtra) {
  36150. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36151. }
  36152. if (this.matricesWeightsExtra) {
  36153. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36154. }
  36155. if (this.indices) {
  36156. meshOrGeometry.setIndices(this.indices, null, updatable);
  36157. }
  36158. return this;
  36159. };
  36160. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36161. if (this.positions) {
  36162. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36163. }
  36164. if (this.normals) {
  36165. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36166. }
  36167. if (this.tangents) {
  36168. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36169. }
  36170. if (this.uvs) {
  36171. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36172. }
  36173. if (this.uvs2) {
  36174. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36175. }
  36176. if (this.uvs3) {
  36177. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36178. }
  36179. if (this.uvs4) {
  36180. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36181. }
  36182. if (this.uvs5) {
  36183. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36184. }
  36185. if (this.uvs6) {
  36186. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36187. }
  36188. if (this.colors) {
  36189. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36190. }
  36191. if (this.matricesIndices) {
  36192. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36193. }
  36194. if (this.matricesWeights) {
  36195. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36196. }
  36197. if (this.matricesIndicesExtra) {
  36198. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36199. }
  36200. if (this.matricesWeightsExtra) {
  36201. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36202. }
  36203. if (this.indices) {
  36204. meshOrGeometry.setIndices(this.indices, null);
  36205. }
  36206. return this;
  36207. };
  36208. /**
  36209. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36210. * @param matrix the transforming matrix
  36211. * @returns the VertexData
  36212. */
  36213. VertexData.prototype.transform = function (matrix) {
  36214. var transformed = BABYLON.Vector3.Zero();
  36215. var index;
  36216. if (this.positions) {
  36217. var position = BABYLON.Vector3.Zero();
  36218. for (index = 0; index < this.positions.length; index += 3) {
  36219. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36220. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36221. this.positions[index] = transformed.x;
  36222. this.positions[index + 1] = transformed.y;
  36223. this.positions[index + 2] = transformed.z;
  36224. }
  36225. }
  36226. if (this.normals) {
  36227. var normal = BABYLON.Vector3.Zero();
  36228. for (index = 0; index < this.normals.length; index += 3) {
  36229. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36230. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36231. this.normals[index] = transformed.x;
  36232. this.normals[index + 1] = transformed.y;
  36233. this.normals[index + 2] = transformed.z;
  36234. }
  36235. }
  36236. if (this.tangents) {
  36237. var tangent = BABYLON.Vector4.Zero();
  36238. var tangentTransformed = BABYLON.Vector4.Zero();
  36239. for (index = 0; index < this.tangents.length; index += 4) {
  36240. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36241. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36242. this.tangents[index] = tangentTransformed.x;
  36243. this.tangents[index + 1] = tangentTransformed.y;
  36244. this.tangents[index + 2] = tangentTransformed.z;
  36245. this.tangents[index + 3] = tangentTransformed.w;
  36246. }
  36247. }
  36248. return this;
  36249. };
  36250. /**
  36251. * Merges the passed VertexData into the current one
  36252. * @param other the VertexData to be merged into the current one
  36253. * @returns the modified VertexData
  36254. */
  36255. VertexData.prototype.merge = function (other) {
  36256. this._validate();
  36257. other._validate();
  36258. if (!this.normals !== !other.normals ||
  36259. !this.tangents !== !other.tangents ||
  36260. !this.uvs !== !other.uvs ||
  36261. !this.uvs2 !== !other.uvs2 ||
  36262. !this.uvs3 !== !other.uvs3 ||
  36263. !this.uvs4 !== !other.uvs4 ||
  36264. !this.uvs5 !== !other.uvs5 ||
  36265. !this.uvs6 !== !other.uvs6 ||
  36266. !this.colors !== !other.colors ||
  36267. !this.matricesIndices !== !other.matricesIndices ||
  36268. !this.matricesWeights !== !other.matricesWeights ||
  36269. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36270. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36271. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36272. }
  36273. if (other.indices) {
  36274. if (!this.indices) {
  36275. this.indices = [];
  36276. }
  36277. var offset = this.positions ? this.positions.length / 3 : 0;
  36278. for (var index = 0; index < other.indices.length; index++) {
  36279. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36280. this.indices.push(other.indices[index] + offset);
  36281. }
  36282. }
  36283. this.positions = this._mergeElement(this.positions, other.positions);
  36284. this.normals = this._mergeElement(this.normals, other.normals);
  36285. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36286. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36287. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36288. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36289. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36290. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36291. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36292. this.colors = this._mergeElement(this.colors, other.colors);
  36293. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36294. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36295. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36296. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36297. return this;
  36298. };
  36299. VertexData.prototype._mergeElement = function (source, other) {
  36300. if (!source) {
  36301. return other;
  36302. }
  36303. if (!other) {
  36304. return source;
  36305. }
  36306. var len = other.length + source.length;
  36307. var isSrcTypedArray = source instanceof Float32Array;
  36308. var isOthTypedArray = other instanceof Float32Array;
  36309. // use non-loop method when the source is Float32Array
  36310. if (isSrcTypedArray) {
  36311. var ret32 = new Float32Array(len);
  36312. ret32.set(source);
  36313. ret32.set(other, source.length);
  36314. return ret32;
  36315. // source is number[], when other is also use concat
  36316. }
  36317. else if (!isOthTypedArray) {
  36318. return source.concat(other);
  36319. // source is a number[], but other is a Float32Array, loop required
  36320. }
  36321. else {
  36322. var ret = source.slice(0); // copy source to a separate array
  36323. for (var i = 0, len = other.length; i < len; i++) {
  36324. ret.push(other[i]);
  36325. }
  36326. return ret;
  36327. }
  36328. };
  36329. VertexData.prototype._validate = function () {
  36330. if (!this.positions) {
  36331. throw new Error("Positions are required");
  36332. }
  36333. var getElementCount = function (kind, values) {
  36334. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36335. if ((values.length % stride) !== 0) {
  36336. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36337. }
  36338. return values.length / stride;
  36339. };
  36340. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36341. var validateElementCount = function (kind, values) {
  36342. var elementCount = getElementCount(kind, values);
  36343. if (elementCount !== positionsElementCount) {
  36344. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36345. }
  36346. };
  36347. if (this.normals)
  36348. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36349. if (this.tangents)
  36350. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36351. if (this.uvs)
  36352. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36353. if (this.uvs2)
  36354. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36355. if (this.uvs3)
  36356. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36357. if (this.uvs4)
  36358. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36359. if (this.uvs5)
  36360. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36361. if (this.uvs6)
  36362. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36363. if (this.colors)
  36364. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36365. if (this.matricesIndices)
  36366. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36367. if (this.matricesWeights)
  36368. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36369. if (this.matricesIndicesExtra)
  36370. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36371. if (this.matricesWeightsExtra)
  36372. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36373. };
  36374. /**
  36375. * Serializes the VertexData
  36376. * @returns a serialized object
  36377. */
  36378. VertexData.prototype.serialize = function () {
  36379. var serializationObject = this.serialize();
  36380. if (this.positions) {
  36381. serializationObject.positions = this.positions;
  36382. }
  36383. if (this.normals) {
  36384. serializationObject.normals = this.normals;
  36385. }
  36386. if (this.tangents) {
  36387. serializationObject.tangents = this.tangents;
  36388. }
  36389. if (this.uvs) {
  36390. serializationObject.uvs = this.uvs;
  36391. }
  36392. if (this.uvs2) {
  36393. serializationObject.uvs2 = this.uvs2;
  36394. }
  36395. if (this.uvs3) {
  36396. serializationObject.uvs3 = this.uvs3;
  36397. }
  36398. if (this.uvs4) {
  36399. serializationObject.uvs4 = this.uvs4;
  36400. }
  36401. if (this.uvs5) {
  36402. serializationObject.uvs5 = this.uvs5;
  36403. }
  36404. if (this.uvs6) {
  36405. serializationObject.uvs6 = this.uvs6;
  36406. }
  36407. if (this.colors) {
  36408. serializationObject.colors = this.colors;
  36409. }
  36410. if (this.matricesIndices) {
  36411. serializationObject.matricesIndices = this.matricesIndices;
  36412. serializationObject.matricesIndices._isExpanded = true;
  36413. }
  36414. if (this.matricesWeights) {
  36415. serializationObject.matricesWeights = this.matricesWeights;
  36416. }
  36417. if (this.matricesIndicesExtra) {
  36418. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36419. serializationObject.matricesIndicesExtra._isExpanded = true;
  36420. }
  36421. if (this.matricesWeightsExtra) {
  36422. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36423. }
  36424. serializationObject.indices = this.indices;
  36425. return serializationObject;
  36426. };
  36427. // Statics
  36428. /**
  36429. * Extracts the vertexData from a mesh
  36430. * @param mesh the mesh from which to extract the VertexData
  36431. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36432. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36433. * @returns the object VertexData associated to the passed mesh
  36434. */
  36435. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36436. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36437. };
  36438. /**
  36439. * Extracts the vertexData from the geometry
  36440. * @param geometry the geometry from which to extract the VertexData
  36441. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36442. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36443. * @returns the object VertexData associated to the passed mesh
  36444. */
  36445. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36446. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36447. };
  36448. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36449. var result = new VertexData();
  36450. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36451. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36452. }
  36453. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36454. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36455. }
  36456. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36457. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36458. }
  36459. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36460. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36461. }
  36462. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36463. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36464. }
  36465. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36466. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36467. }
  36468. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36469. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36470. }
  36471. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36472. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36473. }
  36474. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36475. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36476. }
  36477. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36478. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36479. }
  36480. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36481. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36482. }
  36483. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36484. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36485. }
  36486. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36487. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36488. }
  36489. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36490. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36491. }
  36492. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36493. return result;
  36494. };
  36495. /**
  36496. * Creates the VertexData for a Ribbon
  36497. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36498. * * pathArray array of paths, each of which an array of successive Vector3
  36499. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36500. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36501. * * 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
  36502. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36503. * * 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)
  36504. * * 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)
  36505. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36506. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36507. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36508. * @returns the VertexData of the ribbon
  36509. */
  36510. VertexData.CreateRibbon = function (options) {
  36511. var pathArray = options.pathArray;
  36512. var closeArray = options.closeArray || false;
  36513. var closePath = options.closePath || false;
  36514. var invertUV = options.invertUV || false;
  36515. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36516. var offset = options.offset || defaultOffset;
  36517. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36518. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36519. var customUV = options.uvs;
  36520. var customColors = options.colors;
  36521. var positions = [];
  36522. var indices = [];
  36523. var normals = [];
  36524. var uvs = [];
  36525. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36526. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36527. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36528. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36529. var minlg; // minimal length among all paths from pathArray
  36530. var lg = []; // array of path lengths : nb of vertex per path
  36531. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36532. var p; // path iterator
  36533. var i; // point iterator
  36534. var j; // point iterator
  36535. // if single path in pathArray
  36536. if (pathArray.length < 2) {
  36537. var ar1 = [];
  36538. var ar2 = [];
  36539. for (i = 0; i < pathArray[0].length - offset; i++) {
  36540. ar1.push(pathArray[0][i]);
  36541. ar2.push(pathArray[0][i + offset]);
  36542. }
  36543. pathArray = [ar1, ar2];
  36544. }
  36545. // positions and horizontal distances (u)
  36546. var idc = 0;
  36547. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36548. var path;
  36549. var l;
  36550. minlg = pathArray[0].length;
  36551. var vectlg;
  36552. var dist;
  36553. for (p = 0; p < pathArray.length; p++) {
  36554. uTotalDistance[p] = 0;
  36555. us[p] = [0];
  36556. path = pathArray[p];
  36557. l = path.length;
  36558. minlg = (minlg < l) ? minlg : l;
  36559. j = 0;
  36560. while (j < l) {
  36561. positions.push(path[j].x, path[j].y, path[j].z);
  36562. if (j > 0) {
  36563. vectlg = path[j].subtract(path[j - 1]).length();
  36564. dist = vectlg + uTotalDistance[p];
  36565. us[p].push(dist);
  36566. uTotalDistance[p] = dist;
  36567. }
  36568. j++;
  36569. }
  36570. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36571. j--;
  36572. positions.push(path[0].x, path[0].y, path[0].z);
  36573. vectlg = path[j].subtract(path[0]).length();
  36574. dist = vectlg + uTotalDistance[p];
  36575. us[p].push(dist);
  36576. uTotalDistance[p] = dist;
  36577. }
  36578. lg[p] = l + closePathCorr;
  36579. idx[p] = idc;
  36580. idc += (l + closePathCorr);
  36581. }
  36582. // vertical distances (v)
  36583. var path1;
  36584. var path2;
  36585. var vertex1 = null;
  36586. var vertex2 = null;
  36587. for (i = 0; i < minlg + closePathCorr; i++) {
  36588. vTotalDistance[i] = 0;
  36589. vs[i] = [0];
  36590. for (p = 0; p < pathArray.length - 1; p++) {
  36591. path1 = pathArray[p];
  36592. path2 = pathArray[p + 1];
  36593. if (i === minlg) { // closePath
  36594. vertex1 = path1[0];
  36595. vertex2 = path2[0];
  36596. }
  36597. else {
  36598. vertex1 = path1[i];
  36599. vertex2 = path2[i];
  36600. }
  36601. vectlg = vertex2.subtract(vertex1).length();
  36602. dist = vectlg + vTotalDistance[i];
  36603. vs[i].push(dist);
  36604. vTotalDistance[i] = dist;
  36605. }
  36606. if (closeArray && vertex2 && vertex1) {
  36607. path1 = pathArray[p];
  36608. path2 = pathArray[0];
  36609. if (i === minlg) { // closePath
  36610. vertex2 = path2[0];
  36611. }
  36612. vectlg = vertex2.subtract(vertex1).length();
  36613. dist = vectlg + vTotalDistance[i];
  36614. vTotalDistance[i] = dist;
  36615. }
  36616. }
  36617. // uvs
  36618. var u;
  36619. var v;
  36620. if (customUV) {
  36621. for (p = 0; p < customUV.length; p++) {
  36622. uvs.push(customUV[p].x, customUV[p].y);
  36623. }
  36624. }
  36625. else {
  36626. for (p = 0; p < pathArray.length; p++) {
  36627. for (i = 0; i < minlg + closePathCorr; i++) {
  36628. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36629. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36630. if (invertUV) {
  36631. uvs.push(v, u);
  36632. }
  36633. else {
  36634. uvs.push(u, v);
  36635. }
  36636. }
  36637. }
  36638. }
  36639. // indices
  36640. p = 0; // path index
  36641. var pi = 0; // positions array index
  36642. var l1 = lg[p] - 1; // path1 length
  36643. var l2 = lg[p + 1] - 1; // path2 length
  36644. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36645. var shft = idx[1] - idx[0]; // shift
  36646. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36647. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36648. // 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
  36649. indices.push(pi, pi + shft, pi + 1);
  36650. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36651. pi += 1;
  36652. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36653. p++;
  36654. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36655. shft = idx[0] - idx[p];
  36656. l1 = lg[p] - 1;
  36657. l2 = lg[0] - 1;
  36658. }
  36659. else {
  36660. shft = idx[p + 1] - idx[p];
  36661. l1 = lg[p] - 1;
  36662. l2 = lg[p + 1] - 1;
  36663. }
  36664. pi = idx[p];
  36665. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36666. }
  36667. }
  36668. // normals
  36669. VertexData.ComputeNormals(positions, indices, normals);
  36670. if (closePath) { // update both the first and last vertex normals to their average value
  36671. var indexFirst = 0;
  36672. var indexLast = 0;
  36673. for (p = 0; p < pathArray.length; p++) {
  36674. indexFirst = idx[p] * 3;
  36675. if (p + 1 < pathArray.length) {
  36676. indexLast = (idx[p + 1] - 1) * 3;
  36677. }
  36678. else {
  36679. indexLast = normals.length - 3;
  36680. }
  36681. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36682. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36683. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36684. normals[indexLast] = normals[indexFirst];
  36685. normals[indexLast + 1] = normals[indexFirst + 1];
  36686. normals[indexLast + 2] = normals[indexFirst + 2];
  36687. }
  36688. }
  36689. // sides
  36690. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36691. // Colors
  36692. var colors = null;
  36693. if (customColors) {
  36694. colors = new Float32Array(customColors.length * 4);
  36695. for (var c = 0; c < customColors.length; c++) {
  36696. colors[c * 4] = customColors[c].r;
  36697. colors[c * 4 + 1] = customColors[c].g;
  36698. colors[c * 4 + 2] = customColors[c].b;
  36699. colors[c * 4 + 3] = customColors[c].a;
  36700. }
  36701. }
  36702. // Result
  36703. var vertexData = new VertexData();
  36704. var positions32 = new Float32Array(positions);
  36705. var normals32 = new Float32Array(normals);
  36706. var uvs32 = new Float32Array(uvs);
  36707. vertexData.indices = indices;
  36708. vertexData.positions = positions32;
  36709. vertexData.normals = normals32;
  36710. vertexData.uvs = uvs32;
  36711. if (colors) {
  36712. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36713. }
  36714. if (closePath) {
  36715. vertexData._idx = idx;
  36716. }
  36717. return vertexData;
  36718. };
  36719. /**
  36720. * Creates the VertexData for a box
  36721. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36722. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36723. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36724. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36725. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36726. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36727. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36728. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36729. * * 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)
  36730. * * 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)
  36731. * @returns the VertexData of the box
  36732. */
  36733. VertexData.CreateBox = function (options) {
  36734. var normalsSource = [
  36735. new BABYLON.Vector3(0, 0, 1),
  36736. new BABYLON.Vector3(0, 0, -1),
  36737. new BABYLON.Vector3(1, 0, 0),
  36738. new BABYLON.Vector3(-1, 0, 0),
  36739. new BABYLON.Vector3(0, 1, 0),
  36740. new BABYLON.Vector3(0, -1, 0)
  36741. ];
  36742. var indices = [];
  36743. var positions = [];
  36744. var normals = [];
  36745. var uvs = [];
  36746. var width = options.width || options.size || 1;
  36747. var height = options.height || options.size || 1;
  36748. var depth = options.depth || options.size || 1;
  36749. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36750. var faceUV = options.faceUV || new Array(6);
  36751. var faceColors = options.faceColors;
  36752. var colors = [];
  36753. // default face colors and UV if undefined
  36754. for (var f = 0; f < 6; f++) {
  36755. if (faceUV[f] === undefined) {
  36756. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36757. }
  36758. if (faceColors && faceColors[f] === undefined) {
  36759. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36760. }
  36761. }
  36762. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36763. // Create each face in turn.
  36764. for (var index = 0; index < normalsSource.length; index++) {
  36765. var normal = normalsSource[index];
  36766. // Get two vectors perpendicular to the face normal and to each other.
  36767. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36768. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36769. // Six indices (two triangles) per face.
  36770. var verticesLength = positions.length / 3;
  36771. indices.push(verticesLength);
  36772. indices.push(verticesLength + 1);
  36773. indices.push(verticesLength + 2);
  36774. indices.push(verticesLength);
  36775. indices.push(verticesLength + 2);
  36776. indices.push(verticesLength + 3);
  36777. // Four vertices per face.
  36778. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36779. positions.push(vertex.x, vertex.y, vertex.z);
  36780. normals.push(normal.x, normal.y, normal.z);
  36781. uvs.push(faceUV[index].z, faceUV[index].w);
  36782. if (faceColors) {
  36783. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36784. }
  36785. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36786. positions.push(vertex.x, vertex.y, vertex.z);
  36787. normals.push(normal.x, normal.y, normal.z);
  36788. uvs.push(faceUV[index].x, faceUV[index].w);
  36789. if (faceColors) {
  36790. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36791. }
  36792. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36793. positions.push(vertex.x, vertex.y, vertex.z);
  36794. normals.push(normal.x, normal.y, normal.z);
  36795. uvs.push(faceUV[index].x, faceUV[index].y);
  36796. if (faceColors) {
  36797. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36798. }
  36799. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36800. positions.push(vertex.x, vertex.y, vertex.z);
  36801. normals.push(normal.x, normal.y, normal.z);
  36802. uvs.push(faceUV[index].z, faceUV[index].y);
  36803. if (faceColors) {
  36804. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36805. }
  36806. }
  36807. // sides
  36808. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36809. // Result
  36810. var vertexData = new VertexData();
  36811. vertexData.indices = indices;
  36812. vertexData.positions = positions;
  36813. vertexData.normals = normals;
  36814. vertexData.uvs = uvs;
  36815. if (faceColors) {
  36816. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36817. vertexData.colors = totalColors;
  36818. }
  36819. return vertexData;
  36820. };
  36821. /**
  36822. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36823. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36824. * * segments sets the number of horizontal strips optional, default 32
  36825. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36826. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36827. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36828. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36829. * * 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
  36830. * * 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
  36831. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36832. * * 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)
  36833. * * 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)
  36834. * @returns the VertexData of the ellipsoid
  36835. */
  36836. VertexData.CreateSphere = function (options) {
  36837. var segments = options.segments || 32;
  36838. var diameterX = options.diameterX || options.diameter || 1;
  36839. var diameterY = options.diameterY || options.diameter || 1;
  36840. var diameterZ = options.diameterZ || options.diameter || 1;
  36841. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36842. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36843. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36844. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36845. var totalZRotationSteps = 2 + segments;
  36846. var totalYRotationSteps = 2 * totalZRotationSteps;
  36847. var indices = [];
  36848. var positions = [];
  36849. var normals = [];
  36850. var uvs = [];
  36851. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36852. var normalizedZ = zRotationStep / totalZRotationSteps;
  36853. var angleZ = normalizedZ * Math.PI * slice;
  36854. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36855. var normalizedY = yRotationStep / totalYRotationSteps;
  36856. var angleY = normalizedY * Math.PI * 2 * arc;
  36857. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36858. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36859. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36860. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36861. var vertex = complete.multiply(radius);
  36862. var normal = complete.divide(radius).normalize();
  36863. positions.push(vertex.x, vertex.y, vertex.z);
  36864. normals.push(normal.x, normal.y, normal.z);
  36865. uvs.push(normalizedY, normalizedZ);
  36866. }
  36867. if (zRotationStep > 0) {
  36868. var verticesCount = positions.length / 3;
  36869. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36870. indices.push((firstIndex));
  36871. indices.push((firstIndex + 1));
  36872. indices.push(firstIndex + totalYRotationSteps + 1);
  36873. indices.push((firstIndex + totalYRotationSteps + 1));
  36874. indices.push((firstIndex + 1));
  36875. indices.push((firstIndex + totalYRotationSteps + 2));
  36876. }
  36877. }
  36878. }
  36879. // Sides
  36880. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36881. // Result
  36882. var vertexData = new VertexData();
  36883. vertexData.indices = indices;
  36884. vertexData.positions = positions;
  36885. vertexData.normals = normals;
  36886. vertexData.uvs = uvs;
  36887. return vertexData;
  36888. };
  36889. /**
  36890. * Creates the VertexData for a cylinder, cone or prism
  36891. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36892. * * height sets the height (y direction) of the cylinder, optional, default 2
  36893. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36894. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36895. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36896. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36897. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36898. * * 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
  36899. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36900. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36901. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36902. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36903. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36904. * * 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)
  36905. * * 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)
  36906. * @returns the VertexData of the cylinder, cone or prism
  36907. */
  36908. VertexData.CreateCylinder = function (options) {
  36909. var height = options.height || 2;
  36910. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36911. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36912. var tessellation = options.tessellation || 24;
  36913. var subdivisions = options.subdivisions || 1;
  36914. var hasRings = options.hasRings ? true : false;
  36915. var enclose = options.enclose ? true : false;
  36916. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36917. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36918. var faceUV = options.faceUV || new Array(3);
  36919. var faceColors = options.faceColors;
  36920. // default face colors and UV if undefined
  36921. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36922. var ringNb = (hasRings) ? subdivisions : 1;
  36923. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36924. var f;
  36925. for (f = 0; f < surfaceNb; f++) {
  36926. if (faceColors && faceColors[f] === undefined) {
  36927. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36928. }
  36929. }
  36930. for (f = 0; f < surfaceNb; f++) {
  36931. if (faceUV && faceUV[f] === undefined) {
  36932. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36933. }
  36934. }
  36935. var indices = new Array();
  36936. var positions = new Array();
  36937. var normals = new Array();
  36938. var uvs = new Array();
  36939. var colors = new Array();
  36940. var angle_step = Math.PI * 2 * arc / tessellation;
  36941. var angle;
  36942. var h;
  36943. var radius;
  36944. var tan = (diameterBottom - diameterTop) / 2 / height;
  36945. var ringVertex = BABYLON.Vector3.Zero();
  36946. var ringNormal = BABYLON.Vector3.Zero();
  36947. var ringFirstVertex = BABYLON.Vector3.Zero();
  36948. var ringFirstNormal = BABYLON.Vector3.Zero();
  36949. var quadNormal = BABYLON.Vector3.Zero();
  36950. var Y = BABYLON.Axis.Y;
  36951. // positions, normals, uvs
  36952. var i;
  36953. var j;
  36954. var r;
  36955. var ringIdx = 1;
  36956. var s = 1; // surface index
  36957. var cs = 0;
  36958. var v = 0;
  36959. for (i = 0; i <= subdivisions; i++) {
  36960. h = i / subdivisions;
  36961. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36962. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36963. for (r = 0; r < ringIdx; r++) {
  36964. if (hasRings) {
  36965. s += r;
  36966. }
  36967. if (enclose) {
  36968. s += 2 * r;
  36969. }
  36970. for (j = 0; j <= tessellation; j++) {
  36971. angle = j * angle_step;
  36972. // position
  36973. ringVertex.x = Math.cos(-angle) * radius;
  36974. ringVertex.y = -height / 2 + h * height;
  36975. ringVertex.z = Math.sin(-angle) * radius;
  36976. // normal
  36977. if (diameterTop === 0 && i === subdivisions) {
  36978. // if no top cap, reuse former normals
  36979. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36980. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36981. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36982. }
  36983. else {
  36984. ringNormal.x = ringVertex.x;
  36985. ringNormal.z = ringVertex.z;
  36986. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36987. ringNormal.normalize();
  36988. }
  36989. // keep first ring vertex values for enclose
  36990. if (j === 0) {
  36991. ringFirstVertex.copyFrom(ringVertex);
  36992. ringFirstNormal.copyFrom(ringNormal);
  36993. }
  36994. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36995. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  36996. if (hasRings) {
  36997. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  36998. }
  36999. else {
  37000. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37001. }
  37002. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37003. if (faceColors) {
  37004. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37005. }
  37006. }
  37007. // if enclose, add four vertices and their dedicated normals
  37008. if (arc !== 1 && enclose) {
  37009. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37010. positions.push(0, ringVertex.y, 0);
  37011. positions.push(0, ringVertex.y, 0);
  37012. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37013. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37014. quadNormal.normalize();
  37015. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37016. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37017. quadNormal.normalize();
  37018. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37019. if (hasRings) {
  37020. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37021. }
  37022. else {
  37023. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37024. }
  37025. uvs.push(faceUV[s + 1].x, v);
  37026. uvs.push(faceUV[s + 1].z, v);
  37027. if (hasRings) {
  37028. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37029. }
  37030. else {
  37031. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37032. }
  37033. uvs.push(faceUV[s + 2].x, v);
  37034. uvs.push(faceUV[s + 2].z, v);
  37035. if (faceColors) {
  37036. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37037. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37038. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37039. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37040. }
  37041. }
  37042. if (cs !== s) {
  37043. cs = s;
  37044. }
  37045. }
  37046. }
  37047. // indices
  37048. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37049. var s;
  37050. i = 0;
  37051. for (s = 0; s < subdivisions; s++) {
  37052. var i0 = 0;
  37053. var i1 = 0;
  37054. var i2 = 0;
  37055. var i3 = 0;
  37056. for (j = 0; j < tessellation; j++) {
  37057. i0 = i * (e + 1) + j;
  37058. i1 = (i + 1) * (e + 1) + j;
  37059. i2 = i * (e + 1) + (j + 1);
  37060. i3 = (i + 1) * (e + 1) + (j + 1);
  37061. indices.push(i0, i1, i2);
  37062. indices.push(i3, i2, i1);
  37063. }
  37064. if (arc !== 1 && enclose) { // if enclose, add two quads
  37065. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37066. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37067. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37068. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37069. }
  37070. i = (hasRings) ? (i + 2) : (i + 1);
  37071. }
  37072. // Caps
  37073. var createCylinderCap = function (isTop) {
  37074. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37075. if (radius === 0) {
  37076. return;
  37077. }
  37078. // Cap positions, normals & uvs
  37079. var angle;
  37080. var circleVector;
  37081. var i;
  37082. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37083. var c = null;
  37084. if (faceColors) {
  37085. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37086. }
  37087. // cap center
  37088. var vbase = positions.length / 3;
  37089. var offset = isTop ? height / 2 : -height / 2;
  37090. var center = new BABYLON.Vector3(0, offset, 0);
  37091. positions.push(center.x, center.y, center.z);
  37092. normals.push(0, isTop ? 1 : -1, 0);
  37093. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37094. if (c) {
  37095. colors.push(c.r, c.g, c.b, c.a);
  37096. }
  37097. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37098. for (i = 0; i <= tessellation; i++) {
  37099. angle = Math.PI * 2 * i * arc / tessellation;
  37100. var cos = Math.cos(-angle);
  37101. var sin = Math.sin(-angle);
  37102. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37103. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37104. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37105. normals.push(0, isTop ? 1 : -1, 0);
  37106. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37107. if (c) {
  37108. colors.push(c.r, c.g, c.b, c.a);
  37109. }
  37110. }
  37111. // Cap indices
  37112. for (i = 0; i < tessellation; i++) {
  37113. if (!isTop) {
  37114. indices.push(vbase);
  37115. indices.push(vbase + (i + 1));
  37116. indices.push(vbase + (i + 2));
  37117. }
  37118. else {
  37119. indices.push(vbase);
  37120. indices.push(vbase + (i + 2));
  37121. indices.push(vbase + (i + 1));
  37122. }
  37123. }
  37124. };
  37125. // add caps to geometry
  37126. createCylinderCap(false);
  37127. createCylinderCap(true);
  37128. // Sides
  37129. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37130. var vertexData = new VertexData();
  37131. vertexData.indices = indices;
  37132. vertexData.positions = positions;
  37133. vertexData.normals = normals;
  37134. vertexData.uvs = uvs;
  37135. if (faceColors) {
  37136. vertexData.colors = colors;
  37137. }
  37138. return vertexData;
  37139. };
  37140. /**
  37141. * Creates the VertexData for a torus
  37142. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37143. * * diameter the diameter of the torus, optional default 1
  37144. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37145. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37146. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37147. * * 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)
  37148. * * 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)
  37149. * @returns the VertexData of the torus
  37150. */
  37151. VertexData.CreateTorus = function (options) {
  37152. var indices = [];
  37153. var positions = [];
  37154. var normals = [];
  37155. var uvs = [];
  37156. var diameter = options.diameter || 1;
  37157. var thickness = options.thickness || 0.5;
  37158. var tessellation = options.tessellation || 16;
  37159. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37160. var stride = tessellation + 1;
  37161. for (var i = 0; i <= tessellation; i++) {
  37162. var u = i / tessellation;
  37163. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37164. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37165. for (var j = 0; j <= tessellation; j++) {
  37166. var v = 1 - j / tessellation;
  37167. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37168. var dx = Math.cos(innerAngle);
  37169. var dy = Math.sin(innerAngle);
  37170. // Create a vertex.
  37171. var normal = new BABYLON.Vector3(dx, dy, 0);
  37172. var position = normal.scale(thickness / 2);
  37173. var textureCoordinate = new BABYLON.Vector2(u, v);
  37174. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37175. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37176. positions.push(position.x, position.y, position.z);
  37177. normals.push(normal.x, normal.y, normal.z);
  37178. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37179. // And create indices for two triangles.
  37180. var nextI = (i + 1) % stride;
  37181. var nextJ = (j + 1) % stride;
  37182. indices.push(i * stride + j);
  37183. indices.push(i * stride + nextJ);
  37184. indices.push(nextI * stride + j);
  37185. indices.push(i * stride + nextJ);
  37186. indices.push(nextI * stride + nextJ);
  37187. indices.push(nextI * stride + j);
  37188. }
  37189. }
  37190. // Sides
  37191. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37192. // Result
  37193. var vertexData = new VertexData();
  37194. vertexData.indices = indices;
  37195. vertexData.positions = positions;
  37196. vertexData.normals = normals;
  37197. vertexData.uvs = uvs;
  37198. return vertexData;
  37199. };
  37200. /**
  37201. * Creates the VertexData of the LineSystem
  37202. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37203. * - lines an array of lines, each line being an array of successive Vector3
  37204. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37205. * @returns the VertexData of the LineSystem
  37206. */
  37207. VertexData.CreateLineSystem = function (options) {
  37208. var indices = [];
  37209. var positions = [];
  37210. var lines = options.lines;
  37211. var colors = options.colors;
  37212. var vertexColors = [];
  37213. var idx = 0;
  37214. for (var l = 0; l < lines.length; l++) {
  37215. var points = lines[l];
  37216. for (var index = 0; index < points.length; index++) {
  37217. positions.push(points[index].x, points[index].y, points[index].z);
  37218. if (colors) {
  37219. var color = colors[l];
  37220. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37221. }
  37222. if (index > 0) {
  37223. indices.push(idx - 1);
  37224. indices.push(idx);
  37225. }
  37226. idx++;
  37227. }
  37228. }
  37229. var vertexData = new VertexData();
  37230. vertexData.indices = indices;
  37231. vertexData.positions = positions;
  37232. if (colors) {
  37233. vertexData.colors = vertexColors;
  37234. }
  37235. return vertexData;
  37236. };
  37237. /**
  37238. * Create the VertexData for a DashedLines
  37239. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37240. * - points an array successive Vector3
  37241. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37242. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37243. * - dashNb the intended total number of dashes, optional, default 200
  37244. * @returns the VertexData for the DashedLines
  37245. */
  37246. VertexData.CreateDashedLines = function (options) {
  37247. var dashSize = options.dashSize || 3;
  37248. var gapSize = options.gapSize || 1;
  37249. var dashNb = options.dashNb || 200;
  37250. var points = options.points;
  37251. var positions = new Array();
  37252. var indices = new Array();
  37253. var curvect = BABYLON.Vector3.Zero();
  37254. var lg = 0;
  37255. var nb = 0;
  37256. var shft = 0;
  37257. var dashshft = 0;
  37258. var curshft = 0;
  37259. var idx = 0;
  37260. var i = 0;
  37261. for (i = 0; i < points.length - 1; i++) {
  37262. points[i + 1].subtractToRef(points[i], curvect);
  37263. lg += curvect.length();
  37264. }
  37265. shft = lg / dashNb;
  37266. dashshft = dashSize * shft / (dashSize + gapSize);
  37267. for (i = 0; i < points.length - 1; i++) {
  37268. points[i + 1].subtractToRef(points[i], curvect);
  37269. nb = Math.floor(curvect.length() / shft);
  37270. curvect.normalize();
  37271. for (var j = 0; j < nb; j++) {
  37272. curshft = shft * j;
  37273. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37274. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37275. indices.push(idx, idx + 1);
  37276. idx += 2;
  37277. }
  37278. }
  37279. // Result
  37280. var vertexData = new VertexData();
  37281. vertexData.positions = positions;
  37282. vertexData.indices = indices;
  37283. return vertexData;
  37284. };
  37285. /**
  37286. * Creates the VertexData for a Ground
  37287. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37288. * - width the width (x direction) of the ground, optional, default 1
  37289. * - height the height (z direction) of the ground, optional, default 1
  37290. * - subdivisions the number of subdivisions per side, optional, default 1
  37291. * @returns the VertexData of the Ground
  37292. */
  37293. VertexData.CreateGround = function (options) {
  37294. var indices = [];
  37295. var positions = [];
  37296. var normals = [];
  37297. var uvs = [];
  37298. var row, col;
  37299. var width = options.width || 1;
  37300. var height = options.height || 1;
  37301. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37302. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37303. for (row = 0; row <= subdivisionsY; row++) {
  37304. for (col = 0; col <= subdivisionsX; col++) {
  37305. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37306. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37307. positions.push(position.x, position.y, position.z);
  37308. normals.push(normal.x, normal.y, normal.z);
  37309. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37310. }
  37311. }
  37312. for (row = 0; row < subdivisionsY; row++) {
  37313. for (col = 0; col < subdivisionsX; col++) {
  37314. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37315. indices.push(col + 1 + row * (subdivisionsX + 1));
  37316. indices.push(col + row * (subdivisionsX + 1));
  37317. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37318. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37319. indices.push(col + row * (subdivisionsX + 1));
  37320. }
  37321. }
  37322. // Result
  37323. var vertexData = new VertexData();
  37324. vertexData.indices = indices;
  37325. vertexData.positions = positions;
  37326. vertexData.normals = normals;
  37327. vertexData.uvs = uvs;
  37328. return vertexData;
  37329. };
  37330. /**
  37331. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37332. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37333. * * xmin the ground minimum X coordinate, optional, default -1
  37334. * * zmin the ground minimum Z coordinate, optional, default -1
  37335. * * xmax the ground maximum X coordinate, optional, default 1
  37336. * * zmax the ground maximum Z coordinate, optional, default 1
  37337. * * 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}
  37338. * * 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}
  37339. * @returns the VertexData of the TiledGround
  37340. */
  37341. VertexData.CreateTiledGround = function (options) {
  37342. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37343. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37344. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37345. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37346. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37347. var precision = options.precision || { w: 1, h: 1 };
  37348. var indices = new Array();
  37349. var positions = new Array();
  37350. var normals = new Array();
  37351. var uvs = new Array();
  37352. var row, col, tileRow, tileCol;
  37353. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37354. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37355. precision.w = (precision.w < 1) ? 1 : precision.w;
  37356. precision.h = (precision.h < 1) ? 1 : precision.h;
  37357. var tileSize = {
  37358. 'w': (xmax - xmin) / subdivisions.w,
  37359. 'h': (zmax - zmin) / subdivisions.h
  37360. };
  37361. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37362. // Indices
  37363. var base = positions.length / 3;
  37364. var rowLength = precision.w + 1;
  37365. for (row = 0; row < precision.h; row++) {
  37366. for (col = 0; col < precision.w; col++) {
  37367. var square = [
  37368. base + col + row * rowLength,
  37369. base + (col + 1) + row * rowLength,
  37370. base + (col + 1) + (row + 1) * rowLength,
  37371. base + col + (row + 1) * rowLength
  37372. ];
  37373. indices.push(square[1]);
  37374. indices.push(square[2]);
  37375. indices.push(square[3]);
  37376. indices.push(square[0]);
  37377. indices.push(square[1]);
  37378. indices.push(square[3]);
  37379. }
  37380. }
  37381. // Position, normals and uvs
  37382. var position = BABYLON.Vector3.Zero();
  37383. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37384. for (row = 0; row <= precision.h; row++) {
  37385. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37386. for (col = 0; col <= precision.w; col++) {
  37387. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37388. position.y = 0;
  37389. positions.push(position.x, position.y, position.z);
  37390. normals.push(normal.x, normal.y, normal.z);
  37391. uvs.push(col / precision.w, row / precision.h);
  37392. }
  37393. }
  37394. }
  37395. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37396. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37397. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37398. }
  37399. }
  37400. // Result
  37401. var vertexData = new VertexData();
  37402. vertexData.indices = indices;
  37403. vertexData.positions = positions;
  37404. vertexData.normals = normals;
  37405. vertexData.uvs = uvs;
  37406. return vertexData;
  37407. };
  37408. /**
  37409. * Creates the VertexData of the Ground designed from a heightmap
  37410. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37411. * * width the width (x direction) of the ground
  37412. * * height the height (z direction) of the ground
  37413. * * subdivisions the number of subdivisions per side
  37414. * * minHeight the minimum altitude on the ground, optional, default 0
  37415. * * maxHeight the maximum altitude on the ground, optional default 1
  37416. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37417. * * buffer the array holding the image color data
  37418. * * bufferWidth the width of image
  37419. * * bufferHeight the height of image
  37420. * @returns the VertexData of the Ground designed from a heightmap
  37421. */
  37422. VertexData.CreateGroundFromHeightMap = function (options) {
  37423. var indices = [];
  37424. var positions = [];
  37425. var normals = [];
  37426. var uvs = [];
  37427. var row, col;
  37428. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37429. // Vertices
  37430. for (row = 0; row <= options.subdivisions; row++) {
  37431. for (col = 0; col <= options.subdivisions; col++) {
  37432. 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));
  37433. // Compute height
  37434. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37435. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37436. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37437. var r = options.buffer[pos] / 255.0;
  37438. var g = options.buffer[pos + 1] / 255.0;
  37439. var b = options.buffer[pos + 2] / 255.0;
  37440. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37441. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37442. // Add vertex
  37443. positions.push(position.x, position.y, position.z);
  37444. normals.push(0, 0, 0);
  37445. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37446. }
  37447. }
  37448. // Indices
  37449. for (row = 0; row < options.subdivisions; row++) {
  37450. for (col = 0; col < options.subdivisions; col++) {
  37451. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37452. indices.push(col + 1 + row * (options.subdivisions + 1));
  37453. indices.push(col + row * (options.subdivisions + 1));
  37454. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37455. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37456. indices.push(col + row * (options.subdivisions + 1));
  37457. }
  37458. }
  37459. // Normals
  37460. VertexData.ComputeNormals(positions, indices, normals);
  37461. // Result
  37462. var vertexData = new VertexData();
  37463. vertexData.indices = indices;
  37464. vertexData.positions = positions;
  37465. vertexData.normals = normals;
  37466. vertexData.uvs = uvs;
  37467. return vertexData;
  37468. };
  37469. /**
  37470. * Creates the VertexData for a Plane
  37471. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37472. * * size sets the width and height of the plane to the value of size, optional default 1
  37473. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37474. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37475. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37476. * * 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)
  37477. * * 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)
  37478. * @returns the VertexData of the box
  37479. */
  37480. VertexData.CreatePlane = function (options) {
  37481. var indices = [];
  37482. var positions = [];
  37483. var normals = [];
  37484. var uvs = [];
  37485. var width = options.width || options.size || 1;
  37486. var height = options.height || options.size || 1;
  37487. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37488. // Vertices
  37489. var halfWidth = width / 2.0;
  37490. var halfHeight = height / 2.0;
  37491. positions.push(-halfWidth, -halfHeight, 0);
  37492. normals.push(0, 0, -1.0);
  37493. uvs.push(0.0, 0.0);
  37494. positions.push(halfWidth, -halfHeight, 0);
  37495. normals.push(0, 0, -1.0);
  37496. uvs.push(1.0, 0.0);
  37497. positions.push(halfWidth, halfHeight, 0);
  37498. normals.push(0, 0, -1.0);
  37499. uvs.push(1.0, 1.0);
  37500. positions.push(-halfWidth, halfHeight, 0);
  37501. normals.push(0, 0, -1.0);
  37502. uvs.push(0.0, 1.0);
  37503. // Indices
  37504. indices.push(0);
  37505. indices.push(1);
  37506. indices.push(2);
  37507. indices.push(0);
  37508. indices.push(2);
  37509. indices.push(3);
  37510. // Sides
  37511. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37512. // Result
  37513. var vertexData = new VertexData();
  37514. vertexData.indices = indices;
  37515. vertexData.positions = positions;
  37516. vertexData.normals = normals;
  37517. vertexData.uvs = uvs;
  37518. return vertexData;
  37519. };
  37520. /**
  37521. * Creates the VertexData of the Disc or regular Polygon
  37522. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37523. * * radius the radius of the disc, optional default 0.5
  37524. * * tessellation the number of polygon sides, optional, default 64
  37525. * * 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
  37526. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37527. * * 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)
  37528. * * 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)
  37529. * @returns the VertexData of the box
  37530. */
  37531. VertexData.CreateDisc = function (options) {
  37532. var positions = new Array();
  37533. var indices = new Array();
  37534. var normals = new Array();
  37535. var uvs = new Array();
  37536. var radius = options.radius || 0.5;
  37537. var tessellation = options.tessellation || 64;
  37538. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37539. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37540. // positions and uvs
  37541. positions.push(0, 0, 0); // disc center first
  37542. uvs.push(0.5, 0.5);
  37543. var theta = Math.PI * 2 * arc;
  37544. var step = theta / tessellation;
  37545. for (var a = 0; a < theta; a += step) {
  37546. var x = Math.cos(a);
  37547. var y = Math.sin(a);
  37548. var u = (x + 1) / 2;
  37549. var v = (1 - y) / 2;
  37550. positions.push(radius * x, radius * y, 0);
  37551. uvs.push(u, v);
  37552. }
  37553. if (arc === 1) {
  37554. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37555. uvs.push(uvs[2], uvs[3]);
  37556. }
  37557. //indices
  37558. var vertexNb = positions.length / 3;
  37559. for (var i = 1; i < vertexNb - 1; i++) {
  37560. indices.push(i + 1, 0, i);
  37561. }
  37562. // result
  37563. VertexData.ComputeNormals(positions, indices, normals);
  37564. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37565. var vertexData = new VertexData();
  37566. vertexData.indices = indices;
  37567. vertexData.positions = positions;
  37568. vertexData.normals = normals;
  37569. vertexData.uvs = uvs;
  37570. return vertexData;
  37571. };
  37572. /**
  37573. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37574. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37575. * @param polygon a mesh built from polygonTriangulation.build()
  37576. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37577. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37578. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37579. * @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)
  37580. * @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)
  37581. * @returns the VertexData of the Polygon
  37582. */
  37583. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37584. var faceUV = fUV || new Array(3);
  37585. var faceColors = fColors;
  37586. var colors = [];
  37587. // default face colors and UV if undefined
  37588. for (var f = 0; f < 3; f++) {
  37589. if (faceUV[f] === undefined) {
  37590. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37591. }
  37592. if (faceColors && faceColors[f] === undefined) {
  37593. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37594. }
  37595. }
  37596. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37597. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37598. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37599. var indices = polygon.getIndices();
  37600. // set face colours and textures
  37601. var idx = 0;
  37602. var face = 0;
  37603. for (var index = 0; index < normals.length; index += 3) {
  37604. //Edge Face no. 1
  37605. if (Math.abs(normals[index + 1]) < 0.001) {
  37606. face = 1;
  37607. }
  37608. //Top Face no. 0
  37609. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37610. face = 0;
  37611. }
  37612. //Bottom Face no. 2
  37613. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37614. face = 2;
  37615. }
  37616. idx = index / 3;
  37617. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37618. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37619. if (faceColors) {
  37620. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37621. }
  37622. }
  37623. // sides
  37624. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37625. // Result
  37626. var vertexData = new VertexData();
  37627. vertexData.indices = indices;
  37628. vertexData.positions = positions;
  37629. vertexData.normals = normals;
  37630. vertexData.uvs = uvs;
  37631. if (faceColors) {
  37632. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37633. vertexData.colors = totalColors;
  37634. }
  37635. return vertexData;
  37636. };
  37637. /**
  37638. * Creates the VertexData of the IcoSphere
  37639. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37640. * * radius the radius of the IcoSphere, optional default 1
  37641. * * radiusX allows stretching in the x direction, optional, default radius
  37642. * * radiusY allows stretching in the y direction, optional, default radius
  37643. * * radiusZ allows stretching in the z direction, optional, default radius
  37644. * * flat when true creates a flat shaded mesh, optional, default true
  37645. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37646. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37647. * * 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)
  37648. * * 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)
  37649. * @returns the VertexData of the IcoSphere
  37650. */
  37651. VertexData.CreateIcoSphere = function (options) {
  37652. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37653. var radius = options.radius || 1;
  37654. var flat = (options.flat === undefined) ? true : options.flat;
  37655. var subdivisions = options.subdivisions || 4;
  37656. var radiusX = options.radiusX || radius;
  37657. var radiusY = options.radiusY || radius;
  37658. var radiusZ = options.radiusZ || radius;
  37659. var t = (1 + Math.sqrt(5)) / 2;
  37660. // 12 vertex x,y,z
  37661. var ico_vertices = [
  37662. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37663. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37664. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37665. ];
  37666. // index of 3 vertex makes a face of icopshere
  37667. var ico_indices = [
  37668. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37669. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37670. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37671. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37672. ];
  37673. // vertex for uv have aliased position, not for UV
  37674. var vertices_unalias_id = [
  37675. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37676. // vertex alias
  37677. 0,
  37678. 2,
  37679. 3,
  37680. 3,
  37681. 3,
  37682. 4,
  37683. 7,
  37684. 8,
  37685. 9,
  37686. 9,
  37687. 10,
  37688. 11 // 23: B + 12
  37689. ];
  37690. // uv as integer step (not pixels !)
  37691. var ico_vertexuv = [
  37692. 5, 1, 3, 1, 6, 4, 0, 0,
  37693. 5, 3, 4, 2, 2, 2, 4, 0,
  37694. 2, 0, 1, 1, 6, 0, 6, 2,
  37695. // vertex alias (for same vertex on different faces)
  37696. 0, 4,
  37697. 3, 3,
  37698. 4, 4,
  37699. 3, 1,
  37700. 4, 2,
  37701. 4, 4,
  37702. 0, 2,
  37703. 1, 1,
  37704. 2, 2,
  37705. 3, 3,
  37706. 1, 3,
  37707. 2, 4 // 23: B + 12
  37708. ];
  37709. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37710. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37711. // First island of uv mapping
  37712. // v = 4h 3+ 2
  37713. // v = 3h 9+ 4
  37714. // v = 2h 9+ 5 B
  37715. // v = 1h 9 1 0
  37716. // v = 0h 3 8 7 A
  37717. // u = 0 1 2 3 4 5 6 *a
  37718. // Second island of uv mapping
  37719. // v = 4h 0+ B+ 4+
  37720. // v = 3h A+ 2+
  37721. // v = 2h 7+ 6 3+
  37722. // v = 1h 8+ 3+
  37723. // v = 0h
  37724. // u = 0 1 2 3 4 5 6 *a
  37725. // Face layout on texture UV mapping
  37726. // ============
  37727. // \ 4 /\ 16 / ======
  37728. // \ / \ / /\ 11 /
  37729. // \/ 7 \/ / \ /
  37730. // ======= / 10 \/
  37731. // /\ 17 /\ =======
  37732. // / \ / \ \ 15 /\
  37733. // / 8 \/ 12 \ \ / \
  37734. // ============ \/ 6 \
  37735. // \ 18 /\ ============
  37736. // \ / \ \ 5 /\ 0 /
  37737. // \/ 13 \ \ / \ /
  37738. // ======= \/ 1 \/
  37739. // =============
  37740. // /\ 19 /\ 2 /\
  37741. // / \ / \ / \
  37742. // / 14 \/ 9 \/ 3 \
  37743. // ===================
  37744. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37745. var ustep = 138 / 1024;
  37746. var vstep = 239 / 1024;
  37747. var uoffset = 60 / 1024;
  37748. var voffset = 26 / 1024;
  37749. // Second island should have margin, not to touch the first island
  37750. // avoid any borderline artefact in pixel rounding
  37751. var island_u_offset = -40 / 1024;
  37752. var island_v_offset = +20 / 1024;
  37753. // face is either island 0 or 1 :
  37754. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37755. var island = [
  37756. 0, 0, 0, 0, 1,
  37757. 0, 0, 1, 1, 0,
  37758. 0, 0, 1, 1, 0,
  37759. 0, 1, 1, 1, 0 // 15 - 19
  37760. ];
  37761. var indices = new Array();
  37762. var positions = new Array();
  37763. var normals = new Array();
  37764. var uvs = new Array();
  37765. var current_indice = 0;
  37766. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37767. var face_vertex_pos = new Array(3);
  37768. var face_vertex_uv = new Array(3);
  37769. var v012;
  37770. for (v012 = 0; v012 < 3; v012++) {
  37771. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37772. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37773. }
  37774. // create all with normals
  37775. for (var face = 0; face < 20; face++) {
  37776. // 3 vertex per face
  37777. for (v012 = 0; v012 < 3; v012++) {
  37778. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37779. var v_id = ico_indices[3 * face + v012];
  37780. // vertex have 3D position (x,y,z)
  37781. 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]);
  37782. // Normalize to get normal, then scale to radius
  37783. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37784. // uv Coordinates from vertex ID
  37785. 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);
  37786. }
  37787. // Subdivide the face (interpolate pos, norm, uv)
  37788. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37789. // - norm is linear interpolation of vertex corner normal
  37790. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37791. // - uv is linear interpolation
  37792. //
  37793. // Topology is as below for sub-divide by 2
  37794. // vertex shown as v0,v1,v2
  37795. // interp index is i1 to progress in range [v0,v1[
  37796. // interp index is i2 to progress in range [v0,v2[
  37797. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37798. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37799. //
  37800. //
  37801. // i2 v2
  37802. // ^ ^
  37803. // / / \
  37804. // / / \
  37805. // / / \
  37806. // / / (0,1) \
  37807. // / #---------\
  37808. // / / \ (0,0)'/ \
  37809. // / / \ / \
  37810. // / / \ / \
  37811. // / / (0,0) \ / (1,0) \
  37812. // / #---------#---------\
  37813. // v0 v1
  37814. //
  37815. // --------------------> i1
  37816. //
  37817. // interp of (i1,i2):
  37818. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37819. // along i1 : lerp(x0,x1, i1/(S-i2))
  37820. //
  37821. // centroid of triangle is needed to get help normal computation
  37822. // (c1,c2) are used for centroid location
  37823. var interp_vertex = function (i1, i2, c1, c2) {
  37824. // vertex is interpolated from
  37825. // - face_vertex_pos[0..2]
  37826. // - face_vertex_uv[0..2]
  37827. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37828. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37829. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37830. pos_interp.normalize();
  37831. var vertex_normal;
  37832. if (flat) {
  37833. // in flat mode, recalculate normal as face centroid normal
  37834. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37835. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37836. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37837. }
  37838. else {
  37839. // in smooth mode, recalculate normal from each single vertex position
  37840. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37841. }
  37842. // Vertex normal need correction due to X,Y,Z radius scaling
  37843. vertex_normal.x /= radiusX;
  37844. vertex_normal.y /= radiusY;
  37845. vertex_normal.z /= radiusZ;
  37846. vertex_normal.normalize();
  37847. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37848. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37849. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37850. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37851. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37852. uvs.push(uv_interp.x, uv_interp.y);
  37853. // push each vertex has member of a face
  37854. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37855. indices.push(current_indice);
  37856. current_indice++;
  37857. };
  37858. for (var i2 = 0; i2 < subdivisions; i2++) {
  37859. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37860. // face : (i1,i2) for /\ :
  37861. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37862. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37863. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37864. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37865. if (i1 + i2 + 1 < subdivisions) {
  37866. // face : (i1,i2)' for \/ :
  37867. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37868. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37869. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37870. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37871. }
  37872. }
  37873. }
  37874. }
  37875. // Sides
  37876. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37877. // Result
  37878. var vertexData = new VertexData();
  37879. vertexData.indices = indices;
  37880. vertexData.positions = positions;
  37881. vertexData.normals = normals;
  37882. vertexData.uvs = uvs;
  37883. return vertexData;
  37884. };
  37885. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37886. /**
  37887. * Creates the VertexData for a Polyhedron
  37888. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37889. * * type provided types are:
  37890. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37891. * * 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)
  37892. * * size the size of the IcoSphere, optional default 1
  37893. * * sizeX allows stretching in the x direction, optional, default size
  37894. * * sizeY allows stretching in the y direction, optional, default size
  37895. * * sizeZ allows stretching in the z direction, optional, default size
  37896. * * 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
  37897. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37898. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37899. * * flat when true creates a flat shaded mesh, optional, default true
  37900. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37901. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37902. * * 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)
  37903. * * 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)
  37904. * @returns the VertexData of the Polyhedron
  37905. */
  37906. VertexData.CreatePolyhedron = function (options) {
  37907. // provided polyhedron types :
  37908. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37909. // 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)
  37910. var polyhedra = [];
  37911. 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]] };
  37912. 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]] };
  37913. polyhedra[2] = {
  37914. 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]],
  37915. 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]]
  37916. };
  37917. polyhedra[3] = {
  37918. 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]],
  37919. 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]]
  37920. };
  37921. polyhedra[4] = {
  37922. 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]],
  37923. 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]]
  37924. };
  37925. 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]] };
  37926. 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]] };
  37927. 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]] };
  37928. 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]] };
  37929. 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]] };
  37930. 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]] };
  37931. 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]] };
  37932. 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]] };
  37933. 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]] };
  37934. polyhedra[14] = {
  37935. 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]],
  37936. 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]]
  37937. };
  37938. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37939. var size = options.size;
  37940. var sizeX = options.sizeX || size || 1;
  37941. var sizeY = options.sizeY || size || 1;
  37942. var sizeZ = options.sizeZ || size || 1;
  37943. var data = options.custom || polyhedra[type];
  37944. var nbfaces = data.face.length;
  37945. var faceUV = options.faceUV || new Array(nbfaces);
  37946. var faceColors = options.faceColors;
  37947. var flat = (options.flat === undefined) ? true : options.flat;
  37948. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37949. var positions = new Array();
  37950. var indices = new Array();
  37951. var normals = new Array();
  37952. var uvs = new Array();
  37953. var colors = new Array();
  37954. var index = 0;
  37955. var faceIdx = 0; // face cursor in the array "indexes"
  37956. var indexes = new Array();
  37957. var i = 0;
  37958. var f = 0;
  37959. var u, v, ang, x, y, tmp;
  37960. // default face colors and UV if undefined
  37961. if (flat) {
  37962. for (f = 0; f < nbfaces; f++) {
  37963. if (faceColors && faceColors[f] === undefined) {
  37964. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37965. }
  37966. if (faceUV && faceUV[f] === undefined) {
  37967. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37968. }
  37969. }
  37970. }
  37971. if (!flat) {
  37972. for (i = 0; i < data.vertex.length; i++) {
  37973. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37974. uvs.push(0, 0);
  37975. }
  37976. for (f = 0; f < nbfaces; f++) {
  37977. for (i = 0; i < data.face[f].length - 2; i++) {
  37978. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37979. }
  37980. }
  37981. }
  37982. else {
  37983. for (f = 0; f < nbfaces; f++) {
  37984. var fl = data.face[f].length; // number of vertices of the current face
  37985. ang = 2 * Math.PI / fl;
  37986. x = 0.5 * Math.tan(ang / 2);
  37987. y = 0.5;
  37988. // positions, uvs, colors
  37989. for (i = 0; i < fl; i++) {
  37990. // positions
  37991. 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);
  37992. indexes.push(index);
  37993. index++;
  37994. // uvs
  37995. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  37996. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  37997. uvs.push(u, v);
  37998. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  37999. y = x * Math.sin(ang) + y * Math.cos(ang);
  38000. x = tmp;
  38001. // colors
  38002. if (faceColors) {
  38003. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38004. }
  38005. }
  38006. // indices from indexes
  38007. for (i = 0; i < fl - 2; i++) {
  38008. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38009. }
  38010. faceIdx += fl;
  38011. }
  38012. }
  38013. VertexData.ComputeNormals(positions, indices, normals);
  38014. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38015. var vertexData = new VertexData();
  38016. vertexData.positions = positions;
  38017. vertexData.indices = indices;
  38018. vertexData.normals = normals;
  38019. vertexData.uvs = uvs;
  38020. if (faceColors && flat) {
  38021. vertexData.colors = colors;
  38022. }
  38023. return vertexData;
  38024. };
  38025. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38026. /**
  38027. * Creates the VertexData for a TorusKnot
  38028. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38029. * * radius the radius of the torus knot, optional, default 2
  38030. * * tube the thickness of the tube, optional, default 0.5
  38031. * * radialSegments the number of sides on each tube segments, optional, default 32
  38032. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38033. * * p the number of windings around the z axis, optional, default 2
  38034. * * q the number of windings around the x axis, optional, default 3
  38035. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38036. * * 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)
  38037. * * 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)
  38038. * @returns the VertexData of the Torus Knot
  38039. */
  38040. VertexData.CreateTorusKnot = function (options) {
  38041. var indices = new Array();
  38042. var positions = new Array();
  38043. var normals = new Array();
  38044. var uvs = new Array();
  38045. var radius = options.radius || 2;
  38046. var tube = options.tube || 0.5;
  38047. var radialSegments = options.radialSegments || 32;
  38048. var tubularSegments = options.tubularSegments || 32;
  38049. var p = options.p || 2;
  38050. var q = options.q || 3;
  38051. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38052. // Helper
  38053. var getPos = function (angle) {
  38054. var cu = Math.cos(angle);
  38055. var su = Math.sin(angle);
  38056. var quOverP = q / p * angle;
  38057. var cs = Math.cos(quOverP);
  38058. var tx = radius * (2 + cs) * 0.5 * cu;
  38059. var ty = radius * (2 + cs) * su * 0.5;
  38060. var tz = radius * Math.sin(quOverP) * 0.5;
  38061. return new BABYLON.Vector3(tx, ty, tz);
  38062. };
  38063. // Vertices
  38064. var i;
  38065. var j;
  38066. for (i = 0; i <= radialSegments; i++) {
  38067. var modI = i % radialSegments;
  38068. var u = modI / radialSegments * 2 * p * Math.PI;
  38069. var p1 = getPos(u);
  38070. var p2 = getPos(u + 0.01);
  38071. var tang = p2.subtract(p1);
  38072. var n = p2.add(p1);
  38073. var bitan = BABYLON.Vector3.Cross(tang, n);
  38074. n = BABYLON.Vector3.Cross(bitan, tang);
  38075. bitan.normalize();
  38076. n.normalize();
  38077. for (j = 0; j < tubularSegments; j++) {
  38078. var modJ = j % tubularSegments;
  38079. var v = modJ / tubularSegments * 2 * Math.PI;
  38080. var cx = -tube * Math.cos(v);
  38081. var cy = tube * Math.sin(v);
  38082. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38083. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38084. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38085. uvs.push(i / radialSegments);
  38086. uvs.push(j / tubularSegments);
  38087. }
  38088. }
  38089. for (i = 0; i < radialSegments; i++) {
  38090. for (j = 0; j < tubularSegments; j++) {
  38091. var jNext = (j + 1) % tubularSegments;
  38092. var a = i * tubularSegments + j;
  38093. var b = (i + 1) * tubularSegments + j;
  38094. var c = (i + 1) * tubularSegments + jNext;
  38095. var d = i * tubularSegments + jNext;
  38096. indices.push(d);
  38097. indices.push(b);
  38098. indices.push(a);
  38099. indices.push(d);
  38100. indices.push(c);
  38101. indices.push(b);
  38102. }
  38103. }
  38104. // Normals
  38105. VertexData.ComputeNormals(positions, indices, normals);
  38106. // Sides
  38107. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38108. // Result
  38109. var vertexData = new VertexData();
  38110. vertexData.indices = indices;
  38111. vertexData.positions = positions;
  38112. vertexData.normals = normals;
  38113. vertexData.uvs = uvs;
  38114. return vertexData;
  38115. };
  38116. // Tools
  38117. /**
  38118. * Compute normals for given positions and indices
  38119. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38120. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38121. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38122. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38123. * * facetNormals : optional array of facet normals (vector3)
  38124. * * facetPositions : optional array of facet positions (vector3)
  38125. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38126. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38127. * * bInfo : optional bounding info, required for facetPartitioning computation
  38128. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38129. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38130. * * useRightHandedSystem: optional boolean to for right handed system computation
  38131. * * depthSort : optional boolean to enable the facet depth sort computation
  38132. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38133. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38134. */
  38135. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38136. // temporary scalar variables
  38137. var index = 0; // facet index
  38138. var p1p2x = 0.0; // p1p2 vector x coordinate
  38139. var p1p2y = 0.0; // p1p2 vector y coordinate
  38140. var p1p2z = 0.0; // p1p2 vector z coordinate
  38141. var p3p2x = 0.0; // p3p2 vector x coordinate
  38142. var p3p2y = 0.0; // p3p2 vector y coordinate
  38143. var p3p2z = 0.0; // p3p2 vector z coordinate
  38144. var faceNormalx = 0.0; // facet normal x coordinate
  38145. var faceNormaly = 0.0; // facet normal y coordinate
  38146. var faceNormalz = 0.0; // facet normal z coordinate
  38147. var length = 0.0; // facet normal length before normalization
  38148. var v1x = 0; // vector1 x index in the positions array
  38149. var v1y = 0; // vector1 y index in the positions array
  38150. var v1z = 0; // vector1 z index in the positions array
  38151. var v2x = 0; // vector2 x index in the positions array
  38152. var v2y = 0; // vector2 y index in the positions array
  38153. var v2z = 0; // vector2 z index in the positions array
  38154. var v3x = 0; // vector3 x index in the positions array
  38155. var v3y = 0; // vector3 y index in the positions array
  38156. var v3z = 0; // vector3 z index in the positions array
  38157. var computeFacetNormals = false;
  38158. var computeFacetPositions = false;
  38159. var computeFacetPartitioning = false;
  38160. var computeDepthSort = false;
  38161. var faceNormalSign = 1;
  38162. var ratio = 0;
  38163. var distanceTo = null;
  38164. if (options) {
  38165. computeFacetNormals = (options.facetNormals) ? true : false;
  38166. computeFacetPositions = (options.facetPositions) ? true : false;
  38167. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38168. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38169. ratio = options.ratio || 0;
  38170. computeDepthSort = (options.depthSort) ? true : false;
  38171. distanceTo = (options.distanceTo);
  38172. if (computeDepthSort) {
  38173. if (distanceTo === undefined) {
  38174. distanceTo = BABYLON.Vector3.Zero();
  38175. }
  38176. var depthSortedFacets = options.depthSortedFacets;
  38177. }
  38178. }
  38179. // facetPartitioning reinit if needed
  38180. var xSubRatio = 0;
  38181. var ySubRatio = 0;
  38182. var zSubRatio = 0;
  38183. var subSq = 0;
  38184. if (computeFacetPartitioning && options && options.bbSize) {
  38185. var ox = 0; // X partitioning index for facet position
  38186. var oy = 0; // Y partinioning index for facet position
  38187. var oz = 0; // Z partinioning index for facet position
  38188. var b1x = 0; // X partitioning index for facet v1 vertex
  38189. var b1y = 0; // Y partitioning index for facet v1 vertex
  38190. var b1z = 0; // z partitioning index for facet v1 vertex
  38191. var b2x = 0; // X partitioning index for facet v2 vertex
  38192. var b2y = 0; // Y partitioning index for facet v2 vertex
  38193. var b2z = 0; // Z partitioning index for facet v2 vertex
  38194. var b3x = 0; // X partitioning index for facet v3 vertex
  38195. var b3y = 0; // Y partitioning index for facet v3 vertex
  38196. var b3z = 0; // Z partitioning index for facet v3 vertex
  38197. var block_idx_o = 0; // facet barycenter block index
  38198. var block_idx_v1 = 0; // v1 vertex block index
  38199. var block_idx_v2 = 0; // v2 vertex block index
  38200. var block_idx_v3 = 0; // v3 vertex block index
  38201. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38202. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38203. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38204. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38205. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38206. subSq = options.subDiv.max * options.subDiv.max;
  38207. options.facetPartitioning.length = 0;
  38208. }
  38209. // reset the normals
  38210. for (index = 0; index < positions.length; index++) {
  38211. normals[index] = 0.0;
  38212. }
  38213. // Loop : 1 indice triplet = 1 facet
  38214. var nbFaces = (indices.length / 3) | 0;
  38215. for (index = 0; index < nbFaces; index++) {
  38216. // get the indexes of the coordinates of each vertex of the facet
  38217. v1x = indices[index * 3] * 3;
  38218. v1y = v1x + 1;
  38219. v1z = v1x + 2;
  38220. v2x = indices[index * 3 + 1] * 3;
  38221. v2y = v2x + 1;
  38222. v2z = v2x + 2;
  38223. v3x = indices[index * 3 + 2] * 3;
  38224. v3y = v3x + 1;
  38225. v3z = v3x + 2;
  38226. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38227. p1p2y = positions[v1y] - positions[v2y];
  38228. p1p2z = positions[v1z] - positions[v2z];
  38229. p3p2x = positions[v3x] - positions[v2x];
  38230. p3p2y = positions[v3y] - positions[v2y];
  38231. p3p2z = positions[v3z] - positions[v2z];
  38232. // compute the face normal with the cross product
  38233. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38234. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38235. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38236. // normalize this normal and store it in the array facetData
  38237. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38238. length = (length === 0) ? 1.0 : length;
  38239. faceNormalx /= length;
  38240. faceNormaly /= length;
  38241. faceNormalz /= length;
  38242. if (computeFacetNormals && options) {
  38243. options.facetNormals[index].x = faceNormalx;
  38244. options.facetNormals[index].y = faceNormaly;
  38245. options.facetNormals[index].z = faceNormalz;
  38246. }
  38247. if (computeFacetPositions && options) {
  38248. // compute and the facet barycenter coordinates in the array facetPositions
  38249. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38250. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38251. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38252. }
  38253. if (computeFacetPartitioning && options) {
  38254. // store the facet indexes in arrays in the main facetPartitioning array :
  38255. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38256. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38257. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38258. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38259. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38260. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38261. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38262. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38263. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38264. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38265. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38266. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38267. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38268. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38269. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38270. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38271. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38272. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38273. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38274. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38275. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38276. // push each facet index in each block containing the vertex
  38277. options.facetPartitioning[block_idx_v1].push(index);
  38278. if (block_idx_v2 != block_idx_v1) {
  38279. options.facetPartitioning[block_idx_v2].push(index);
  38280. }
  38281. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38282. options.facetPartitioning[block_idx_v3].push(index);
  38283. }
  38284. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38285. options.facetPartitioning[block_idx_o].push(index);
  38286. }
  38287. }
  38288. if (computeDepthSort && options && options.facetPositions) {
  38289. var dsf = depthSortedFacets[index];
  38290. dsf.ind = index * 3;
  38291. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38292. }
  38293. // compute the normals anyway
  38294. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38295. normals[v1y] += faceNormaly;
  38296. normals[v1z] += faceNormalz;
  38297. normals[v2x] += faceNormalx;
  38298. normals[v2y] += faceNormaly;
  38299. normals[v2z] += faceNormalz;
  38300. normals[v3x] += faceNormalx;
  38301. normals[v3y] += faceNormaly;
  38302. normals[v3z] += faceNormalz;
  38303. }
  38304. // last normalization of each normal
  38305. for (index = 0; index < normals.length / 3; index++) {
  38306. faceNormalx = normals[index * 3];
  38307. faceNormaly = normals[index * 3 + 1];
  38308. faceNormalz = normals[index * 3 + 2];
  38309. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38310. length = (length === 0) ? 1.0 : length;
  38311. faceNormalx /= length;
  38312. faceNormaly /= length;
  38313. faceNormalz /= length;
  38314. normals[index * 3] = faceNormalx;
  38315. normals[index * 3 + 1] = faceNormaly;
  38316. normals[index * 3 + 2] = faceNormalz;
  38317. }
  38318. };
  38319. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38320. var li = indices.length;
  38321. var ln = normals.length;
  38322. var i;
  38323. var n;
  38324. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38325. switch (sideOrientation) {
  38326. case BABYLON.Mesh.FRONTSIDE:
  38327. // nothing changed
  38328. break;
  38329. case BABYLON.Mesh.BACKSIDE:
  38330. var tmp;
  38331. // indices
  38332. for (i = 0; i < li; i += 3) {
  38333. tmp = indices[i];
  38334. indices[i] = indices[i + 2];
  38335. indices[i + 2] = tmp;
  38336. }
  38337. // normals
  38338. for (n = 0; n < ln; n++) {
  38339. normals[n] = -normals[n];
  38340. }
  38341. break;
  38342. case BABYLON.Mesh.DOUBLESIDE:
  38343. // positions
  38344. var lp = positions.length;
  38345. var l = lp / 3;
  38346. for (var p = 0; p < lp; p++) {
  38347. positions[lp + p] = positions[p];
  38348. }
  38349. // indices
  38350. for (i = 0; i < li; i += 3) {
  38351. indices[i + li] = indices[i + 2] + l;
  38352. indices[i + 1 + li] = indices[i + 1] + l;
  38353. indices[i + 2 + li] = indices[i] + l;
  38354. }
  38355. // normals
  38356. for (n = 0; n < ln; n++) {
  38357. normals[ln + n] = -normals[n];
  38358. }
  38359. // uvs
  38360. var lu = uvs.length;
  38361. var u = 0;
  38362. for (u = 0; u < lu; u++) {
  38363. uvs[u + lu] = uvs[u];
  38364. }
  38365. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38366. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38367. u = 0;
  38368. for (i = 0; i < lu / 2; i++) {
  38369. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38370. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38371. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38372. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38373. u += 2;
  38374. }
  38375. break;
  38376. }
  38377. };
  38378. /**
  38379. * Applies VertexData created from the imported parameters to the geometry
  38380. * @param parsedVertexData the parsed data from an imported file
  38381. * @param geometry the geometry to apply the VertexData to
  38382. */
  38383. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38384. var vertexData = new VertexData();
  38385. // positions
  38386. var positions = parsedVertexData.positions;
  38387. if (positions) {
  38388. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38389. }
  38390. // normals
  38391. var normals = parsedVertexData.normals;
  38392. if (normals) {
  38393. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38394. }
  38395. // tangents
  38396. var tangents = parsedVertexData.tangents;
  38397. if (tangents) {
  38398. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38399. }
  38400. // uvs
  38401. var uvs = parsedVertexData.uvs;
  38402. if (uvs) {
  38403. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38404. }
  38405. // uv2s
  38406. var uv2s = parsedVertexData.uv2s;
  38407. if (uv2s) {
  38408. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38409. }
  38410. // uv3s
  38411. var uv3s = parsedVertexData.uv3s;
  38412. if (uv3s) {
  38413. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38414. }
  38415. // uv4s
  38416. var uv4s = parsedVertexData.uv4s;
  38417. if (uv4s) {
  38418. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38419. }
  38420. // uv5s
  38421. var uv5s = parsedVertexData.uv5s;
  38422. if (uv5s) {
  38423. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38424. }
  38425. // uv6s
  38426. var uv6s = parsedVertexData.uv6s;
  38427. if (uv6s) {
  38428. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38429. }
  38430. // colors
  38431. var colors = parsedVertexData.colors;
  38432. if (colors) {
  38433. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38434. }
  38435. // matricesIndices
  38436. var matricesIndices = parsedVertexData.matricesIndices;
  38437. if (matricesIndices) {
  38438. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38439. }
  38440. // matricesWeights
  38441. var matricesWeights = parsedVertexData.matricesWeights;
  38442. if (matricesWeights) {
  38443. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38444. }
  38445. // indices
  38446. var indices = parsedVertexData.indices;
  38447. if (indices) {
  38448. vertexData.indices = indices;
  38449. }
  38450. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38451. };
  38452. return VertexData;
  38453. }());
  38454. BABYLON.VertexData = VertexData;
  38455. })(BABYLON || (BABYLON = {}));
  38456. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38457. var BABYLON;
  38458. (function (BABYLON) {
  38459. /**
  38460. * Class used to store geometry data (vertex buffers + index buffer)
  38461. */
  38462. var Geometry = /** @class */ (function () {
  38463. /**
  38464. * Creates a new geometry
  38465. * @param id defines the unique ID
  38466. * @param scene defines the hosting scene
  38467. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38468. * @param updatable defines if geometry must be updatable (false by default)
  38469. * @param mesh defines the mesh that will be associated with the geometry
  38470. */
  38471. function Geometry(id, scene, vertexData, updatable, mesh) {
  38472. if (updatable === void 0) { updatable = false; }
  38473. if (mesh === void 0) { mesh = null; }
  38474. /**
  38475. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38476. */
  38477. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38478. this._totalVertices = 0;
  38479. this._isDisposed = false;
  38480. this._indexBufferIsUpdatable = false;
  38481. this.id = id;
  38482. this._engine = scene.getEngine();
  38483. this._meshes = [];
  38484. this._scene = scene;
  38485. //Init vertex buffer cache
  38486. this._vertexBuffers = {};
  38487. this._indices = [];
  38488. this._updatable = updatable;
  38489. // vertexData
  38490. if (vertexData) {
  38491. this.setAllVerticesData(vertexData, updatable);
  38492. }
  38493. else {
  38494. this._totalVertices = 0;
  38495. this._indices = [];
  38496. }
  38497. if (this._engine.getCaps().vertexArrayObject) {
  38498. this._vertexArrayObjects = {};
  38499. }
  38500. // applyToMesh
  38501. if (mesh) {
  38502. if (mesh.getClassName() === "LinesMesh") {
  38503. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38504. this._updateExtend();
  38505. }
  38506. this.applyToMesh(mesh);
  38507. mesh.computeWorldMatrix(true);
  38508. }
  38509. }
  38510. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38511. /**
  38512. * 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
  38513. */
  38514. get: function () {
  38515. return this._boundingBias;
  38516. },
  38517. /**
  38518. * 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
  38519. */
  38520. set: function (value) {
  38521. if (this._boundingBias && this._boundingBias.equals(value)) {
  38522. return;
  38523. }
  38524. this._boundingBias = value.clone();
  38525. this._updateBoundingInfo(true, null);
  38526. },
  38527. enumerable: true,
  38528. configurable: true
  38529. });
  38530. /**
  38531. * Static function used to attach a new empty geometry to a mesh
  38532. * @param mesh defines the mesh to attach the geometry to
  38533. * @returns the new {BABYLON.Geometry}
  38534. */
  38535. Geometry.CreateGeometryForMesh = function (mesh) {
  38536. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38537. geometry.applyToMesh(mesh);
  38538. return geometry;
  38539. };
  38540. Object.defineProperty(Geometry.prototype, "extend", {
  38541. /**
  38542. * Gets the current extend of the geometry
  38543. */
  38544. get: function () {
  38545. return this._extend;
  38546. },
  38547. enumerable: true,
  38548. configurable: true
  38549. });
  38550. /**
  38551. * Gets the hosting scene
  38552. * @returns the hosting {BABYLON.Scene}
  38553. */
  38554. Geometry.prototype.getScene = function () {
  38555. return this._scene;
  38556. };
  38557. /**
  38558. * Gets the hosting engine
  38559. * @returns the hosting {BABYLON.Engine}
  38560. */
  38561. Geometry.prototype.getEngine = function () {
  38562. return this._engine;
  38563. };
  38564. /**
  38565. * Defines if the geometry is ready to use
  38566. * @returns true if the geometry is ready to be used
  38567. */
  38568. Geometry.prototype.isReady = function () {
  38569. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38570. };
  38571. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38572. /**
  38573. * Gets a value indicating that the geometry should not be serialized
  38574. */
  38575. get: function () {
  38576. for (var index = 0; index < this._meshes.length; index++) {
  38577. if (!this._meshes[index].doNotSerialize) {
  38578. return false;
  38579. }
  38580. }
  38581. return true;
  38582. },
  38583. enumerable: true,
  38584. configurable: true
  38585. });
  38586. /** @hidden */
  38587. Geometry.prototype._rebuild = function () {
  38588. if (this._vertexArrayObjects) {
  38589. this._vertexArrayObjects = {};
  38590. }
  38591. // Index buffer
  38592. if (this._meshes.length !== 0 && this._indices) {
  38593. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38594. }
  38595. // Vertex buffers
  38596. for (var key in this._vertexBuffers) {
  38597. var vertexBuffer = this._vertexBuffers[key];
  38598. vertexBuffer._rebuild();
  38599. }
  38600. };
  38601. /**
  38602. * Affects all gemetry data in one call
  38603. * @param vertexData defines the geometry data
  38604. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38605. */
  38606. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38607. vertexData.applyToGeometry(this, updatable);
  38608. this.notifyUpdate();
  38609. };
  38610. /**
  38611. * Set specific vertex data
  38612. * @param kind defines the data kind (Position, normal, etc...)
  38613. * @param data defines the vertex data to use
  38614. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38615. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38616. */
  38617. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38618. if (updatable === void 0) { updatable = false; }
  38619. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38620. this.setVerticesBuffer(buffer);
  38621. };
  38622. /**
  38623. * Removes a specific vertex data
  38624. * @param kind defines the data kind (Position, normal, etc...)
  38625. */
  38626. Geometry.prototype.removeVerticesData = function (kind) {
  38627. if (this._vertexBuffers[kind]) {
  38628. this._vertexBuffers[kind].dispose();
  38629. delete this._vertexBuffers[kind];
  38630. }
  38631. };
  38632. /**
  38633. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38634. * @param buffer defines the vertex buffer to use
  38635. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38636. */
  38637. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38638. if (totalVertices === void 0) { totalVertices = null; }
  38639. var kind = buffer.getKind();
  38640. if (this._vertexBuffers[kind]) {
  38641. this._vertexBuffers[kind].dispose();
  38642. }
  38643. this._vertexBuffers[kind] = buffer;
  38644. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38645. var data = buffer.getData();
  38646. if (totalVertices != null) {
  38647. this._totalVertices = totalVertices;
  38648. }
  38649. else {
  38650. if (data != null) {
  38651. this._totalVertices = data.length / (buffer.byteStride / 4);
  38652. }
  38653. }
  38654. this._updateExtend(data);
  38655. this._resetPointsArrayCache();
  38656. var meshes = this._meshes;
  38657. var numOfMeshes = meshes.length;
  38658. for (var index = 0; index < numOfMeshes; index++) {
  38659. var mesh = meshes[index];
  38660. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38661. mesh._createGlobalSubMesh(false);
  38662. mesh.computeWorldMatrix(true);
  38663. }
  38664. }
  38665. this.notifyUpdate(kind);
  38666. if (this._vertexArrayObjects) {
  38667. this._disposeVertexArrayObjects();
  38668. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38669. }
  38670. };
  38671. /**
  38672. * Update a specific vertex buffer
  38673. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38674. * It will do nothing if the buffer is not updatable
  38675. * @param kind defines the data kind (Position, normal, etc...)
  38676. * @param data defines the data to use
  38677. * @param offset defines the offset in the target buffer where to store the data
  38678. * @param useBytes set to true if the offset is in bytes
  38679. */
  38680. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38681. if (useBytes === void 0) { useBytes = false; }
  38682. var vertexBuffer = this.getVertexBuffer(kind);
  38683. if (!vertexBuffer) {
  38684. return;
  38685. }
  38686. vertexBuffer.updateDirectly(data, offset, useBytes);
  38687. this.notifyUpdate(kind);
  38688. };
  38689. /**
  38690. * Update a specific vertex buffer
  38691. * This function will create a new buffer if the current one is not updatable
  38692. * @param kind defines the data kind (Position, normal, etc...)
  38693. * @param data defines the data to use
  38694. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38695. */
  38696. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38697. if (updateExtends === void 0) { updateExtends = false; }
  38698. var vertexBuffer = this.getVertexBuffer(kind);
  38699. if (!vertexBuffer) {
  38700. return;
  38701. }
  38702. vertexBuffer.update(data);
  38703. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38704. this._updateBoundingInfo(updateExtends, data);
  38705. }
  38706. this.notifyUpdate(kind);
  38707. };
  38708. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38709. if (updateExtends) {
  38710. this._updateExtend(data);
  38711. }
  38712. var meshes = this._meshes;
  38713. var numOfMeshes = meshes.length;
  38714. this._resetPointsArrayCache();
  38715. for (var index = 0; index < numOfMeshes; index++) {
  38716. var mesh = meshes[index];
  38717. if (updateExtends) {
  38718. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38719. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38720. var subMesh = mesh.subMeshes[subIndex];
  38721. subMesh.refreshBoundingInfo();
  38722. }
  38723. }
  38724. }
  38725. };
  38726. /** @hidden */
  38727. Geometry.prototype._bind = function (effect, indexToBind) {
  38728. if (!effect) {
  38729. return;
  38730. }
  38731. if (indexToBind === undefined) {
  38732. indexToBind = this._indexBuffer;
  38733. }
  38734. var vbs = this.getVertexBuffers();
  38735. if (!vbs) {
  38736. return;
  38737. }
  38738. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38739. this._engine.bindBuffers(vbs, indexToBind, effect);
  38740. return;
  38741. }
  38742. // Using VAO
  38743. if (!this._vertexArrayObjects[effect.key]) {
  38744. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38745. }
  38746. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38747. };
  38748. /**
  38749. * Gets total number of vertices
  38750. * @returns the total number of vertices
  38751. */
  38752. Geometry.prototype.getTotalVertices = function () {
  38753. if (!this.isReady()) {
  38754. return 0;
  38755. }
  38756. return this._totalVertices;
  38757. };
  38758. /**
  38759. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38760. * @param kind defines the data kind (Position, normal, etc...)
  38761. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38762. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38763. * @returns a float array containing vertex data
  38764. */
  38765. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38766. var vertexBuffer = this.getVertexBuffer(kind);
  38767. if (!vertexBuffer) {
  38768. return null;
  38769. }
  38770. var data = vertexBuffer.getData();
  38771. if (!data) {
  38772. return null;
  38773. }
  38774. var defaultStride = BABYLON.VertexBuffer.DeduceStride(vertexBuffer.getKind());
  38775. var defaultByteStride = defaultStride * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38776. var count = this._totalVertices * defaultStride;
  38777. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== defaultByteStride) {
  38778. var copy_1 = new Array(count);
  38779. vertexBuffer.forEach(count, function (value, index) {
  38780. copy_1[index] = value;
  38781. });
  38782. return copy_1;
  38783. }
  38784. if (!(data instanceof Array || data instanceof Float32Array) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38785. if (data instanceof Array) {
  38786. var offset = vertexBuffer.byteOffset / 4;
  38787. return BABYLON.Tools.Slice(data, offset, offset + count);
  38788. }
  38789. else if (data instanceof ArrayBuffer) {
  38790. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38791. }
  38792. else {
  38793. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38794. }
  38795. }
  38796. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38797. return BABYLON.Tools.Slice(data);
  38798. }
  38799. return data;
  38800. };
  38801. /**
  38802. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38803. * @param kind defines the data kind (Position, normal, etc...)
  38804. * @returns true if the vertex buffer with the specified kind is updatable
  38805. */
  38806. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38807. var vb = this._vertexBuffers[kind];
  38808. if (!vb) {
  38809. return false;
  38810. }
  38811. return vb.isUpdatable();
  38812. };
  38813. /**
  38814. * Gets a specific vertex buffer
  38815. * @param kind defines the data kind (Position, normal, etc...)
  38816. * @returns a {BABYLON.VertexBuffer}
  38817. */
  38818. Geometry.prototype.getVertexBuffer = function (kind) {
  38819. if (!this.isReady()) {
  38820. return null;
  38821. }
  38822. return this._vertexBuffers[kind];
  38823. };
  38824. /**
  38825. * Returns all vertex buffers
  38826. * @return an object holding all vertex buffers indexed by kind
  38827. */
  38828. Geometry.prototype.getVertexBuffers = function () {
  38829. if (!this.isReady()) {
  38830. return null;
  38831. }
  38832. return this._vertexBuffers;
  38833. };
  38834. /**
  38835. * Gets a boolean indicating if specific vertex buffer is present
  38836. * @param kind defines the data kind (Position, normal, etc...)
  38837. * @returns true if data is present
  38838. */
  38839. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38840. if (!this._vertexBuffers) {
  38841. if (this._delayInfo) {
  38842. return this._delayInfo.indexOf(kind) !== -1;
  38843. }
  38844. return false;
  38845. }
  38846. return this._vertexBuffers[kind] !== undefined;
  38847. };
  38848. /**
  38849. * Gets a list of all attached data kinds (Position, normal, etc...)
  38850. * @returns a list of string containing all kinds
  38851. */
  38852. Geometry.prototype.getVerticesDataKinds = function () {
  38853. var result = [];
  38854. var kind;
  38855. if (!this._vertexBuffers && this._delayInfo) {
  38856. for (kind in this._delayInfo) {
  38857. result.push(kind);
  38858. }
  38859. }
  38860. else {
  38861. for (kind in this._vertexBuffers) {
  38862. result.push(kind);
  38863. }
  38864. }
  38865. return result;
  38866. };
  38867. /**
  38868. * Update index buffer
  38869. * @param indices defines the indices to store in the index buffer
  38870. * @param offset defines the offset in the target buffer where to store the data
  38871. */
  38872. Geometry.prototype.updateIndices = function (indices, offset) {
  38873. if (!this._indexBuffer) {
  38874. return;
  38875. }
  38876. if (!this._indexBufferIsUpdatable) {
  38877. this.setIndices(indices, null, true);
  38878. }
  38879. else {
  38880. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38881. }
  38882. };
  38883. /**
  38884. * Creates a new index buffer
  38885. * @param indices defines the indices to store in the index buffer
  38886. * @param totalVertices defines the total number of vertices (could be null)
  38887. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38888. */
  38889. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38890. if (totalVertices === void 0) { totalVertices = null; }
  38891. if (updatable === void 0) { updatable = false; }
  38892. if (this._indexBuffer) {
  38893. this._engine._releaseBuffer(this._indexBuffer);
  38894. }
  38895. this._disposeVertexArrayObjects();
  38896. this._indices = indices;
  38897. this._indexBufferIsUpdatable = updatable;
  38898. if (this._meshes.length !== 0 && this._indices) {
  38899. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38900. }
  38901. if (totalVertices != undefined) { // including null and undefined
  38902. this._totalVertices = totalVertices;
  38903. }
  38904. var meshes = this._meshes;
  38905. var numOfMeshes = meshes.length;
  38906. for (var index = 0; index < numOfMeshes; index++) {
  38907. meshes[index]._createGlobalSubMesh(true);
  38908. }
  38909. this.notifyUpdate();
  38910. };
  38911. /**
  38912. * Return the total number of indices
  38913. * @returns the total number of indices
  38914. */
  38915. Geometry.prototype.getTotalIndices = function () {
  38916. if (!this.isReady()) {
  38917. return 0;
  38918. }
  38919. return this._indices.length;
  38920. };
  38921. /**
  38922. * Gets the index buffer array
  38923. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38924. * @returns the index buffer array
  38925. */
  38926. Geometry.prototype.getIndices = function (copyWhenShared) {
  38927. if (!this.isReady()) {
  38928. return null;
  38929. }
  38930. var orig = this._indices;
  38931. if (!copyWhenShared || this._meshes.length === 1) {
  38932. return orig;
  38933. }
  38934. else {
  38935. var len = orig.length;
  38936. var copy = [];
  38937. for (var i = 0; i < len; i++) {
  38938. copy.push(orig[i]);
  38939. }
  38940. return copy;
  38941. }
  38942. };
  38943. /**
  38944. * Gets the index buffer
  38945. * @return the index buffer
  38946. */
  38947. Geometry.prototype.getIndexBuffer = function () {
  38948. if (!this.isReady()) {
  38949. return null;
  38950. }
  38951. return this._indexBuffer;
  38952. };
  38953. /** @hidden */
  38954. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  38955. if (effect === void 0) { effect = null; }
  38956. if (!effect || !this._vertexArrayObjects) {
  38957. return;
  38958. }
  38959. if (this._vertexArrayObjects[effect.key]) {
  38960. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  38961. delete this._vertexArrayObjects[effect.key];
  38962. }
  38963. };
  38964. /**
  38965. * Release the associated resources for a specific mesh
  38966. * @param mesh defines the source mesh
  38967. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  38968. */
  38969. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  38970. var meshes = this._meshes;
  38971. var index = meshes.indexOf(mesh);
  38972. if (index === -1) {
  38973. return;
  38974. }
  38975. meshes.splice(index, 1);
  38976. mesh._geometry = null;
  38977. if (meshes.length === 0 && shouldDispose) {
  38978. this.dispose();
  38979. }
  38980. };
  38981. /**
  38982. * Apply current geometry to a given mesh
  38983. * @param mesh defines the mesh to apply geometry to
  38984. */
  38985. Geometry.prototype.applyToMesh = function (mesh) {
  38986. if (mesh._geometry === this) {
  38987. return;
  38988. }
  38989. var previousGeometry = mesh._geometry;
  38990. if (previousGeometry) {
  38991. previousGeometry.releaseForMesh(mesh);
  38992. }
  38993. var meshes = this._meshes;
  38994. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  38995. mesh._geometry = this;
  38996. this._scene.pushGeometry(this);
  38997. meshes.push(mesh);
  38998. if (this.isReady()) {
  38999. this._applyToMesh(mesh);
  39000. }
  39001. else {
  39002. mesh._boundingInfo = this._boundingInfo;
  39003. }
  39004. };
  39005. Geometry.prototype._updateExtend = function (data) {
  39006. if (data === void 0) { data = null; }
  39007. if (!data) {
  39008. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39009. }
  39010. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39011. };
  39012. Geometry.prototype._applyToMesh = function (mesh) {
  39013. var numOfMeshes = this._meshes.length;
  39014. // vertexBuffers
  39015. for (var kind in this._vertexBuffers) {
  39016. if (numOfMeshes === 1) {
  39017. this._vertexBuffers[kind].create();
  39018. }
  39019. var buffer = this._vertexBuffers[kind].getBuffer();
  39020. if (buffer)
  39021. buffer.references = numOfMeshes;
  39022. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39023. if (!this._extend) {
  39024. this._updateExtend();
  39025. }
  39026. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39027. mesh._createGlobalSubMesh(false);
  39028. //bounding info was just created again, world matrix should be applied again.
  39029. mesh._updateBoundingInfo();
  39030. }
  39031. }
  39032. // indexBuffer
  39033. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39034. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39035. }
  39036. if (this._indexBuffer) {
  39037. this._indexBuffer.references = numOfMeshes;
  39038. }
  39039. };
  39040. Geometry.prototype.notifyUpdate = function (kind) {
  39041. if (this.onGeometryUpdated) {
  39042. this.onGeometryUpdated(this, kind);
  39043. }
  39044. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39045. var mesh = _a[_i];
  39046. mesh._markSubMeshesAsAttributesDirty();
  39047. }
  39048. };
  39049. /**
  39050. * Load the geometry if it was flagged as delay loaded
  39051. * @param scene defines the hosting scene
  39052. * @param onLoaded defines a callback called when the geometry is loaded
  39053. */
  39054. Geometry.prototype.load = function (scene, onLoaded) {
  39055. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39056. return;
  39057. }
  39058. if (this.isReady()) {
  39059. if (onLoaded) {
  39060. onLoaded();
  39061. }
  39062. return;
  39063. }
  39064. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39065. this._queueLoad(scene, onLoaded);
  39066. };
  39067. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39068. var _this = this;
  39069. if (!this.delayLoadingFile) {
  39070. return;
  39071. }
  39072. scene._addPendingData(this);
  39073. scene._loadFile(this.delayLoadingFile, function (data) {
  39074. if (!_this._delayLoadingFunction) {
  39075. return;
  39076. }
  39077. _this._delayLoadingFunction(JSON.parse(data), _this);
  39078. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39079. _this._delayInfo = [];
  39080. scene._removePendingData(_this);
  39081. var meshes = _this._meshes;
  39082. var numOfMeshes = meshes.length;
  39083. for (var index = 0; index < numOfMeshes; index++) {
  39084. _this._applyToMesh(meshes[index]);
  39085. }
  39086. if (onLoaded) {
  39087. onLoaded();
  39088. }
  39089. }, undefined, true);
  39090. };
  39091. /**
  39092. * Invert the geometry to move from a right handed system to a left handed one.
  39093. */
  39094. Geometry.prototype.toLeftHanded = function () {
  39095. // Flip faces
  39096. var tIndices = this.getIndices(false);
  39097. if (tIndices != null && tIndices.length > 0) {
  39098. for (var i = 0; i < tIndices.length; i += 3) {
  39099. var tTemp = tIndices[i + 0];
  39100. tIndices[i + 0] = tIndices[i + 2];
  39101. tIndices[i + 2] = tTemp;
  39102. }
  39103. this.setIndices(tIndices);
  39104. }
  39105. // Negate position.z
  39106. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39107. if (tPositions != null && tPositions.length > 0) {
  39108. for (var i = 0; i < tPositions.length; i += 3) {
  39109. tPositions[i + 2] = -tPositions[i + 2];
  39110. }
  39111. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39112. }
  39113. // Negate normal.z
  39114. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39115. if (tNormals != null && tNormals.length > 0) {
  39116. for (var i = 0; i < tNormals.length; i += 3) {
  39117. tNormals[i + 2] = -tNormals[i + 2];
  39118. }
  39119. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39120. }
  39121. };
  39122. // Cache
  39123. /** @hidden */
  39124. Geometry.prototype._resetPointsArrayCache = function () {
  39125. this._positions = null;
  39126. };
  39127. /** @hidden */
  39128. Geometry.prototype._generatePointsArray = function () {
  39129. if (this._positions)
  39130. return true;
  39131. this._positions = [];
  39132. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39133. if (!data) {
  39134. return false;
  39135. }
  39136. for (var index = 0; index < data.length; index += 3) {
  39137. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39138. }
  39139. return true;
  39140. };
  39141. /**
  39142. * Gets a value indicating if the geometry is disposed
  39143. * @returns true if the geometry was disposed
  39144. */
  39145. Geometry.prototype.isDisposed = function () {
  39146. return this._isDisposed;
  39147. };
  39148. Geometry.prototype._disposeVertexArrayObjects = function () {
  39149. if (this._vertexArrayObjects) {
  39150. for (var kind in this._vertexArrayObjects) {
  39151. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39152. }
  39153. this._vertexArrayObjects = {};
  39154. }
  39155. };
  39156. /**
  39157. * Free all associated resources
  39158. */
  39159. Geometry.prototype.dispose = function () {
  39160. var meshes = this._meshes;
  39161. var numOfMeshes = meshes.length;
  39162. var index;
  39163. for (index = 0; index < numOfMeshes; index++) {
  39164. this.releaseForMesh(meshes[index]);
  39165. }
  39166. this._meshes = [];
  39167. this._disposeVertexArrayObjects();
  39168. for (var kind in this._vertexBuffers) {
  39169. this._vertexBuffers[kind].dispose();
  39170. }
  39171. this._vertexBuffers = {};
  39172. this._totalVertices = 0;
  39173. if (this._indexBuffer) {
  39174. this._engine._releaseBuffer(this._indexBuffer);
  39175. }
  39176. this._indexBuffer = null;
  39177. this._indices = [];
  39178. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39179. this.delayLoadingFile = null;
  39180. this._delayLoadingFunction = null;
  39181. this._delayInfo = [];
  39182. this._boundingInfo = null;
  39183. this._scene.removeGeometry(this);
  39184. this._isDisposed = true;
  39185. };
  39186. /**
  39187. * Clone the current geometry into a new geometry
  39188. * @param id defines the unique ID of the new geometry
  39189. * @returns a new geometry object
  39190. */
  39191. Geometry.prototype.copy = function (id) {
  39192. var vertexData = new BABYLON.VertexData();
  39193. vertexData.indices = [];
  39194. var indices = this.getIndices();
  39195. if (indices) {
  39196. for (var index = 0; index < indices.length; index++) {
  39197. vertexData.indices.push(indices[index]);
  39198. }
  39199. }
  39200. var updatable = false;
  39201. var stopChecking = false;
  39202. var kind;
  39203. for (kind in this._vertexBuffers) {
  39204. // using slice() to make a copy of the array and not just reference it
  39205. var data = this.getVerticesData(kind);
  39206. if (data instanceof Float32Array) {
  39207. vertexData.set(new Float32Array(data), kind);
  39208. }
  39209. else {
  39210. vertexData.set(data.slice(0), kind);
  39211. }
  39212. if (!stopChecking) {
  39213. var vb = this.getVertexBuffer(kind);
  39214. if (vb) {
  39215. updatable = vb.isUpdatable();
  39216. stopChecking = !updatable;
  39217. }
  39218. }
  39219. }
  39220. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39221. geometry.delayLoadState = this.delayLoadState;
  39222. geometry.delayLoadingFile = this.delayLoadingFile;
  39223. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39224. for (kind in this._delayInfo) {
  39225. geometry._delayInfo = geometry._delayInfo || [];
  39226. geometry._delayInfo.push(kind);
  39227. }
  39228. // Bounding info
  39229. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39230. return geometry;
  39231. };
  39232. /**
  39233. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39234. * @return a JSON representation of the current geometry data (without the vertices data)
  39235. */
  39236. Geometry.prototype.serialize = function () {
  39237. var serializationObject = {};
  39238. serializationObject.id = this.id;
  39239. serializationObject.updatable = this._updatable;
  39240. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39241. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39242. }
  39243. return serializationObject;
  39244. };
  39245. Geometry.prototype.toNumberArray = function (origin) {
  39246. if (Array.isArray(origin)) {
  39247. return origin;
  39248. }
  39249. else {
  39250. return Array.prototype.slice.call(origin);
  39251. }
  39252. };
  39253. /**
  39254. * Serialize all vertices data into a JSON oject
  39255. * @returns a JSON representation of the current geometry data
  39256. */
  39257. Geometry.prototype.serializeVerticeData = function () {
  39258. var serializationObject = this.serialize();
  39259. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39260. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39261. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39262. serializationObject.positions._updatable = true;
  39263. }
  39264. }
  39265. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39266. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39267. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39268. serializationObject.normals._updatable = true;
  39269. }
  39270. }
  39271. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39272. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39273. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39274. serializationObject.tangets._updatable = true;
  39275. }
  39276. }
  39277. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39278. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39279. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39280. serializationObject.uvs._updatable = true;
  39281. }
  39282. }
  39283. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39284. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39285. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39286. serializationObject.uv2s._updatable = true;
  39287. }
  39288. }
  39289. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39290. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39291. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39292. serializationObject.uv3s._updatable = true;
  39293. }
  39294. }
  39295. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39296. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39297. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39298. serializationObject.uv4s._updatable = true;
  39299. }
  39300. }
  39301. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39302. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39303. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39304. serializationObject.uv5s._updatable = true;
  39305. }
  39306. }
  39307. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39308. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39309. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39310. serializationObject.uv6s._updatable = true;
  39311. }
  39312. }
  39313. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39314. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39315. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39316. serializationObject.colors._updatable = true;
  39317. }
  39318. }
  39319. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39320. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39321. serializationObject.matricesIndices._isExpanded = true;
  39322. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39323. serializationObject.matricesIndices._updatable = true;
  39324. }
  39325. }
  39326. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39327. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39328. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39329. serializationObject.matricesWeights._updatable = true;
  39330. }
  39331. }
  39332. serializationObject.indices = this.toNumberArray(this.getIndices());
  39333. return serializationObject;
  39334. };
  39335. // Statics
  39336. /**
  39337. * Extracts a clone of a mesh geometry
  39338. * @param mesh defines the source mesh
  39339. * @param id defines the unique ID of the new geometry object
  39340. * @returns the new geometry object
  39341. */
  39342. Geometry.ExtractFromMesh = function (mesh, id) {
  39343. var geometry = mesh._geometry;
  39344. if (!geometry) {
  39345. return null;
  39346. }
  39347. return geometry.copy(id);
  39348. };
  39349. /**
  39350. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39351. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39352. * Be aware Math.random() could cause collisions, but:
  39353. * "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"
  39354. * @returns a string containing a new GUID
  39355. */
  39356. Geometry.RandomId = function () {
  39357. return BABYLON.Tools.RandomId();
  39358. };
  39359. /** @hidden */
  39360. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39361. var scene = mesh.getScene();
  39362. // Geometry
  39363. var geometryId = parsedGeometry.geometryId;
  39364. if (geometryId) {
  39365. var geometry = scene.getGeometryByID(geometryId);
  39366. if (geometry) {
  39367. geometry.applyToMesh(mesh);
  39368. }
  39369. }
  39370. else if (parsedGeometry instanceof ArrayBuffer) {
  39371. var binaryInfo = mesh._binaryInfo;
  39372. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39373. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39374. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39375. }
  39376. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39377. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39378. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39379. }
  39380. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39381. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39382. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39383. }
  39384. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39385. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39386. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39387. }
  39388. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39389. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39390. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39391. }
  39392. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39393. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39394. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39395. }
  39396. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39397. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39398. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39399. }
  39400. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39401. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39402. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39403. }
  39404. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39405. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39406. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39407. }
  39408. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39409. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39410. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39411. }
  39412. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39413. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39414. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39415. }
  39416. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39417. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39418. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39419. }
  39420. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39421. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39422. mesh.setIndices(indicesData, null);
  39423. }
  39424. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39425. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39426. mesh.subMeshes = [];
  39427. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39428. var materialIndex = subMeshesData[(i * 5) + 0];
  39429. var verticesStart = subMeshesData[(i * 5) + 1];
  39430. var verticesCount = subMeshesData[(i * 5) + 2];
  39431. var indexStart = subMeshesData[(i * 5) + 3];
  39432. var indexCount = subMeshesData[(i * 5) + 4];
  39433. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39434. }
  39435. }
  39436. }
  39437. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39438. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39439. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39440. if (parsedGeometry.tangents) {
  39441. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39442. }
  39443. if (parsedGeometry.uvs) {
  39444. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39445. }
  39446. if (parsedGeometry.uvs2) {
  39447. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39448. }
  39449. if (parsedGeometry.uvs3) {
  39450. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39451. }
  39452. if (parsedGeometry.uvs4) {
  39453. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39454. }
  39455. if (parsedGeometry.uvs5) {
  39456. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39457. }
  39458. if (parsedGeometry.uvs6) {
  39459. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39460. }
  39461. if (parsedGeometry.colors) {
  39462. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39463. }
  39464. if (parsedGeometry.matricesIndices) {
  39465. if (!parsedGeometry.matricesIndices._isExpanded) {
  39466. var floatIndices = [];
  39467. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39468. var matricesIndex = parsedGeometry.matricesIndices[i];
  39469. floatIndices.push(matricesIndex & 0x000000FF);
  39470. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39471. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39472. floatIndices.push(matricesIndex >> 24);
  39473. }
  39474. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39475. }
  39476. else {
  39477. delete parsedGeometry.matricesIndices._isExpanded;
  39478. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39479. }
  39480. }
  39481. if (parsedGeometry.matricesIndicesExtra) {
  39482. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39483. var floatIndices = [];
  39484. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39485. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39486. floatIndices.push(matricesIndex & 0x000000FF);
  39487. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39488. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39489. floatIndices.push(matricesIndex >> 24);
  39490. }
  39491. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39492. }
  39493. else {
  39494. delete parsedGeometry.matricesIndices._isExpanded;
  39495. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39496. }
  39497. }
  39498. if (parsedGeometry.matricesWeights) {
  39499. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39500. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39501. }
  39502. if (parsedGeometry.matricesWeightsExtra) {
  39503. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39504. }
  39505. mesh.setIndices(parsedGeometry.indices, null);
  39506. }
  39507. // SubMeshes
  39508. if (parsedGeometry.subMeshes) {
  39509. mesh.subMeshes = [];
  39510. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39511. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39512. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39513. }
  39514. }
  39515. // Flat shading
  39516. if (mesh._shouldGenerateFlatShading) {
  39517. mesh.convertToFlatShadedMesh();
  39518. delete mesh._shouldGenerateFlatShading;
  39519. }
  39520. // Update
  39521. mesh.computeWorldMatrix(true);
  39522. // Octree
  39523. var sceneOctree = scene.selectionOctree;
  39524. if (sceneOctree !== undefined && sceneOctree !== null) {
  39525. sceneOctree.addMesh(mesh);
  39526. }
  39527. };
  39528. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39529. var epsilon = 1e-3;
  39530. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39531. return;
  39532. }
  39533. var noInfluenceBoneIndex = 0.0;
  39534. if (parsedGeometry.skeletonId > -1) {
  39535. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39536. if (!skeleton) {
  39537. return;
  39538. }
  39539. noInfluenceBoneIndex = skeleton.bones.length;
  39540. }
  39541. else {
  39542. return;
  39543. }
  39544. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39545. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39546. var matricesWeights = parsedGeometry.matricesWeights;
  39547. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39548. var influencers = parsedGeometry.numBoneInfluencer;
  39549. var size = matricesWeights.length;
  39550. for (var i = 0; i < size; i += 4) {
  39551. var weight = 0.0;
  39552. var firstZeroWeight = -1;
  39553. for (var j = 0; j < 4; j++) {
  39554. var w = matricesWeights[i + j];
  39555. weight += w;
  39556. if (w < epsilon && firstZeroWeight < 0) {
  39557. firstZeroWeight = j;
  39558. }
  39559. }
  39560. if (matricesWeightsExtra) {
  39561. for (var j = 0; j < 4; j++) {
  39562. var w = matricesWeightsExtra[i + j];
  39563. weight += w;
  39564. if (w < epsilon && firstZeroWeight < 0) {
  39565. firstZeroWeight = j + 4;
  39566. }
  39567. }
  39568. }
  39569. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39570. firstZeroWeight = influencers - 1;
  39571. }
  39572. if (weight > epsilon) {
  39573. var mweight = 1.0 / weight;
  39574. for (var j = 0; j < 4; j++) {
  39575. matricesWeights[i + j] *= mweight;
  39576. }
  39577. if (matricesWeightsExtra) {
  39578. for (var j = 0; j < 4; j++) {
  39579. matricesWeightsExtra[i + j] *= mweight;
  39580. }
  39581. }
  39582. }
  39583. else {
  39584. if (firstZeroWeight >= 4) {
  39585. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39586. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39587. }
  39588. else {
  39589. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39590. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39591. }
  39592. }
  39593. }
  39594. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39595. if (parsedGeometry.matricesWeightsExtra) {
  39596. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39597. }
  39598. };
  39599. /**
  39600. * Create a new geometry from persisted data (Using .babylon file format)
  39601. * @param parsedVertexData defines the persisted data
  39602. * @param scene defines the hosting scene
  39603. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39604. * @returns the new geometry object
  39605. */
  39606. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39607. if (scene.getGeometryByID(parsedVertexData.id)) {
  39608. return null; // null since geometry could be something else than a box...
  39609. }
  39610. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39611. if (BABYLON.Tags) {
  39612. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39613. }
  39614. if (parsedVertexData.delayLoadingFile) {
  39615. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39616. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39617. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39618. geometry._delayInfo = [];
  39619. if (parsedVertexData.hasUVs) {
  39620. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39621. }
  39622. if (parsedVertexData.hasUVs2) {
  39623. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39624. }
  39625. if (parsedVertexData.hasUVs3) {
  39626. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39627. }
  39628. if (parsedVertexData.hasUVs4) {
  39629. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39630. }
  39631. if (parsedVertexData.hasUVs5) {
  39632. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39633. }
  39634. if (parsedVertexData.hasUVs6) {
  39635. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39636. }
  39637. if (parsedVertexData.hasColors) {
  39638. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39639. }
  39640. if (parsedVertexData.hasMatricesIndices) {
  39641. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39642. }
  39643. if (parsedVertexData.hasMatricesWeights) {
  39644. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39645. }
  39646. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39647. }
  39648. else {
  39649. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39650. }
  39651. scene.pushGeometry(geometry, true);
  39652. return geometry;
  39653. };
  39654. return Geometry;
  39655. }());
  39656. BABYLON.Geometry = Geometry;
  39657. // Primitives
  39658. /// Abstract class
  39659. /**
  39660. * Abstract class used to provide common services for all typed geometries
  39661. * @hidden
  39662. */
  39663. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39664. __extends(_PrimitiveGeometry, _super);
  39665. /**
  39666. * Creates a new typed geometry
  39667. * @param id defines the unique ID of the geometry
  39668. * @param scene defines the hosting scene
  39669. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39670. * @param mesh defines the hosting mesh (can be null)
  39671. */
  39672. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39673. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39674. if (mesh === void 0) { mesh = null; }
  39675. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39676. _this._canBeRegenerated = _canBeRegenerated;
  39677. _this._beingRegenerated = true;
  39678. _this.regenerate();
  39679. _this._beingRegenerated = false;
  39680. return _this;
  39681. }
  39682. /**
  39683. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39684. * @returns true if the geometry can be regenerated
  39685. */
  39686. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39687. return this._canBeRegenerated;
  39688. };
  39689. /**
  39690. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39691. */
  39692. _PrimitiveGeometry.prototype.regenerate = function () {
  39693. if (!this._canBeRegenerated) {
  39694. return;
  39695. }
  39696. this._beingRegenerated = true;
  39697. this.setAllVerticesData(this._regenerateVertexData(), false);
  39698. this._beingRegenerated = false;
  39699. };
  39700. /**
  39701. * Clone the geometry
  39702. * @param id defines the unique ID of the new geometry
  39703. * @returns the new geometry
  39704. */
  39705. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39706. return _super.prototype.copy.call(this, id);
  39707. };
  39708. // overrides
  39709. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39710. if (!this._beingRegenerated) {
  39711. return;
  39712. }
  39713. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39714. };
  39715. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39716. if (!this._beingRegenerated) {
  39717. return;
  39718. }
  39719. _super.prototype.setVerticesData.call(this, kind, data, false);
  39720. };
  39721. // to override
  39722. /** @hidden */
  39723. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39724. throw new Error("Abstract method");
  39725. };
  39726. _PrimitiveGeometry.prototype.copy = function (id) {
  39727. throw new Error("Must be overriden in sub-classes.");
  39728. };
  39729. _PrimitiveGeometry.prototype.serialize = function () {
  39730. var serializationObject = _super.prototype.serialize.call(this);
  39731. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39732. return serializationObject;
  39733. };
  39734. return _PrimitiveGeometry;
  39735. }(Geometry));
  39736. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39737. /**
  39738. * Creates a ribbon geometry
  39739. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39740. */
  39741. var RibbonGeometry = /** @class */ (function (_super) {
  39742. __extends(RibbonGeometry, _super);
  39743. /**
  39744. * Creates a ribbon geometry
  39745. * @param id defines the unique ID of the geometry
  39746. * @param scene defines the hosting scene
  39747. * @param pathArray defines the array of paths to use
  39748. * @param closeArray defines if the last path and the first path must be joined
  39749. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39750. * @param offset defines the offset between points
  39751. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39752. * @param mesh defines the hosting mesh (can be null)
  39753. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39754. */
  39755. function RibbonGeometry(id, scene,
  39756. /**
  39757. * Defines the array of paths to use
  39758. */
  39759. pathArray,
  39760. /**
  39761. * Defines if the last and first points of each path in your pathArray must be joined
  39762. */
  39763. closeArray,
  39764. /**
  39765. * Defines if the last and first points of each path in your pathArray must be joined
  39766. */
  39767. closePath,
  39768. /**
  39769. * Defines the offset between points
  39770. */
  39771. offset, canBeRegenerated, mesh,
  39772. /**
  39773. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39774. */
  39775. side) {
  39776. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39777. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39778. _this.pathArray = pathArray;
  39779. _this.closeArray = closeArray;
  39780. _this.closePath = closePath;
  39781. _this.offset = offset;
  39782. _this.side = side;
  39783. return _this;
  39784. }
  39785. /** @hidden */
  39786. RibbonGeometry.prototype._regenerateVertexData = function () {
  39787. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39788. };
  39789. RibbonGeometry.prototype.copy = function (id) {
  39790. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39791. };
  39792. return RibbonGeometry;
  39793. }(_PrimitiveGeometry));
  39794. BABYLON.RibbonGeometry = RibbonGeometry;
  39795. /**
  39796. * Creates a box geometry
  39797. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39798. */
  39799. var BoxGeometry = /** @class */ (function (_super) {
  39800. __extends(BoxGeometry, _super);
  39801. /**
  39802. * Creates a box geometry
  39803. * @param id defines the unique ID of the geometry
  39804. * @param scene defines the hosting scene
  39805. * @param size defines the zise of the box (width, height and depth are the same)
  39806. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39807. * @param mesh defines the hosting mesh (can be null)
  39808. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39809. */
  39810. function BoxGeometry(id, scene,
  39811. /**
  39812. * Defines the zise of the box (width, height and depth are the same)
  39813. */
  39814. size, canBeRegenerated, mesh,
  39815. /**
  39816. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39817. */
  39818. side) {
  39819. if (mesh === void 0) { mesh = null; }
  39820. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39821. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39822. _this.size = size;
  39823. _this.side = side;
  39824. return _this;
  39825. }
  39826. BoxGeometry.prototype._regenerateVertexData = function () {
  39827. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39828. };
  39829. BoxGeometry.prototype.copy = function (id) {
  39830. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39831. };
  39832. BoxGeometry.prototype.serialize = function () {
  39833. var serializationObject = _super.prototype.serialize.call(this);
  39834. serializationObject.size = this.size;
  39835. return serializationObject;
  39836. };
  39837. BoxGeometry.Parse = function (parsedBox, scene) {
  39838. if (scene.getGeometryByID(parsedBox.id)) {
  39839. return null; // null since geometry could be something else than a box...
  39840. }
  39841. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39842. if (BABYLON.Tags) {
  39843. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39844. }
  39845. scene.pushGeometry(box, true);
  39846. return box;
  39847. };
  39848. return BoxGeometry;
  39849. }(_PrimitiveGeometry));
  39850. BABYLON.BoxGeometry = BoxGeometry;
  39851. /**
  39852. * Creates a sphere geometry
  39853. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39854. */
  39855. var SphereGeometry = /** @class */ (function (_super) {
  39856. __extends(SphereGeometry, _super);
  39857. /**
  39858. * Create a new sphere geometry
  39859. * @param id defines the unique ID of the geometry
  39860. * @param scene defines the hosting scene
  39861. * @param segments defines the number of segments to use to create the sphere
  39862. * @param diameter defines the diameter of the sphere
  39863. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39864. * @param mesh defines the hosting mesh (can be null)
  39865. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39866. */
  39867. function SphereGeometry(id, scene,
  39868. /**
  39869. * Defines the number of segments to use to create the sphere
  39870. */
  39871. segments,
  39872. /**
  39873. * Defines the diameter of the sphere
  39874. */
  39875. diameter, canBeRegenerated, mesh,
  39876. /**
  39877. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39878. */
  39879. side) {
  39880. if (mesh === void 0) { mesh = null; }
  39881. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39882. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39883. _this.segments = segments;
  39884. _this.diameter = diameter;
  39885. _this.side = side;
  39886. return _this;
  39887. }
  39888. SphereGeometry.prototype._regenerateVertexData = function () {
  39889. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39890. };
  39891. SphereGeometry.prototype.copy = function (id) {
  39892. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39893. };
  39894. SphereGeometry.prototype.serialize = function () {
  39895. var serializationObject = _super.prototype.serialize.call(this);
  39896. serializationObject.segments = this.segments;
  39897. serializationObject.diameter = this.diameter;
  39898. return serializationObject;
  39899. };
  39900. SphereGeometry.Parse = function (parsedSphere, scene) {
  39901. if (scene.getGeometryByID(parsedSphere.id)) {
  39902. return null; // null since geometry could be something else than a sphere...
  39903. }
  39904. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39905. if (BABYLON.Tags) {
  39906. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39907. }
  39908. scene.pushGeometry(sphere, true);
  39909. return sphere;
  39910. };
  39911. return SphereGeometry;
  39912. }(_PrimitiveGeometry));
  39913. BABYLON.SphereGeometry = SphereGeometry;
  39914. /**
  39915. * Creates a disc geometry
  39916. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39917. */
  39918. var DiscGeometry = /** @class */ (function (_super) {
  39919. __extends(DiscGeometry, _super);
  39920. /**
  39921. * Creates a new disc geometry
  39922. * @param id defines the unique ID of the geometry
  39923. * @param scene defines the hosting scene
  39924. * @param radius defines the radius of the disc
  39925. * @param tessellation defines the tesselation factor to apply to the disc
  39926. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39927. * @param mesh defines the hosting mesh (can be null)
  39928. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39929. */
  39930. function DiscGeometry(id, scene,
  39931. /**
  39932. * Defines the radius of the disc
  39933. */
  39934. radius,
  39935. /**
  39936. * Defines the tesselation factor to apply to the disc
  39937. */
  39938. tessellation, canBeRegenerated, mesh,
  39939. /**
  39940. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39941. */
  39942. side) {
  39943. if (mesh === void 0) { mesh = null; }
  39944. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39945. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39946. _this.radius = radius;
  39947. _this.tessellation = tessellation;
  39948. _this.side = side;
  39949. return _this;
  39950. }
  39951. DiscGeometry.prototype._regenerateVertexData = function () {
  39952. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  39953. };
  39954. DiscGeometry.prototype.copy = function (id) {
  39955. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  39956. };
  39957. return DiscGeometry;
  39958. }(_PrimitiveGeometry));
  39959. BABYLON.DiscGeometry = DiscGeometry;
  39960. /**
  39961. * Creates a new cylinder geometry
  39962. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  39963. */
  39964. var CylinderGeometry = /** @class */ (function (_super) {
  39965. __extends(CylinderGeometry, _super);
  39966. /**
  39967. * Creates a new cylinder geometry
  39968. * @param id defines the unique ID of the geometry
  39969. * @param scene defines the hosting scene
  39970. * @param height defines the height of the cylinder
  39971. * @param diameterTop defines the diameter of the cylinder's top cap
  39972. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  39973. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  39974. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  39975. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39976. * @param mesh defines the hosting mesh (can be null)
  39977. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39978. */
  39979. function CylinderGeometry(id, scene,
  39980. /**
  39981. * Defines the height of the cylinder
  39982. */
  39983. height,
  39984. /**
  39985. * Defines the diameter of the cylinder's top cap
  39986. */
  39987. diameterTop,
  39988. /**
  39989. * Defines the diameter of the cylinder's bottom cap
  39990. */
  39991. diameterBottom,
  39992. /**
  39993. * Defines the tessellation factor to apply to the cylinder
  39994. */
  39995. tessellation,
  39996. /**
  39997. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  39998. */
  39999. subdivisions, canBeRegenerated, mesh,
  40000. /**
  40001. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40002. */
  40003. side) {
  40004. if (subdivisions === void 0) { subdivisions = 1; }
  40005. if (mesh === void 0) { mesh = null; }
  40006. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40007. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40008. _this.height = height;
  40009. _this.diameterTop = diameterTop;
  40010. _this.diameterBottom = diameterBottom;
  40011. _this.tessellation = tessellation;
  40012. _this.subdivisions = subdivisions;
  40013. _this.side = side;
  40014. return _this;
  40015. }
  40016. CylinderGeometry.prototype._regenerateVertexData = function () {
  40017. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40018. };
  40019. CylinderGeometry.prototype.copy = function (id) {
  40020. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40021. };
  40022. CylinderGeometry.prototype.serialize = function () {
  40023. var serializationObject = _super.prototype.serialize.call(this);
  40024. serializationObject.height = this.height;
  40025. serializationObject.diameterTop = this.diameterTop;
  40026. serializationObject.diameterBottom = this.diameterBottom;
  40027. serializationObject.tessellation = this.tessellation;
  40028. return serializationObject;
  40029. };
  40030. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40031. if (scene.getGeometryByID(parsedCylinder.id)) {
  40032. return null; // null since geometry could be something else than a cylinder...
  40033. }
  40034. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40035. if (BABYLON.Tags) {
  40036. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40037. }
  40038. scene.pushGeometry(cylinder, true);
  40039. return cylinder;
  40040. };
  40041. return CylinderGeometry;
  40042. }(_PrimitiveGeometry));
  40043. BABYLON.CylinderGeometry = CylinderGeometry;
  40044. /**
  40045. * Creates a new torus geometry
  40046. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40047. */
  40048. var TorusGeometry = /** @class */ (function (_super) {
  40049. __extends(TorusGeometry, _super);
  40050. /**
  40051. * Creates a new torus geometry
  40052. * @param id defines the unique ID of the geometry
  40053. * @param scene defines the hosting scene
  40054. * @param diameter defines the diameter of the torus
  40055. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40056. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40057. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40058. * @param mesh defines the hosting mesh (can be null)
  40059. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40060. */
  40061. function TorusGeometry(id, scene,
  40062. /**
  40063. * Defines the diameter of the torus
  40064. */
  40065. diameter,
  40066. /**
  40067. * Defines the thickness of the torus (ie. internal diameter)
  40068. */
  40069. thickness,
  40070. /**
  40071. * Defines the tesselation factor to apply to the torus
  40072. */
  40073. tessellation, canBeRegenerated, mesh,
  40074. /**
  40075. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40076. */
  40077. side) {
  40078. if (mesh === void 0) { mesh = null; }
  40079. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40080. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40081. _this.diameter = diameter;
  40082. _this.thickness = thickness;
  40083. _this.tessellation = tessellation;
  40084. _this.side = side;
  40085. return _this;
  40086. }
  40087. TorusGeometry.prototype._regenerateVertexData = function () {
  40088. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40089. };
  40090. TorusGeometry.prototype.copy = function (id) {
  40091. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40092. };
  40093. TorusGeometry.prototype.serialize = function () {
  40094. var serializationObject = _super.prototype.serialize.call(this);
  40095. serializationObject.diameter = this.diameter;
  40096. serializationObject.thickness = this.thickness;
  40097. serializationObject.tessellation = this.tessellation;
  40098. return serializationObject;
  40099. };
  40100. TorusGeometry.Parse = function (parsedTorus, scene) {
  40101. if (scene.getGeometryByID(parsedTorus.id)) {
  40102. return null; // null since geometry could be something else than a torus...
  40103. }
  40104. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40105. if (BABYLON.Tags) {
  40106. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40107. }
  40108. scene.pushGeometry(torus, true);
  40109. return torus;
  40110. };
  40111. return TorusGeometry;
  40112. }(_PrimitiveGeometry));
  40113. BABYLON.TorusGeometry = TorusGeometry;
  40114. /**
  40115. * Creates a new ground geometry
  40116. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40117. */
  40118. var GroundGeometry = /** @class */ (function (_super) {
  40119. __extends(GroundGeometry, _super);
  40120. /**
  40121. * Creates a new ground geometry
  40122. * @param id defines the unique ID of the geometry
  40123. * @param scene defines the hosting scene
  40124. * @param width defines the width of the ground
  40125. * @param height defines the height of the ground
  40126. * @param subdivisions defines the subdivisions to apply to the ground
  40127. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40128. * @param mesh defines the hosting mesh (can be null)
  40129. */
  40130. function GroundGeometry(id, scene,
  40131. /**
  40132. * Defines the width of the ground
  40133. */
  40134. width,
  40135. /**
  40136. * Defines the height of the ground
  40137. */
  40138. height,
  40139. /**
  40140. * Defines the subdivisions to apply to the ground
  40141. */
  40142. subdivisions, canBeRegenerated, mesh) {
  40143. if (mesh === void 0) { mesh = null; }
  40144. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40145. _this.width = width;
  40146. _this.height = height;
  40147. _this.subdivisions = subdivisions;
  40148. return _this;
  40149. }
  40150. GroundGeometry.prototype._regenerateVertexData = function () {
  40151. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40152. };
  40153. GroundGeometry.prototype.copy = function (id) {
  40154. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40155. };
  40156. GroundGeometry.prototype.serialize = function () {
  40157. var serializationObject = _super.prototype.serialize.call(this);
  40158. serializationObject.width = this.width;
  40159. serializationObject.height = this.height;
  40160. serializationObject.subdivisions = this.subdivisions;
  40161. return serializationObject;
  40162. };
  40163. GroundGeometry.Parse = function (parsedGround, scene) {
  40164. if (scene.getGeometryByID(parsedGround.id)) {
  40165. return null; // null since geometry could be something else than a ground...
  40166. }
  40167. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40168. if (BABYLON.Tags) {
  40169. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40170. }
  40171. scene.pushGeometry(ground, true);
  40172. return ground;
  40173. };
  40174. return GroundGeometry;
  40175. }(_PrimitiveGeometry));
  40176. BABYLON.GroundGeometry = GroundGeometry;
  40177. /**
  40178. * Creates a tiled ground geometry
  40179. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40180. */
  40181. var TiledGroundGeometry = /** @class */ (function (_super) {
  40182. __extends(TiledGroundGeometry, _super);
  40183. /**
  40184. * Creates a tiled ground geometry
  40185. * @param id defines the unique ID of the geometry
  40186. * @param scene defines the hosting scene
  40187. * @param xmin defines the minimum value on X axis
  40188. * @param zmin defines the minimum value on Z axis
  40189. * @param xmax defines the maximum value on X axis
  40190. * @param zmax defines the maximum value on Z axis
  40191. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40192. * @param precision defines the precision to use when computing the tiles
  40193. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40194. * @param mesh defines the hosting mesh (can be null)
  40195. */
  40196. function TiledGroundGeometry(id, scene,
  40197. /**
  40198. * Defines the minimum value on X axis
  40199. */
  40200. xmin,
  40201. /**
  40202. * Defines the minimum value on Z axis
  40203. */
  40204. zmin,
  40205. /**
  40206. * Defines the maximum value on X axis
  40207. */
  40208. xmax,
  40209. /**
  40210. * Defines the maximum value on Z axis
  40211. */
  40212. zmax,
  40213. /**
  40214. * Defines the subdivisions to apply to the ground
  40215. */
  40216. subdivisions,
  40217. /**
  40218. * Defines the precision to use when computing the tiles
  40219. */
  40220. precision, canBeRegenerated, mesh) {
  40221. if (mesh === void 0) { mesh = null; }
  40222. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40223. _this.xmin = xmin;
  40224. _this.zmin = zmin;
  40225. _this.xmax = xmax;
  40226. _this.zmax = zmax;
  40227. _this.subdivisions = subdivisions;
  40228. _this.precision = precision;
  40229. return _this;
  40230. }
  40231. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40232. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40233. };
  40234. TiledGroundGeometry.prototype.copy = function (id) {
  40235. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40236. };
  40237. return TiledGroundGeometry;
  40238. }(_PrimitiveGeometry));
  40239. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40240. /**
  40241. * Creates a plane geometry
  40242. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40243. */
  40244. var PlaneGeometry = /** @class */ (function (_super) {
  40245. __extends(PlaneGeometry, _super);
  40246. /**
  40247. * Creates a plane geometry
  40248. * @param id defines the unique ID of the geometry
  40249. * @param scene defines the hosting scene
  40250. * @param size defines the size of the plane (width === height)
  40251. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40252. * @param mesh defines the hosting mesh (can be null)
  40253. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40254. */
  40255. function PlaneGeometry(id, scene,
  40256. /**
  40257. * Defines the size of the plane (width === height)
  40258. */
  40259. size, canBeRegenerated, mesh,
  40260. /**
  40261. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40262. */
  40263. side) {
  40264. if (mesh === void 0) { mesh = null; }
  40265. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40266. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40267. _this.size = size;
  40268. _this.side = side;
  40269. return _this;
  40270. }
  40271. PlaneGeometry.prototype._regenerateVertexData = function () {
  40272. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40273. };
  40274. PlaneGeometry.prototype.copy = function (id) {
  40275. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40276. };
  40277. PlaneGeometry.prototype.serialize = function () {
  40278. var serializationObject = _super.prototype.serialize.call(this);
  40279. serializationObject.size = this.size;
  40280. return serializationObject;
  40281. };
  40282. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40283. if (scene.getGeometryByID(parsedPlane.id)) {
  40284. return null; // null since geometry could be something else than a ground...
  40285. }
  40286. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40287. if (BABYLON.Tags) {
  40288. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40289. }
  40290. scene.pushGeometry(plane, true);
  40291. return plane;
  40292. };
  40293. return PlaneGeometry;
  40294. }(_PrimitiveGeometry));
  40295. BABYLON.PlaneGeometry = PlaneGeometry;
  40296. /**
  40297. * Creates a torus knot geometry
  40298. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40299. */
  40300. var TorusKnotGeometry = /** @class */ (function (_super) {
  40301. __extends(TorusKnotGeometry, _super);
  40302. /**
  40303. * Creates a torus knot geometry
  40304. * @param id defines the unique ID of the geometry
  40305. * @param scene defines the hosting scene
  40306. * @param radius defines the radius of the torus knot
  40307. * @param tube defines the thickness of the torus knot tube
  40308. * @param radialSegments defines the number of radial segments
  40309. * @param tubularSegments defines the number of tubular segments
  40310. * @param p defines the first number of windings
  40311. * @param q defines the second number of windings
  40312. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40313. * @param mesh defines the hosting mesh (can be null)
  40314. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40315. */
  40316. function TorusKnotGeometry(id, scene,
  40317. /**
  40318. * Defines the radius of the torus knot
  40319. */
  40320. radius,
  40321. /**
  40322. * Defines the thickness of the torus knot tube
  40323. */
  40324. tube,
  40325. /**
  40326. * Defines the number of radial segments
  40327. */
  40328. radialSegments,
  40329. /**
  40330. * Defines the number of tubular segments
  40331. */
  40332. tubularSegments,
  40333. /**
  40334. * Defines the first number of windings
  40335. */
  40336. p,
  40337. /**
  40338. * Defines the second number of windings
  40339. */
  40340. q, canBeRegenerated, mesh,
  40341. /**
  40342. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40343. */
  40344. side) {
  40345. if (mesh === void 0) { mesh = null; }
  40346. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40347. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40348. _this.radius = radius;
  40349. _this.tube = tube;
  40350. _this.radialSegments = radialSegments;
  40351. _this.tubularSegments = tubularSegments;
  40352. _this.p = p;
  40353. _this.q = q;
  40354. _this.side = side;
  40355. return _this;
  40356. }
  40357. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40358. 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 });
  40359. };
  40360. TorusKnotGeometry.prototype.copy = function (id) {
  40361. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40362. };
  40363. TorusKnotGeometry.prototype.serialize = function () {
  40364. var serializationObject = _super.prototype.serialize.call(this);
  40365. serializationObject.radius = this.radius;
  40366. serializationObject.tube = this.tube;
  40367. serializationObject.radialSegments = this.radialSegments;
  40368. serializationObject.tubularSegments = this.tubularSegments;
  40369. serializationObject.p = this.p;
  40370. serializationObject.q = this.q;
  40371. return serializationObject;
  40372. };
  40373. ;
  40374. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40375. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40376. return null; // null since geometry could be something else than a ground...
  40377. }
  40378. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40379. if (BABYLON.Tags) {
  40380. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40381. }
  40382. scene.pushGeometry(torusKnot, true);
  40383. return torusKnot;
  40384. };
  40385. return TorusKnotGeometry;
  40386. }(_PrimitiveGeometry));
  40387. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40388. //}
  40389. })(BABYLON || (BABYLON = {}));
  40390. //# sourceMappingURL=babylon.geometry.js.map
  40391. var BABYLON;
  40392. (function (BABYLON) {
  40393. /**
  40394. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40395. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40396. */
  40397. var PostProcessManager = /** @class */ (function () {
  40398. /**
  40399. * Creates a new instance PostProcess
  40400. * @param scene The scene that the post process is associated with.
  40401. */
  40402. function PostProcessManager(scene) {
  40403. this._vertexBuffers = {};
  40404. this._scene = scene;
  40405. }
  40406. PostProcessManager.prototype._prepareBuffers = function () {
  40407. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40408. return;
  40409. }
  40410. // VBO
  40411. var vertices = [];
  40412. vertices.push(1, 1);
  40413. vertices.push(-1, 1);
  40414. vertices.push(-1, -1);
  40415. vertices.push(1, -1);
  40416. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40417. this._buildIndexBuffer();
  40418. };
  40419. PostProcessManager.prototype._buildIndexBuffer = function () {
  40420. // Indices
  40421. var indices = [];
  40422. indices.push(0);
  40423. indices.push(1);
  40424. indices.push(2);
  40425. indices.push(0);
  40426. indices.push(2);
  40427. indices.push(3);
  40428. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40429. };
  40430. /**
  40431. * Rebuilds the vertex buffers of the manager.
  40432. */
  40433. PostProcessManager.prototype._rebuild = function () {
  40434. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40435. if (!vb) {
  40436. return;
  40437. }
  40438. vb._rebuild();
  40439. this._buildIndexBuffer();
  40440. };
  40441. // Methods
  40442. /**
  40443. * Prepares a frame to be run through a post process.
  40444. * @param sourceTexture The input texture to the post procesess. (default: null)
  40445. * @param postProcesses An array of post processes to be run. (default: null)
  40446. * @returns True if the post processes were able to be run.
  40447. */
  40448. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40449. if (sourceTexture === void 0) { sourceTexture = null; }
  40450. if (postProcesses === void 0) { postProcesses = null; }
  40451. var camera = this._scene.activeCamera;
  40452. if (!camera) {
  40453. return false;
  40454. }
  40455. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40456. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40457. return false;
  40458. }
  40459. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40460. return true;
  40461. };
  40462. /**
  40463. * Manually render a set of post processes to a texture.
  40464. * @param postProcesses An array of post processes to be run.
  40465. * @param targetTexture The target texture to render to.
  40466. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40467. */
  40468. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40469. if (targetTexture === void 0) { targetTexture = null; }
  40470. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40471. var engine = this._scene.getEngine();
  40472. for (var index = 0; index < postProcesses.length; index++) {
  40473. if (index < postProcesses.length - 1) {
  40474. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40475. }
  40476. else {
  40477. if (targetTexture) {
  40478. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40479. }
  40480. else {
  40481. engine.restoreDefaultFramebuffer();
  40482. }
  40483. }
  40484. var pp = postProcesses[index];
  40485. var effect = pp.apply();
  40486. if (effect) {
  40487. pp.onBeforeRenderObservable.notifyObservers(effect);
  40488. // VBOs
  40489. this._prepareBuffers();
  40490. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40491. // Draw order
  40492. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40493. pp.onAfterRenderObservable.notifyObservers(effect);
  40494. }
  40495. }
  40496. // Restore depth buffer
  40497. engine.setDepthBuffer(true);
  40498. engine.setDepthWrite(true);
  40499. };
  40500. /**
  40501. * Finalize the result of the output of the postprocesses.
  40502. * @param doNotPresent If true the result will not be displayed to the screen.
  40503. * @param targetTexture The target texture to render to.
  40504. * @param faceIndex The index of the face to bind the target texture to.
  40505. * @param postProcesses The array of post processes to render.
  40506. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40507. */
  40508. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40509. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40510. var camera = this._scene.activeCamera;
  40511. if (!camera) {
  40512. return;
  40513. }
  40514. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40515. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40516. return;
  40517. }
  40518. var engine = this._scene.getEngine();
  40519. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40520. var pp = postProcesses[index];
  40521. if (index < len - 1) {
  40522. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40523. }
  40524. else {
  40525. if (targetTexture) {
  40526. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40527. pp._outputTexture = targetTexture;
  40528. }
  40529. else {
  40530. engine.restoreDefaultFramebuffer();
  40531. pp._outputTexture = null;
  40532. }
  40533. }
  40534. if (doNotPresent) {
  40535. break;
  40536. }
  40537. var effect = pp.apply();
  40538. if (effect) {
  40539. pp.onBeforeRenderObservable.notifyObservers(effect);
  40540. // VBOs
  40541. this._prepareBuffers();
  40542. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40543. // Draw order
  40544. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40545. pp.onAfterRenderObservable.notifyObservers(effect);
  40546. }
  40547. }
  40548. // Restore states
  40549. engine.setDepthBuffer(true);
  40550. engine.setDepthWrite(true);
  40551. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40552. };
  40553. /**
  40554. * Disposes of the post process manager.
  40555. */
  40556. PostProcessManager.prototype.dispose = function () {
  40557. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40558. if (buffer) {
  40559. buffer.dispose();
  40560. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40561. }
  40562. if (this._indexBuffer) {
  40563. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40564. this._indexBuffer = null;
  40565. }
  40566. };
  40567. return PostProcessManager;
  40568. }());
  40569. BABYLON.PostProcessManager = PostProcessManager;
  40570. })(BABYLON || (BABYLON = {}));
  40571. //# sourceMappingURL=babylon.postProcessManager.js.map
  40572. var BABYLON;
  40573. (function (BABYLON) {
  40574. /**
  40575. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40576. */
  40577. var PerformanceMonitor = /** @class */ (function () {
  40578. /**
  40579. * constructor
  40580. * @param frameSampleSize The number of samples required to saturate the sliding window
  40581. */
  40582. function PerformanceMonitor(frameSampleSize) {
  40583. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40584. this._enabled = true;
  40585. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40586. }
  40587. /**
  40588. * Samples current frame
  40589. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40590. */
  40591. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40592. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40593. if (!this._enabled)
  40594. return;
  40595. if (this._lastFrameTimeMs != null) {
  40596. var dt = timeMs - this._lastFrameTimeMs;
  40597. this._rollingFrameTime.add(dt);
  40598. }
  40599. this._lastFrameTimeMs = timeMs;
  40600. };
  40601. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40602. /**
  40603. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40604. * @return Average frame time in milliseconds
  40605. */
  40606. get: function () {
  40607. return this._rollingFrameTime.average;
  40608. },
  40609. enumerable: true,
  40610. configurable: true
  40611. });
  40612. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40613. /**
  40614. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40615. * @return Frame time variance in milliseconds squared
  40616. */
  40617. get: function () {
  40618. return this._rollingFrameTime.variance;
  40619. },
  40620. enumerable: true,
  40621. configurable: true
  40622. });
  40623. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40624. /**
  40625. * Returns the frame time of the most recent frame
  40626. * @return Frame time in milliseconds
  40627. */
  40628. get: function () {
  40629. return this._rollingFrameTime.history(0);
  40630. },
  40631. enumerable: true,
  40632. configurable: true
  40633. });
  40634. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40635. /**
  40636. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40637. * @return Framerate in frames per second
  40638. */
  40639. get: function () {
  40640. return 1000.0 / this._rollingFrameTime.average;
  40641. },
  40642. enumerable: true,
  40643. configurable: true
  40644. });
  40645. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40646. /**
  40647. * Returns the average framerate in frames per second using the most recent frame time
  40648. * @return Framerate in frames per second
  40649. */
  40650. get: function () {
  40651. var history = this._rollingFrameTime.history(0);
  40652. if (history === 0) {
  40653. return 0;
  40654. }
  40655. return 1000.0 / history;
  40656. },
  40657. enumerable: true,
  40658. configurable: true
  40659. });
  40660. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40661. /**
  40662. * Returns true if enough samples have been taken to completely fill the sliding window
  40663. * @return true if saturated
  40664. */
  40665. get: function () {
  40666. return this._rollingFrameTime.isSaturated();
  40667. },
  40668. enumerable: true,
  40669. configurable: true
  40670. });
  40671. /**
  40672. * Enables contributions to the sliding window sample set
  40673. */
  40674. PerformanceMonitor.prototype.enable = function () {
  40675. this._enabled = true;
  40676. };
  40677. /**
  40678. * Disables contributions to the sliding window sample set
  40679. * Samples will not be interpolated over the disabled period
  40680. */
  40681. PerformanceMonitor.prototype.disable = function () {
  40682. this._enabled = false;
  40683. //clear last sample to avoid interpolating over the disabled period when next enabled
  40684. this._lastFrameTimeMs = null;
  40685. };
  40686. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40687. /**
  40688. * Returns true if sampling is enabled
  40689. * @return true if enabled
  40690. */
  40691. get: function () {
  40692. return this._enabled;
  40693. },
  40694. enumerable: true,
  40695. configurable: true
  40696. });
  40697. /**
  40698. * Resets performance monitor
  40699. */
  40700. PerformanceMonitor.prototype.reset = function () {
  40701. //clear last sample to avoid interpolating over the disabled period when next enabled
  40702. this._lastFrameTimeMs = null;
  40703. //wipe record
  40704. this._rollingFrameTime.reset();
  40705. };
  40706. return PerformanceMonitor;
  40707. }());
  40708. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40709. /**
  40710. * RollingAverage
  40711. *
  40712. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40713. */
  40714. var RollingAverage = /** @class */ (function () {
  40715. /**
  40716. * constructor
  40717. * @param length The number of samples required to saturate the sliding window
  40718. */
  40719. function RollingAverage(length) {
  40720. this._samples = new Array(length);
  40721. this.reset();
  40722. }
  40723. /**
  40724. * Adds a sample to the sample set
  40725. * @param v The sample value
  40726. */
  40727. RollingAverage.prototype.add = function (v) {
  40728. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40729. var delta;
  40730. //we need to check if we've already wrapped round
  40731. if (this.isSaturated()) {
  40732. //remove bottom of stack from mean
  40733. var bottomValue = this._samples[this._pos];
  40734. delta = bottomValue - this.average;
  40735. this.average -= delta / (this._sampleCount - 1);
  40736. this._m2 -= delta * (bottomValue - this.average);
  40737. }
  40738. else {
  40739. this._sampleCount++;
  40740. }
  40741. //add new value to mean
  40742. delta = v - this.average;
  40743. this.average += delta / (this._sampleCount);
  40744. this._m2 += delta * (v - this.average);
  40745. //set the new variance
  40746. this.variance = this._m2 / (this._sampleCount - 1);
  40747. this._samples[this._pos] = v;
  40748. this._pos++;
  40749. this._pos %= this._samples.length; //positive wrap around
  40750. };
  40751. /**
  40752. * Returns previously added values or null if outside of history or outside the sliding window domain
  40753. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40754. * @return Value previously recorded with add() or null if outside of range
  40755. */
  40756. RollingAverage.prototype.history = function (i) {
  40757. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40758. return 0;
  40759. }
  40760. var i0 = this._wrapPosition(this._pos - 1.0);
  40761. return this._samples[this._wrapPosition(i0 - i)];
  40762. };
  40763. /**
  40764. * Returns true if enough samples have been taken to completely fill the sliding window
  40765. * @return true if sample-set saturated
  40766. */
  40767. RollingAverage.prototype.isSaturated = function () {
  40768. return this._sampleCount >= this._samples.length;
  40769. };
  40770. /**
  40771. * Resets the rolling average (equivalent to 0 samples taken so far)
  40772. */
  40773. RollingAverage.prototype.reset = function () {
  40774. this.average = 0;
  40775. this.variance = 0;
  40776. this._sampleCount = 0;
  40777. this._pos = 0;
  40778. this._m2 = 0;
  40779. };
  40780. /**
  40781. * Wraps a value around the sample range boundaries
  40782. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40783. * @return Wrapped position in sample range
  40784. */
  40785. RollingAverage.prototype._wrapPosition = function (i) {
  40786. var max = this._samples.length;
  40787. return ((i % max) + max) % max;
  40788. };
  40789. return RollingAverage;
  40790. }());
  40791. BABYLON.RollingAverage = RollingAverage;
  40792. })(BABYLON || (BABYLON = {}));
  40793. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40794. var BABYLON;
  40795. (function (BABYLON) {
  40796. /**
  40797. * This groups together the common properties used for image processing either in direct forward pass
  40798. * or through post processing effect depending on the use of the image processing pipeline in your scene
  40799. * or not.
  40800. */
  40801. var ImageProcessingConfiguration = /** @class */ (function () {
  40802. function ImageProcessingConfiguration() {
  40803. /**
  40804. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  40805. */
  40806. this.colorCurves = new BABYLON.ColorCurves();
  40807. this._colorCurvesEnabled = false;
  40808. this._colorGradingEnabled = false;
  40809. this._colorGradingWithGreenDepth = true;
  40810. this._colorGradingBGR = true;
  40811. this._exposure = 1.0;
  40812. this._toneMappingEnabled = false;
  40813. this._contrast = 1.0;
  40814. /**
  40815. * Vignette stretch size.
  40816. */
  40817. this.vignetteStretch = 0;
  40818. /**
  40819. * Vignette centre X Offset.
  40820. */
  40821. this.vignetteCentreX = 0;
  40822. /**
  40823. * Vignette centre Y Offset.
  40824. */
  40825. this.vignetteCentreY = 0;
  40826. /**
  40827. * Vignette weight or intensity of the vignette effect.
  40828. */
  40829. this.vignetteWeight = 1.5;
  40830. /**
  40831. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  40832. * if vignetteEnabled is set to true.
  40833. */
  40834. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  40835. /**
  40836. * Camera field of view used by the Vignette effect.
  40837. */
  40838. this.vignetteCameraFov = 0.5;
  40839. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  40840. this._vignetteEnabled = false;
  40841. this._applyByPostProcess = false;
  40842. this._isEnabled = true;
  40843. /**
  40844. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  40845. */
  40846. this.onUpdateParameters = new BABYLON.Observable();
  40847. }
  40848. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  40849. /**
  40850. * Gets wether the color curves effect is enabled.
  40851. */
  40852. get: function () {
  40853. return this._colorCurvesEnabled;
  40854. },
  40855. /**
  40856. * Sets wether the color curves effect is enabled.
  40857. */
  40858. set: function (value) {
  40859. if (this._colorCurvesEnabled === value) {
  40860. return;
  40861. }
  40862. this._colorCurvesEnabled = value;
  40863. this._updateParameters();
  40864. },
  40865. enumerable: true,
  40866. configurable: true
  40867. });
  40868. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  40869. /**
  40870. * Gets wether the color grading effect is enabled.
  40871. */
  40872. get: function () {
  40873. return this._colorGradingEnabled;
  40874. },
  40875. /**
  40876. * Sets wether the color grading effect is enabled.
  40877. */
  40878. set: function (value) {
  40879. if (this._colorGradingEnabled === value) {
  40880. return;
  40881. }
  40882. this._colorGradingEnabled = value;
  40883. this._updateParameters();
  40884. },
  40885. enumerable: true,
  40886. configurable: true
  40887. });
  40888. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  40889. /**
  40890. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  40891. */
  40892. get: function () {
  40893. return this._colorGradingWithGreenDepth;
  40894. },
  40895. /**
  40896. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  40897. */
  40898. set: function (value) {
  40899. if (this._colorGradingWithGreenDepth === value) {
  40900. return;
  40901. }
  40902. this._colorGradingWithGreenDepth = value;
  40903. this._updateParameters();
  40904. },
  40905. enumerable: true,
  40906. configurable: true
  40907. });
  40908. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  40909. /**
  40910. * Gets wether the color grading texture contains BGR values.
  40911. */
  40912. get: function () {
  40913. return this._colorGradingBGR;
  40914. },
  40915. /**
  40916. * Sets wether the color grading texture contains BGR values.
  40917. */
  40918. set: function (value) {
  40919. if (this._colorGradingBGR === value) {
  40920. return;
  40921. }
  40922. this._colorGradingBGR = value;
  40923. this._updateParameters();
  40924. },
  40925. enumerable: true,
  40926. configurable: true
  40927. });
  40928. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  40929. /**
  40930. * Gets the Exposure used in the effect.
  40931. */
  40932. get: function () {
  40933. return this._exposure;
  40934. },
  40935. /**
  40936. * Sets the Exposure used in the effect.
  40937. */
  40938. set: function (value) {
  40939. if (this._exposure === value) {
  40940. return;
  40941. }
  40942. this._exposure = value;
  40943. this._updateParameters();
  40944. },
  40945. enumerable: true,
  40946. configurable: true
  40947. });
  40948. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  40949. /**
  40950. * Gets wether the tone mapping effect is enabled.
  40951. */
  40952. get: function () {
  40953. return this._toneMappingEnabled;
  40954. },
  40955. /**
  40956. * Sets wether the tone mapping effect is enabled.
  40957. */
  40958. set: function (value) {
  40959. if (this._toneMappingEnabled === value) {
  40960. return;
  40961. }
  40962. this._toneMappingEnabled = value;
  40963. this._updateParameters();
  40964. },
  40965. enumerable: true,
  40966. configurable: true
  40967. });
  40968. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  40969. /**
  40970. * Gets the contrast used in the effect.
  40971. */
  40972. get: function () {
  40973. return this._contrast;
  40974. },
  40975. /**
  40976. * Sets the contrast used in the effect.
  40977. */
  40978. set: function (value) {
  40979. if (this._contrast === value) {
  40980. return;
  40981. }
  40982. this._contrast = value;
  40983. this._updateParameters();
  40984. },
  40985. enumerable: true,
  40986. configurable: true
  40987. });
  40988. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  40989. /**
  40990. * Gets the vignette blend mode allowing different kind of effect.
  40991. */
  40992. get: function () {
  40993. return this._vignetteBlendMode;
  40994. },
  40995. /**
  40996. * Sets the vignette blend mode allowing different kind of effect.
  40997. */
  40998. set: function (value) {
  40999. if (this._vignetteBlendMode === value) {
  41000. return;
  41001. }
  41002. this._vignetteBlendMode = value;
  41003. this._updateParameters();
  41004. },
  41005. enumerable: true,
  41006. configurable: true
  41007. });
  41008. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  41009. /**
  41010. * Gets wether the vignette effect is enabled.
  41011. */
  41012. get: function () {
  41013. return this._vignetteEnabled;
  41014. },
  41015. /**
  41016. * Sets wether the vignette effect is enabled.
  41017. */
  41018. set: function (value) {
  41019. if (this._vignetteEnabled === value) {
  41020. return;
  41021. }
  41022. this._vignetteEnabled = value;
  41023. this._updateParameters();
  41024. },
  41025. enumerable: true,
  41026. configurable: true
  41027. });
  41028. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  41029. /**
  41030. * Gets wether the image processing is applied through a post process or not.
  41031. */
  41032. get: function () {
  41033. return this._applyByPostProcess;
  41034. },
  41035. /**
  41036. * Sets wether the image processing is applied through a post process or not.
  41037. */
  41038. set: function (value) {
  41039. if (this._applyByPostProcess === value) {
  41040. return;
  41041. }
  41042. this._applyByPostProcess = value;
  41043. this._updateParameters();
  41044. },
  41045. enumerable: true,
  41046. configurable: true
  41047. });
  41048. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  41049. /**
  41050. * Gets wether the image processing is enabled or not.
  41051. */
  41052. get: function () {
  41053. return this._isEnabled;
  41054. },
  41055. /**
  41056. * Sets wether the image processing is enabled or not.
  41057. */
  41058. set: function (value) {
  41059. if (this._isEnabled === value) {
  41060. return;
  41061. }
  41062. this._isEnabled = value;
  41063. this._updateParameters();
  41064. },
  41065. enumerable: true,
  41066. configurable: true
  41067. });
  41068. /**
  41069. * Method called each time the image processing information changes requires to recompile the effect.
  41070. */
  41071. ImageProcessingConfiguration.prototype._updateParameters = function () {
  41072. this.onUpdateParameters.notifyObservers(this);
  41073. };
  41074. ImageProcessingConfiguration.prototype.getClassName = function () {
  41075. return "ImageProcessingConfiguration";
  41076. };
  41077. /**
  41078. * Prepare the list of uniforms associated with the Image Processing effects.
  41079. * @param uniformsList The list of uniforms used in the effect
  41080. * @param defines the list of defines currently in use
  41081. */
  41082. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  41083. if (defines.EXPOSURE) {
  41084. uniforms.push("exposureLinear");
  41085. }
  41086. if (defines.CONTRAST) {
  41087. uniforms.push("contrast");
  41088. }
  41089. if (defines.COLORGRADING) {
  41090. uniforms.push("colorTransformSettings");
  41091. }
  41092. if (defines.VIGNETTE) {
  41093. uniforms.push("vInverseScreenSize");
  41094. uniforms.push("vignetteSettings1");
  41095. uniforms.push("vignetteSettings2");
  41096. }
  41097. if (defines.COLORCURVES) {
  41098. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  41099. }
  41100. };
  41101. /**
  41102. * Prepare the list of samplers associated with the Image Processing effects.
  41103. * @param uniformsList The list of uniforms used in the effect
  41104. * @param defines the list of defines currently in use
  41105. */
  41106. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  41107. if (defines.COLORGRADING) {
  41108. samplersList.push("txColorTransform");
  41109. }
  41110. };
  41111. /**
  41112. * Prepare the list of defines associated to the shader.
  41113. * @param defines the list of defines to complete
  41114. */
  41115. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  41116. if (forPostProcess === void 0) { forPostProcess = false; }
  41117. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  41118. defines.VIGNETTE = false;
  41119. defines.TONEMAPPING = false;
  41120. defines.CONTRAST = false;
  41121. defines.EXPOSURE = false;
  41122. defines.COLORCURVES = false;
  41123. defines.COLORGRADING = false;
  41124. defines.COLORGRADING3D = false;
  41125. defines.IMAGEPROCESSING = false;
  41126. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  41127. return;
  41128. }
  41129. defines.VIGNETTE = this.vignetteEnabled;
  41130. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41131. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41132. defines.TONEMAPPING = this.toneMappingEnabled;
  41133. defines.CONTRAST = (this.contrast !== 1.0);
  41134. defines.EXPOSURE = (this.exposure !== 1.0);
  41135. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41136. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41137. if (defines.COLORGRADING) {
  41138. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  41139. }
  41140. else {
  41141. defines.COLORGRADING3D = false;
  41142. }
  41143. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41144. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41145. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41146. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41147. };
  41148. /**
  41149. * Returns true if all the image processing information are ready.
  41150. */
  41151. ImageProcessingConfiguration.prototype.isReady = function () {
  41152. // Color Grading texure can not be none blocking.
  41153. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41154. };
  41155. /**
  41156. * Binds the image processing to the shader.
  41157. * @param effect The effect to bind to
  41158. */
  41159. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41160. if (aspectRatio === void 0) { aspectRatio = 1; }
  41161. // Color Curves
  41162. if (this._colorCurvesEnabled && this.colorCurves) {
  41163. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41164. }
  41165. // Vignette
  41166. if (this._vignetteEnabled) {
  41167. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41168. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41169. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41170. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41171. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41172. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41173. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41174. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41175. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41176. var vignettePower = -2.0 * this.vignetteWeight;
  41177. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41178. }
  41179. // Exposure
  41180. effect.setFloat("exposureLinear", this.exposure);
  41181. // Contrast
  41182. effect.setFloat("contrast", this.contrast);
  41183. // Color transform settings
  41184. if (this.colorGradingTexture) {
  41185. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41186. var textureSize = this.colorGradingTexture.getSize().height;
  41187. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41188. 0.5 / textureSize, // textureOffset
  41189. textureSize, // textureSize
  41190. this.colorGradingTexture.level // weight
  41191. );
  41192. }
  41193. };
  41194. /**
  41195. * Clones the current image processing instance.
  41196. * @return The cloned image processing
  41197. */
  41198. ImageProcessingConfiguration.prototype.clone = function () {
  41199. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41200. };
  41201. /**
  41202. * Serializes the current image processing instance to a json representation.
  41203. * @return a JSON representation
  41204. */
  41205. ImageProcessingConfiguration.prototype.serialize = function () {
  41206. return BABYLON.SerializationHelper.Serialize(this);
  41207. };
  41208. /**
  41209. * Parses the image processing from a json representation.
  41210. * @param source the JSON source to parse
  41211. * @return The parsed image processing
  41212. */
  41213. ImageProcessingConfiguration.Parse = function (source) {
  41214. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41215. };
  41216. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41217. /**
  41218. * Used to apply the vignette as a mix with the pixel color.
  41219. */
  41220. get: function () {
  41221. return this._VIGNETTEMODE_MULTIPLY;
  41222. },
  41223. enumerable: true,
  41224. configurable: true
  41225. });
  41226. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41227. /**
  41228. * Used to apply the vignette as a replacement of the pixel color.
  41229. */
  41230. get: function () {
  41231. return this._VIGNETTEMODE_OPAQUE;
  41232. },
  41233. enumerable: true,
  41234. configurable: true
  41235. });
  41236. // Static constants associated to the image processing.
  41237. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41238. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41239. __decorate([
  41240. BABYLON.serializeAsColorCurves()
  41241. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41242. __decorate([
  41243. BABYLON.serialize()
  41244. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41245. __decorate([
  41246. BABYLON.serializeAsTexture()
  41247. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41248. __decorate([
  41249. BABYLON.serialize()
  41250. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41251. __decorate([
  41252. BABYLON.serialize()
  41253. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41254. __decorate([
  41255. BABYLON.serialize()
  41256. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41257. __decorate([
  41258. BABYLON.serialize()
  41259. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41260. __decorate([
  41261. BABYLON.serialize()
  41262. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41263. __decorate([
  41264. BABYLON.serialize()
  41265. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41266. __decorate([
  41267. BABYLON.serialize()
  41268. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41269. __decorate([
  41270. BABYLON.serialize()
  41271. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41272. __decorate([
  41273. BABYLON.serialize()
  41274. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41275. __decorate([
  41276. BABYLON.serialize()
  41277. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41278. __decorate([
  41279. BABYLON.serializeAsColor4()
  41280. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41281. __decorate([
  41282. BABYLON.serialize()
  41283. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41284. __decorate([
  41285. BABYLON.serialize()
  41286. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41287. __decorate([
  41288. BABYLON.serialize()
  41289. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41290. __decorate([
  41291. BABYLON.serialize()
  41292. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41293. __decorate([
  41294. BABYLON.serialize()
  41295. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41296. return ImageProcessingConfiguration;
  41297. }());
  41298. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41299. })(BABYLON || (BABYLON = {}));
  41300. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41301. var BABYLON;
  41302. (function (BABYLON) {
  41303. /**
  41304. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41305. * It can help converting any input color in a desired output one. This can then be used to create effects
  41306. * from sepia, black and white to sixties or futuristic rendering...
  41307. *
  41308. * The only supported format is currently 3dl.
  41309. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41310. */
  41311. var ColorGradingTexture = /** @class */ (function (_super) {
  41312. __extends(ColorGradingTexture, _super);
  41313. /**
  41314. * Instantiates a ColorGradingTexture from the following parameters.
  41315. *
  41316. * @param url The location of the color gradind data (currently only supporting 3dl)
  41317. * @param scene The scene the texture will be used in
  41318. */
  41319. function ColorGradingTexture(url, scene) {
  41320. var _this = _super.call(this, scene) || this;
  41321. if (!url) {
  41322. return _this;
  41323. }
  41324. _this._engine = scene.getEngine();
  41325. _this._textureMatrix = BABYLON.Matrix.Identity();
  41326. _this.name = url;
  41327. _this.url = url;
  41328. _this.hasAlpha = false;
  41329. _this.isCube = false;
  41330. _this.is3D = _this._engine.webGLVersion > 1;
  41331. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41332. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41333. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41334. _this.anisotropicFilteringLevel = 1;
  41335. _this._texture = _this._getFromCache(url, true);
  41336. if (!_this._texture) {
  41337. if (!scene.useDelayedTextureLoading) {
  41338. _this.loadTexture();
  41339. }
  41340. else {
  41341. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41342. }
  41343. }
  41344. return _this;
  41345. }
  41346. /**
  41347. * Returns the texture matrix used in most of the material.
  41348. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41349. */
  41350. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41351. return this._textureMatrix;
  41352. };
  41353. /**
  41354. * Occurs when the file being loaded is a .3dl LUT file.
  41355. */
  41356. ColorGradingTexture.prototype.load3dlTexture = function () {
  41357. var engine = this._engine;
  41358. var texture;
  41359. if (engine.webGLVersion === 1) {
  41360. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41361. }
  41362. else {
  41363. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41364. }
  41365. this._texture = texture;
  41366. var callback = function (text) {
  41367. if (typeof text !== "string") {
  41368. return;
  41369. }
  41370. var data = null;
  41371. var tempData = null;
  41372. var line;
  41373. var lines = text.split('\n');
  41374. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41375. var maxColor = 0;
  41376. for (var i = 0; i < lines.length; i++) {
  41377. line = lines[i];
  41378. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41379. continue;
  41380. if (line.indexOf('#') === 0)
  41381. continue;
  41382. var words = line.split(" ");
  41383. if (size === 0) {
  41384. // Number of space + one
  41385. size = words.length;
  41386. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41387. tempData = new Float32Array(size * size * size * 4);
  41388. continue;
  41389. }
  41390. if (size != 0) {
  41391. var r = Math.max(parseInt(words[0]), 0);
  41392. var g = Math.max(parseInt(words[1]), 0);
  41393. var b = Math.max(parseInt(words[2]), 0);
  41394. maxColor = Math.max(r, maxColor);
  41395. maxColor = Math.max(g, maxColor);
  41396. maxColor = Math.max(b, maxColor);
  41397. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41398. if (tempData) {
  41399. tempData[pixelStorageIndex + 0] = r;
  41400. tempData[pixelStorageIndex + 1] = g;
  41401. tempData[pixelStorageIndex + 2] = b;
  41402. }
  41403. pixelIndexSlice++;
  41404. if (pixelIndexSlice % size == 0) {
  41405. pixelIndexH++;
  41406. pixelIndexSlice = 0;
  41407. if (pixelIndexH % size == 0) {
  41408. pixelIndexW++;
  41409. pixelIndexH = 0;
  41410. }
  41411. }
  41412. }
  41413. }
  41414. if (tempData && data) {
  41415. for (var i = 0; i < tempData.length; i++) {
  41416. if (i > 0 && (i + 1) % 4 === 0) {
  41417. data[i] = 255;
  41418. }
  41419. else {
  41420. var value = tempData[i];
  41421. data[i] = (value / maxColor * 255);
  41422. }
  41423. }
  41424. }
  41425. if (texture.is3D) {
  41426. texture.updateSize(size, size, size);
  41427. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41428. }
  41429. else {
  41430. texture.updateSize(size * size, size);
  41431. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41432. }
  41433. };
  41434. var scene = this.getScene();
  41435. if (scene) {
  41436. scene._loadFile(this.url, callback);
  41437. }
  41438. else {
  41439. this._engine._loadFile(this.url, callback);
  41440. }
  41441. return this._texture;
  41442. };
  41443. /**
  41444. * Starts the loading process of the texture.
  41445. */
  41446. ColorGradingTexture.prototype.loadTexture = function () {
  41447. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41448. this.load3dlTexture();
  41449. }
  41450. };
  41451. /**
  41452. * Clones the color gradind texture.
  41453. */
  41454. ColorGradingTexture.prototype.clone = function () {
  41455. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41456. // Base texture
  41457. newTexture.level = this.level;
  41458. return newTexture;
  41459. };
  41460. /**
  41461. * Called during delayed load for textures.
  41462. */
  41463. ColorGradingTexture.prototype.delayLoad = function () {
  41464. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41465. return;
  41466. }
  41467. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41468. this._texture = this._getFromCache(this.url, true);
  41469. if (!this._texture) {
  41470. this.loadTexture();
  41471. }
  41472. };
  41473. /**
  41474. * Parses a color grading texture serialized by Babylon.
  41475. * @param parsedTexture The texture information being parsedTexture
  41476. * @param scene The scene to load the texture in
  41477. * @param rootUrl The root url of the data assets to load
  41478. * @return A color gradind texture
  41479. */
  41480. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41481. var texture = null;
  41482. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41483. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41484. texture.name = parsedTexture.name;
  41485. texture.level = parsedTexture.level;
  41486. }
  41487. return texture;
  41488. };
  41489. /**
  41490. * Serializes the LUT texture to json format.
  41491. */
  41492. ColorGradingTexture.prototype.serialize = function () {
  41493. if (!this.name) {
  41494. return null;
  41495. }
  41496. var serializationObject = {};
  41497. serializationObject.name = this.name;
  41498. serializationObject.level = this.level;
  41499. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41500. return serializationObject;
  41501. };
  41502. /**
  41503. * Empty line regex stored for GC.
  41504. */
  41505. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41506. return ColorGradingTexture;
  41507. }(BABYLON.BaseTexture));
  41508. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41509. })(BABYLON || (BABYLON = {}));
  41510. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41511. var BABYLON;
  41512. (function (BABYLON) {
  41513. /**
  41514. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41515. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41516. * 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;
  41517. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41518. */
  41519. var ColorCurves = /** @class */ (function () {
  41520. function ColorCurves() {
  41521. this._dirty = true;
  41522. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41523. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41524. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41525. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41526. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41527. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41528. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41529. this._globalHue = 30;
  41530. this._globalDensity = 0;
  41531. this._globalSaturation = 0;
  41532. this._globalExposure = 0;
  41533. this._highlightsHue = 30;
  41534. this._highlightsDensity = 0;
  41535. this._highlightsSaturation = 0;
  41536. this._highlightsExposure = 0;
  41537. this._midtonesHue = 30;
  41538. this._midtonesDensity = 0;
  41539. this._midtonesSaturation = 0;
  41540. this._midtonesExposure = 0;
  41541. this._shadowsHue = 30;
  41542. this._shadowsDensity = 0;
  41543. this._shadowsSaturation = 0;
  41544. this._shadowsExposure = 0;
  41545. }
  41546. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41547. /**
  41548. * Gets the global Hue value.
  41549. * 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).
  41550. */
  41551. get: function () {
  41552. return this._globalHue;
  41553. },
  41554. /**
  41555. * Sets the global Hue value.
  41556. * 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).
  41557. */
  41558. set: function (value) {
  41559. this._globalHue = value;
  41560. this._dirty = true;
  41561. },
  41562. enumerable: true,
  41563. configurable: true
  41564. });
  41565. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41566. /**
  41567. * Gets the global Density value.
  41568. * 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.
  41569. * Values less than zero provide a filter of opposite hue.
  41570. */
  41571. get: function () {
  41572. return this._globalDensity;
  41573. },
  41574. /**
  41575. * Sets the global Density value.
  41576. * 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.
  41577. * Values less than zero provide a filter of opposite hue.
  41578. */
  41579. set: function (value) {
  41580. this._globalDensity = value;
  41581. this._dirty = true;
  41582. },
  41583. enumerable: true,
  41584. configurable: true
  41585. });
  41586. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41587. /**
  41588. * Gets the global Saturation value.
  41589. * 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.
  41590. */
  41591. get: function () {
  41592. return this._globalSaturation;
  41593. },
  41594. /**
  41595. * Sets the global Saturation value.
  41596. * 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.
  41597. */
  41598. set: function (value) {
  41599. this._globalSaturation = value;
  41600. this._dirty = true;
  41601. },
  41602. enumerable: true,
  41603. configurable: true
  41604. });
  41605. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41606. /**
  41607. * Gets the highlights Hue value.
  41608. * 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).
  41609. */
  41610. get: function () {
  41611. return this._highlightsHue;
  41612. },
  41613. /**
  41614. * Sets the highlights Hue value.
  41615. * 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).
  41616. */
  41617. set: function (value) {
  41618. this._highlightsHue = value;
  41619. this._dirty = true;
  41620. },
  41621. enumerable: true,
  41622. configurable: true
  41623. });
  41624. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41625. /**
  41626. * Gets the highlights Density value.
  41627. * 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.
  41628. * Values less than zero provide a filter of opposite hue.
  41629. */
  41630. get: function () {
  41631. return this._highlightsDensity;
  41632. },
  41633. /**
  41634. * Sets the highlights Density value.
  41635. * 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.
  41636. * Values less than zero provide a filter of opposite hue.
  41637. */
  41638. set: function (value) {
  41639. this._highlightsDensity = value;
  41640. this._dirty = true;
  41641. },
  41642. enumerable: true,
  41643. configurable: true
  41644. });
  41645. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41646. /**
  41647. * Gets the highlights Saturation value.
  41648. * 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.
  41649. */
  41650. get: function () {
  41651. return this._highlightsSaturation;
  41652. },
  41653. /**
  41654. * Sets the highlights Saturation value.
  41655. * 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.
  41656. */
  41657. set: function (value) {
  41658. this._highlightsSaturation = value;
  41659. this._dirty = true;
  41660. },
  41661. enumerable: true,
  41662. configurable: true
  41663. });
  41664. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41665. /**
  41666. * Gets the highlights Exposure value.
  41667. * 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.
  41668. */
  41669. get: function () {
  41670. return this._highlightsExposure;
  41671. },
  41672. /**
  41673. * Sets the highlights Exposure value.
  41674. * 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.
  41675. */
  41676. set: function (value) {
  41677. this._highlightsExposure = value;
  41678. this._dirty = true;
  41679. },
  41680. enumerable: true,
  41681. configurable: true
  41682. });
  41683. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41684. /**
  41685. * Gets the midtones Hue value.
  41686. * 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).
  41687. */
  41688. get: function () {
  41689. return this._midtonesHue;
  41690. },
  41691. /**
  41692. * Sets the midtones Hue value.
  41693. * 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).
  41694. */
  41695. set: function (value) {
  41696. this._midtonesHue = value;
  41697. this._dirty = true;
  41698. },
  41699. enumerable: true,
  41700. configurable: true
  41701. });
  41702. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41703. /**
  41704. * Gets the midtones Density value.
  41705. * 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.
  41706. * Values less than zero provide a filter of opposite hue.
  41707. */
  41708. get: function () {
  41709. return this._midtonesDensity;
  41710. },
  41711. /**
  41712. * Sets the midtones Density value.
  41713. * 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.
  41714. * Values less than zero provide a filter of opposite hue.
  41715. */
  41716. set: function (value) {
  41717. this._midtonesDensity = value;
  41718. this._dirty = true;
  41719. },
  41720. enumerable: true,
  41721. configurable: true
  41722. });
  41723. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41724. /**
  41725. * Gets the midtones Saturation value.
  41726. * 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.
  41727. */
  41728. get: function () {
  41729. return this._midtonesSaturation;
  41730. },
  41731. /**
  41732. * Sets the midtones Saturation value.
  41733. * 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.
  41734. */
  41735. set: function (value) {
  41736. this._midtonesSaturation = value;
  41737. this._dirty = true;
  41738. },
  41739. enumerable: true,
  41740. configurable: true
  41741. });
  41742. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41743. /**
  41744. * Gets the midtones Exposure value.
  41745. * 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.
  41746. */
  41747. get: function () {
  41748. return this._midtonesExposure;
  41749. },
  41750. /**
  41751. * Sets the midtones Exposure value.
  41752. * 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.
  41753. */
  41754. set: function (value) {
  41755. this._midtonesExposure = value;
  41756. this._dirty = true;
  41757. },
  41758. enumerable: true,
  41759. configurable: true
  41760. });
  41761. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41762. /**
  41763. * Gets the shadows Hue value.
  41764. * 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).
  41765. */
  41766. get: function () {
  41767. return this._shadowsHue;
  41768. },
  41769. /**
  41770. * Sets the shadows Hue value.
  41771. * 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).
  41772. */
  41773. set: function (value) {
  41774. this._shadowsHue = value;
  41775. this._dirty = true;
  41776. },
  41777. enumerable: true,
  41778. configurable: true
  41779. });
  41780. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41781. /**
  41782. * Gets the shadows Density value.
  41783. * 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.
  41784. * Values less than zero provide a filter of opposite hue.
  41785. */
  41786. get: function () {
  41787. return this._shadowsDensity;
  41788. },
  41789. /**
  41790. * Sets the shadows Density value.
  41791. * 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.
  41792. * Values less than zero provide a filter of opposite hue.
  41793. */
  41794. set: function (value) {
  41795. this._shadowsDensity = value;
  41796. this._dirty = true;
  41797. },
  41798. enumerable: true,
  41799. configurable: true
  41800. });
  41801. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  41802. /**
  41803. * Gets the shadows Saturation value.
  41804. * 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.
  41805. */
  41806. get: function () {
  41807. return this._shadowsSaturation;
  41808. },
  41809. /**
  41810. * Sets the shadows Saturation value.
  41811. * 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.
  41812. */
  41813. set: function (value) {
  41814. this._shadowsSaturation = value;
  41815. this._dirty = true;
  41816. },
  41817. enumerable: true,
  41818. configurable: true
  41819. });
  41820. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  41821. /**
  41822. * Gets the shadows Exposure value.
  41823. * 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.
  41824. */
  41825. get: function () {
  41826. return this._shadowsExposure;
  41827. },
  41828. /**
  41829. * Sets the shadows Exposure value.
  41830. * 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.
  41831. */
  41832. set: function (value) {
  41833. this._shadowsExposure = value;
  41834. this._dirty = true;
  41835. },
  41836. enumerable: true,
  41837. configurable: true
  41838. });
  41839. ColorCurves.prototype.getClassName = function () {
  41840. return "ColorCurves";
  41841. };
  41842. /**
  41843. * Binds the color curves to the shader.
  41844. * @param colorCurves The color curve to bind
  41845. * @param effect The effect to bind to
  41846. */
  41847. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  41848. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  41849. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  41850. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  41851. if (colorCurves._dirty) {
  41852. colorCurves._dirty = false;
  41853. // Fill in global info.
  41854. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  41855. // Compute highlights info.
  41856. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  41857. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  41858. // Compute midtones info.
  41859. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  41860. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  41861. // Compute shadows info.
  41862. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  41863. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  41864. // Compute deltas (neutral is midtones).
  41865. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  41866. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  41867. }
  41868. if (effect) {
  41869. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  41870. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  41871. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  41872. }
  41873. };
  41874. /**
  41875. * Prepare the list of uniforms associated with the ColorCurves effects.
  41876. * @param uniformsList The list of uniforms used in the effect
  41877. */
  41878. ColorCurves.PrepareUniforms = function (uniformsList) {
  41879. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  41880. };
  41881. /**
  41882. * Returns color grading data based on a hue, density, saturation and exposure value.
  41883. * @param filterHue The hue of the color filter.
  41884. * @param filterDensity The density of the color filter.
  41885. * @param saturation The saturation.
  41886. * @param exposure The exposure.
  41887. * @param result The result data container.
  41888. */
  41889. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  41890. if (hue == null) {
  41891. return;
  41892. }
  41893. hue = ColorCurves.clamp(hue, 0, 360);
  41894. density = ColorCurves.clamp(density, -100, 100);
  41895. saturation = ColorCurves.clamp(saturation, -100, 100);
  41896. exposure = ColorCurves.clamp(exposure, -100, 100);
  41897. // Remap the slider/config filter density with non-linear mapping and also scale by half
  41898. // so that the maximum filter density is only 50% control. This provides fine control
  41899. // for small values and reasonable range.
  41900. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  41901. density *= 0.5;
  41902. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  41903. if (density < 0) {
  41904. density *= -1;
  41905. hue = (hue + 180) % 360;
  41906. }
  41907. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  41908. result.scaleToRef(2, result);
  41909. result.a = 1 + 0.01 * saturation;
  41910. };
  41911. /**
  41912. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  41913. * @param value The input slider value in range [-100,100].
  41914. * @returns Adjusted value.
  41915. */
  41916. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  41917. value /= 100;
  41918. var x = Math.abs(value);
  41919. x = Math.pow(x, 2);
  41920. if (value < 0) {
  41921. x *= -1;
  41922. }
  41923. x *= 100;
  41924. return x;
  41925. };
  41926. /**
  41927. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  41928. * @param hue The hue (H) input.
  41929. * @param saturation The saturation (S) input.
  41930. * @param brightness The brightness (B) input.
  41931. * @result An RGBA color represented as Vector4.
  41932. */
  41933. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  41934. var h = ColorCurves.clamp(hue, 0, 360);
  41935. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  41936. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  41937. if (s === 0) {
  41938. result.r = v;
  41939. result.g = v;
  41940. result.b = v;
  41941. }
  41942. else {
  41943. // sector 0 to 5
  41944. h /= 60;
  41945. var i = Math.floor(h);
  41946. // fractional part of h
  41947. var f = h - i;
  41948. var p = v * (1 - s);
  41949. var q = v * (1 - s * f);
  41950. var t = v * (1 - s * (1 - f));
  41951. switch (i) {
  41952. case 0:
  41953. result.r = v;
  41954. result.g = t;
  41955. result.b = p;
  41956. break;
  41957. case 1:
  41958. result.r = q;
  41959. result.g = v;
  41960. result.b = p;
  41961. break;
  41962. case 2:
  41963. result.r = p;
  41964. result.g = v;
  41965. result.b = t;
  41966. break;
  41967. case 3:
  41968. result.r = p;
  41969. result.g = q;
  41970. result.b = v;
  41971. break;
  41972. case 4:
  41973. result.r = t;
  41974. result.g = p;
  41975. result.b = v;
  41976. break;
  41977. default: // case 5:
  41978. result.r = v;
  41979. result.g = p;
  41980. result.b = q;
  41981. break;
  41982. }
  41983. }
  41984. result.a = 1;
  41985. };
  41986. /**
  41987. * Returns a value clamped between min and max
  41988. * @param value The value to clamp
  41989. * @param min The minimum of value
  41990. * @param max The maximum of value
  41991. * @returns The clamped value.
  41992. */
  41993. ColorCurves.clamp = function (value, min, max) {
  41994. return Math.min(Math.max(value, min), max);
  41995. };
  41996. /**
  41997. * Clones the current color curve instance.
  41998. * @return The cloned curves
  41999. */
  42000. ColorCurves.prototype.clone = function () {
  42001. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  42002. };
  42003. /**
  42004. * Serializes the current color curve instance to a json representation.
  42005. * @return a JSON representation
  42006. */
  42007. ColorCurves.prototype.serialize = function () {
  42008. return BABYLON.SerializationHelper.Serialize(this);
  42009. };
  42010. /**
  42011. * Parses the color curve from a json representation.
  42012. * @param source the JSON source to parse
  42013. * @return The parsed curves
  42014. */
  42015. ColorCurves.Parse = function (source) {
  42016. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42017. };
  42018. __decorate([
  42019. BABYLON.serialize()
  42020. ], ColorCurves.prototype, "_globalHue", void 0);
  42021. __decorate([
  42022. BABYLON.serialize()
  42023. ], ColorCurves.prototype, "_globalDensity", void 0);
  42024. __decorate([
  42025. BABYLON.serialize()
  42026. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42027. __decorate([
  42028. BABYLON.serialize()
  42029. ], ColorCurves.prototype, "_globalExposure", void 0);
  42030. __decorate([
  42031. BABYLON.serialize()
  42032. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42033. __decorate([
  42034. BABYLON.serialize()
  42035. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42036. __decorate([
  42037. BABYLON.serialize()
  42038. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42039. __decorate([
  42040. BABYLON.serialize()
  42041. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42042. __decorate([
  42043. BABYLON.serialize()
  42044. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42045. __decorate([
  42046. BABYLON.serialize()
  42047. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42048. __decorate([
  42049. BABYLON.serialize()
  42050. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42051. __decorate([
  42052. BABYLON.serialize()
  42053. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42054. return ColorCurves;
  42055. }());
  42056. BABYLON.ColorCurves = ColorCurves;
  42057. })(BABYLON || (BABYLON = {}));
  42058. //# sourceMappingURL=babylon.colorCurves.js.map
  42059. //# sourceMappingURL=babylon.behavior.js.map
  42060. var BABYLON;
  42061. (function (BABYLON) {
  42062. /**
  42063. * "Static Class" containing the most commonly used helper while dealing with material for
  42064. * rendering purpose.
  42065. *
  42066. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42067. *
  42068. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42069. */
  42070. var MaterialHelper = /** @class */ (function () {
  42071. function MaterialHelper() {
  42072. }
  42073. /**
  42074. * Bind the current view position to an effect.
  42075. * @param effect The effect to be bound
  42076. * @param scene The scene the eyes position is used from
  42077. */
  42078. MaterialHelper.BindEyePosition = function (effect, scene) {
  42079. if (scene._forcedViewPosition) {
  42080. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42081. return;
  42082. }
  42083. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42084. };
  42085. /**
  42086. * Helps preparing the defines values about the UVs in used in the effect.
  42087. * UVs are shared as much as we can accross chanels in the shaders.
  42088. * @param texture The texture we are preparing the UVs for
  42089. * @param defines The defines to update
  42090. * @param key The chanel key "diffuse", "specular"... used in the shader
  42091. */
  42092. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42093. defines._needUVs = true;
  42094. defines[key] = true;
  42095. if (texture.getTextureMatrix().isIdentity(true)) {
  42096. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42097. if (texture.coordinatesIndex === 0) {
  42098. defines["MAINUV1"] = true;
  42099. }
  42100. else {
  42101. defines["MAINUV2"] = true;
  42102. }
  42103. }
  42104. else {
  42105. defines[key + "DIRECTUV"] = 0;
  42106. }
  42107. };
  42108. /**
  42109. * Binds a texture matrix value to its corrsponding uniform
  42110. * @param texture The texture to bind the matrix for
  42111. * @param uniformBuffer The uniform buffer receivin the data
  42112. * @param key The chanel key "diffuse", "specular"... used in the shader
  42113. */
  42114. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42115. var matrix = texture.getTextureMatrix();
  42116. if (!matrix.isIdentity(true)) {
  42117. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42118. }
  42119. };
  42120. /**
  42121. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42122. * @param mesh defines the current mesh
  42123. * @param scene defines the current scene
  42124. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42125. * @param pointsCloud defines if point cloud rendering has to be turned on
  42126. * @param fogEnabled defines if fog has to be turned on
  42127. * @param alphaTest defines if alpha testing has to be turned on
  42128. * @param defines defines the current list of defines
  42129. */
  42130. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42131. if (defines._areMiscDirty) {
  42132. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42133. defines["POINTSIZE"] = pointsCloud;
  42134. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42135. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42136. defines["ALPHATEST"] = alphaTest;
  42137. }
  42138. };
  42139. /**
  42140. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42141. * @param scene defines the current scene
  42142. * @param engine defines the current engine
  42143. * @param defines specifies the list of active defines
  42144. * @param useInstances defines if instances have to be turned on
  42145. * @param useClipPlane defines if clip plane have to be turned on
  42146. */
  42147. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42148. if (useClipPlane === void 0) { useClipPlane = null; }
  42149. var changed = false;
  42150. if (useClipPlane == null) {
  42151. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  42152. }
  42153. if (defines["CLIPPLANE"] !== useClipPlane) {
  42154. defines["CLIPPLANE"] = useClipPlane;
  42155. changed = true;
  42156. }
  42157. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42158. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42159. changed = true;
  42160. }
  42161. if (defines["INSTANCES"] !== useInstances) {
  42162. defines["INSTANCES"] = useInstances;
  42163. changed = true;
  42164. }
  42165. if (changed) {
  42166. defines.markAsUnprocessed();
  42167. }
  42168. };
  42169. /**
  42170. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42171. * @param mesh The mesh containing the geometry data we will draw
  42172. * @param defines The defines to update
  42173. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42174. * @param useBones Precise whether bones should be used or not (override mesh info)
  42175. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42176. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42177. * @returns false if defines are considered not dirty and have not been checked
  42178. */
  42179. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42180. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42181. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42182. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42183. return false;
  42184. }
  42185. defines._normals = defines._needNormals;
  42186. defines._uvs = defines._needUVs;
  42187. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42188. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42189. defines["TANGENT"] = true;
  42190. }
  42191. if (defines._needUVs) {
  42192. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42193. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42194. }
  42195. else {
  42196. defines["UV1"] = false;
  42197. defines["UV2"] = false;
  42198. }
  42199. if (useVertexColor) {
  42200. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42201. defines["VERTEXCOLOR"] = hasVertexColors;
  42202. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42203. }
  42204. if (useBones) {
  42205. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42206. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42207. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42208. }
  42209. else {
  42210. defines["NUM_BONE_INFLUENCERS"] = 0;
  42211. defines["BonesPerMesh"] = 0;
  42212. }
  42213. }
  42214. if (useMorphTargets) {
  42215. var manager = mesh.morphTargetManager;
  42216. if (manager) {
  42217. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42218. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42219. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42220. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42221. }
  42222. else {
  42223. defines["MORPHTARGETS_TANGENT"] = false;
  42224. defines["MORPHTARGETS_NORMAL"] = false;
  42225. defines["MORPHTARGETS"] = false;
  42226. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42227. }
  42228. }
  42229. return true;
  42230. };
  42231. /**
  42232. * Prepares the defines related to the light information passed in parameter
  42233. * @param scene The scene we are intending to draw
  42234. * @param mesh The mesh the effect is compiling for
  42235. * @param defines The defines to update
  42236. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42237. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42238. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42239. * @returns true if normals will be required for the rest of the effect
  42240. */
  42241. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42242. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42243. if (disableLighting === void 0) { disableLighting = false; }
  42244. if (!defines._areLightsDirty) {
  42245. return defines._needNormals;
  42246. }
  42247. var lightIndex = 0;
  42248. var needNormals = false;
  42249. var needRebuild = false;
  42250. var lightmapMode = false;
  42251. var shadowEnabled = false;
  42252. var specularEnabled = false;
  42253. if (scene.lightsEnabled && !disableLighting) {
  42254. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42255. var light = _a[_i];
  42256. needNormals = true;
  42257. if (defines["LIGHT" + lightIndex] === undefined) {
  42258. needRebuild = true;
  42259. }
  42260. defines["LIGHT" + lightIndex] = true;
  42261. defines["SPOTLIGHT" + lightIndex] = false;
  42262. defines["HEMILIGHT" + lightIndex] = false;
  42263. defines["POINTLIGHT" + lightIndex] = false;
  42264. defines["DIRLIGHT" + lightIndex] = false;
  42265. var type;
  42266. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  42267. type = "SPOTLIGHT" + lightIndex;
  42268. var spotLight = light;
  42269. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  42270. }
  42271. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  42272. type = "HEMILIGHT" + lightIndex;
  42273. }
  42274. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  42275. type = "POINTLIGHT" + lightIndex;
  42276. }
  42277. else {
  42278. type = "DIRLIGHT" + lightIndex;
  42279. }
  42280. defines[type] = true;
  42281. // Specular
  42282. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42283. specularEnabled = true;
  42284. }
  42285. // Shadows
  42286. defines["SHADOW" + lightIndex] = false;
  42287. defines["SHADOWPCF" + lightIndex] = false;
  42288. defines["SHADOWPCSS" + lightIndex] = false;
  42289. defines["SHADOWPOISSON" + lightIndex] = false;
  42290. defines["SHADOWESM" + lightIndex] = false;
  42291. defines["SHADOWCUBE" + lightIndex] = false;
  42292. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42293. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42294. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42295. var shadowGenerator = light.getShadowGenerator();
  42296. if (shadowGenerator) {
  42297. shadowEnabled = true;
  42298. shadowGenerator.prepareDefines(defines, lightIndex);
  42299. }
  42300. }
  42301. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42302. lightmapMode = true;
  42303. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42304. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42305. }
  42306. else {
  42307. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42308. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42309. }
  42310. lightIndex++;
  42311. if (lightIndex === maxSimultaneousLights)
  42312. break;
  42313. }
  42314. }
  42315. defines["SPECULARTERM"] = specularEnabled;
  42316. defines["SHADOWS"] = shadowEnabled;
  42317. // Resetting all other lights if any
  42318. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42319. if (defines["LIGHT" + index] !== undefined) {
  42320. defines["LIGHT" + index] = false;
  42321. defines["HEMILIGHT" + lightIndex] = false;
  42322. defines["POINTLIGHT" + lightIndex] = false;
  42323. defines["DIRLIGHT" + lightIndex] = false;
  42324. defines["SPOTLIGHT" + lightIndex] = false;
  42325. defines["SHADOW" + lightIndex] = false;
  42326. }
  42327. }
  42328. var caps = scene.getEngine().getCaps();
  42329. if (defines["SHADOWFLOAT"] === undefined) {
  42330. needRebuild = true;
  42331. }
  42332. defines["SHADOWFLOAT"] = shadowEnabled &&
  42333. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42334. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42335. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42336. if (needRebuild) {
  42337. defines.rebuild();
  42338. }
  42339. return needNormals;
  42340. };
  42341. /**
  42342. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42343. * that won t be acctive due to defines being turned off.
  42344. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42345. * @param samplersList The samplers list
  42346. * @param defines The defines helping in the list generation
  42347. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42348. */
  42349. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42350. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42351. var uniformsList;
  42352. var uniformBuffersList = null;
  42353. if (uniformsListOrOptions.uniformsNames) {
  42354. var options = uniformsListOrOptions;
  42355. uniformsList = options.uniformsNames;
  42356. uniformBuffersList = options.uniformBuffersNames;
  42357. samplersList = options.samplers;
  42358. defines = options.defines;
  42359. maxSimultaneousLights = options.maxSimultaneousLights;
  42360. }
  42361. else {
  42362. uniformsList = uniformsListOrOptions;
  42363. if (!samplersList) {
  42364. samplersList = [];
  42365. }
  42366. }
  42367. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42368. if (!defines["LIGHT" + lightIndex]) {
  42369. break;
  42370. }
  42371. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42372. if (uniformBuffersList) {
  42373. uniformBuffersList.push("Light" + lightIndex);
  42374. }
  42375. samplersList.push("shadowSampler" + lightIndex);
  42376. samplersList.push("depthSampler" + lightIndex);
  42377. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42378. samplersList.push("projectionLightSampler" + lightIndex);
  42379. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42380. }
  42381. }
  42382. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42383. uniformsList.push("morphTargetInfluences");
  42384. }
  42385. };
  42386. /**
  42387. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42388. * @param defines The defines to update while falling back
  42389. * @param fallbacks The authorized effect fallbacks
  42390. * @param maxSimultaneousLights The maximum number of lights allowed
  42391. * @param rank the current rank of the Effect
  42392. * @returns The newly affected rank
  42393. */
  42394. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42395. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42396. if (rank === void 0) { rank = 0; }
  42397. var lightFallbackRank = 0;
  42398. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42399. if (!defines["LIGHT" + lightIndex]) {
  42400. break;
  42401. }
  42402. if (lightIndex > 0) {
  42403. lightFallbackRank = rank + lightIndex;
  42404. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42405. }
  42406. if (!defines["SHADOWS"]) {
  42407. if (defines["SHADOW" + lightIndex]) {
  42408. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42409. }
  42410. if (defines["SHADOWPCF" + lightIndex]) {
  42411. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42412. }
  42413. if (defines["SHADOWPCSS" + lightIndex]) {
  42414. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42415. }
  42416. if (defines["SHADOWPOISSON" + lightIndex]) {
  42417. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42418. }
  42419. if (defines["SHADOWESM" + lightIndex]) {
  42420. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42421. }
  42422. }
  42423. }
  42424. return lightFallbackRank++;
  42425. };
  42426. /**
  42427. * Prepares the list of attributes required for morph targets according to the effect defines.
  42428. * @param attribs The current list of supported attribs
  42429. * @param mesh The mesh to prepare the morph targets attributes for
  42430. * @param defines The current Defines of the effect
  42431. */
  42432. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42433. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42434. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42435. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42436. var manager = mesh.morphTargetManager;
  42437. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42438. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42439. for (var index = 0; index < influencers; index++) {
  42440. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42441. if (normal) {
  42442. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42443. }
  42444. if (tangent) {
  42445. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42446. }
  42447. if (attribs.length > maxAttributesCount) {
  42448. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42449. }
  42450. }
  42451. }
  42452. };
  42453. /**
  42454. * Prepares the list of attributes required for bones according to the effect defines.
  42455. * @param attribs The current list of supported attribs
  42456. * @param mesh The mesh to prepare the bones attributes for
  42457. * @param defines The current Defines of the effect
  42458. * @param fallbacks The current efffect fallback strategy
  42459. */
  42460. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42461. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42462. fallbacks.addCPUSkinningFallback(0, mesh);
  42463. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42464. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42465. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42466. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42467. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42468. }
  42469. }
  42470. };
  42471. /**
  42472. * Prepares the list of attributes required for instances according to the effect defines.
  42473. * @param attribs The current list of supported attribs
  42474. * @param defines The current Defines of the effect
  42475. */
  42476. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42477. if (defines["INSTANCES"]) {
  42478. attribs.push("world0");
  42479. attribs.push("world1");
  42480. attribs.push("world2");
  42481. attribs.push("world3");
  42482. }
  42483. };
  42484. /**
  42485. * Binds the light shadow information to the effect for the given mesh.
  42486. * @param light The light containing the generator
  42487. * @param scene The scene the lights belongs to
  42488. * @param mesh The mesh we are binding the information to render
  42489. * @param lightIndex The light index in the effect used to render the mesh
  42490. * @param effect The effect we are binding the data to
  42491. */
  42492. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42493. if (light.shadowEnabled && mesh.receiveShadows) {
  42494. var shadowGenerator = light.getShadowGenerator();
  42495. if (shadowGenerator) {
  42496. shadowGenerator.bindShadowLight(lightIndex, effect);
  42497. }
  42498. }
  42499. };
  42500. /**
  42501. * Binds the light information to the effect.
  42502. * @param light The light containing the generator
  42503. * @param effect The effect we are binding the data to
  42504. * @param lightIndex The light index in the effect used to render
  42505. */
  42506. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42507. light.transferToEffect(effect, lightIndex + "");
  42508. };
  42509. /**
  42510. * Binds the lights information from the scene to the effect for the given mesh.
  42511. * @param scene The scene the lights belongs to
  42512. * @param mesh The mesh we are binding the information to render
  42513. * @param effect The effect we are binding the data to
  42514. * @param defines The generated defines for the effect
  42515. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42516. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42517. */
  42518. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42519. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42520. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42521. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42522. for (var i = 0; i < len; i++) {
  42523. var light = mesh._lightSources[i];
  42524. var iAsString = i.toString();
  42525. var scaledIntensity = light.getScaledIntensity();
  42526. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42527. MaterialHelper.BindLightProperties(light, effect, i);
  42528. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42529. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42530. if (defines["SPECULARTERM"]) {
  42531. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42532. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42533. }
  42534. // Shadows
  42535. if (scene.shadowsEnabled) {
  42536. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42537. }
  42538. light._uniformBuffer.update();
  42539. }
  42540. };
  42541. /**
  42542. * Binds the fog information from the scene to the effect for the given mesh.
  42543. * @param scene The scene the lights belongs to
  42544. * @param mesh The mesh we are binding the information to render
  42545. * @param effect The effect we are binding the data to
  42546. */
  42547. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42548. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42549. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42550. effect.setColor3("vFogColor", scene.fogColor);
  42551. }
  42552. };
  42553. /**
  42554. * Binds the bones information from the mesh to the effect.
  42555. * @param mesh The mesh we are binding the information to render
  42556. * @param effect The effect we are binding the data to
  42557. */
  42558. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42559. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42560. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42561. if (matrices && effect) {
  42562. effect.setMatrices("mBones", matrices);
  42563. }
  42564. }
  42565. };
  42566. /**
  42567. * Binds the morph targets information from the mesh to the effect.
  42568. * @param abstractMesh The mesh we are binding the information to render
  42569. * @param effect The effect we are binding the data to
  42570. */
  42571. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42572. var manager = abstractMesh.morphTargetManager;
  42573. if (!abstractMesh || !manager) {
  42574. return;
  42575. }
  42576. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42577. };
  42578. /**
  42579. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42580. * @param defines The generated defines used in the effect
  42581. * @param effect The effect we are binding the data to
  42582. * @param scene The scene we are willing to render with logarithmic scale for
  42583. */
  42584. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42585. if (defines["LOGARITHMICDEPTH"]) {
  42586. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42587. }
  42588. };
  42589. /**
  42590. * Binds the clip plane information from the scene to the effect.
  42591. * @param scene The scene the clip plane information are extracted from
  42592. * @param effect The effect we are binding the data to
  42593. */
  42594. MaterialHelper.BindClipPlane = function (effect, scene) {
  42595. if (scene.clipPlane) {
  42596. var clipPlane = scene.clipPlane;
  42597. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42598. }
  42599. };
  42600. return MaterialHelper;
  42601. }());
  42602. BABYLON.MaterialHelper = MaterialHelper;
  42603. })(BABYLON || (BABYLON = {}));
  42604. //# sourceMappingURL=babylon.materialHelper.js.map
  42605. var BABYLON;
  42606. (function (BABYLON) {
  42607. var PushMaterial = /** @class */ (function (_super) {
  42608. __extends(PushMaterial, _super);
  42609. function PushMaterial(name, scene) {
  42610. var _this = _super.call(this, name, scene) || this;
  42611. _this._normalMatrix = new BABYLON.Matrix();
  42612. _this.storeEffectOnSubMeshes = true;
  42613. return _this;
  42614. }
  42615. PushMaterial.prototype.getEffect = function () {
  42616. return this._activeEffect;
  42617. };
  42618. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42619. if (!mesh) {
  42620. return false;
  42621. }
  42622. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42623. return true;
  42624. }
  42625. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42626. };
  42627. /**
  42628. * Binds the given world matrix to the active effect
  42629. *
  42630. * @param world the matrix to bind
  42631. */
  42632. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42633. this._activeEffect.setMatrix("world", world);
  42634. };
  42635. /**
  42636. * Binds the given normal matrix to the active effect
  42637. *
  42638. * @param normalMatrix the matrix to bind
  42639. */
  42640. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42641. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42642. };
  42643. PushMaterial.prototype.bind = function (world, mesh) {
  42644. if (!mesh) {
  42645. return;
  42646. }
  42647. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42648. };
  42649. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42650. if (effect === void 0) { effect = null; }
  42651. _super.prototype._afterBind.call(this, mesh);
  42652. this.getScene()._cachedEffect = effect;
  42653. };
  42654. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42655. if (visibility === void 0) { visibility = 1; }
  42656. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42657. };
  42658. return PushMaterial;
  42659. }(BABYLON.Material));
  42660. BABYLON.PushMaterial = PushMaterial;
  42661. })(BABYLON || (BABYLON = {}));
  42662. //# sourceMappingURL=babylon.pushMaterial.js.map
  42663. var BABYLON;
  42664. (function (BABYLON) {
  42665. /** @hidden */
  42666. var StandardMaterialDefines = /** @class */ (function (_super) {
  42667. __extends(StandardMaterialDefines, _super);
  42668. function StandardMaterialDefines() {
  42669. var _this = _super.call(this) || this;
  42670. _this.MAINUV1 = false;
  42671. _this.MAINUV2 = false;
  42672. _this.DIFFUSE = false;
  42673. _this.DIFFUSEDIRECTUV = 0;
  42674. _this.AMBIENT = false;
  42675. _this.AMBIENTDIRECTUV = 0;
  42676. _this.OPACITY = false;
  42677. _this.OPACITYDIRECTUV = 0;
  42678. _this.OPACITYRGB = false;
  42679. _this.REFLECTION = false;
  42680. _this.EMISSIVE = false;
  42681. _this.EMISSIVEDIRECTUV = 0;
  42682. _this.SPECULAR = false;
  42683. _this.SPECULARDIRECTUV = 0;
  42684. _this.BUMP = false;
  42685. _this.BUMPDIRECTUV = 0;
  42686. _this.PARALLAX = false;
  42687. _this.PARALLAXOCCLUSION = false;
  42688. _this.SPECULAROVERALPHA = false;
  42689. _this.CLIPPLANE = false;
  42690. _this.ALPHATEST = false;
  42691. _this.DEPTHPREPASS = false;
  42692. _this.ALPHAFROMDIFFUSE = false;
  42693. _this.POINTSIZE = false;
  42694. _this.FOG = false;
  42695. _this.SPECULARTERM = false;
  42696. _this.DIFFUSEFRESNEL = false;
  42697. _this.OPACITYFRESNEL = false;
  42698. _this.REFLECTIONFRESNEL = false;
  42699. _this.REFRACTIONFRESNEL = false;
  42700. _this.EMISSIVEFRESNEL = false;
  42701. _this.FRESNEL = false;
  42702. _this.NORMAL = false;
  42703. _this.UV1 = false;
  42704. _this.UV2 = false;
  42705. _this.VERTEXCOLOR = false;
  42706. _this.VERTEXALPHA = false;
  42707. _this.NUM_BONE_INFLUENCERS = 0;
  42708. _this.BonesPerMesh = 0;
  42709. _this.INSTANCES = false;
  42710. _this.GLOSSINESS = false;
  42711. _this.ROUGHNESS = false;
  42712. _this.EMISSIVEASILLUMINATION = false;
  42713. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42714. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42715. _this.LIGHTMAP = false;
  42716. _this.LIGHTMAPDIRECTUV = 0;
  42717. _this.OBJECTSPACE_NORMALMAP = false;
  42718. _this.USELIGHTMAPASSHADOWMAP = false;
  42719. _this.REFLECTIONMAP_3D = false;
  42720. _this.REFLECTIONMAP_SPHERICAL = false;
  42721. _this.REFLECTIONMAP_PLANAR = false;
  42722. _this.REFLECTIONMAP_CUBIC = false;
  42723. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42724. _this.REFLECTIONMAP_PROJECTION = false;
  42725. _this.REFLECTIONMAP_SKYBOX = false;
  42726. _this.REFLECTIONMAP_EXPLICIT = false;
  42727. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42728. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42729. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42730. _this.INVERTCUBICMAP = false;
  42731. _this.LOGARITHMICDEPTH = false;
  42732. _this.REFRACTION = false;
  42733. _this.REFRACTIONMAP_3D = false;
  42734. _this.REFLECTIONOVERALPHA = false;
  42735. _this.TWOSIDEDLIGHTING = false;
  42736. _this.SHADOWFLOAT = false;
  42737. _this.MORPHTARGETS = false;
  42738. _this.MORPHTARGETS_NORMAL = false;
  42739. _this.MORPHTARGETS_TANGENT = false;
  42740. _this.NUM_MORPH_INFLUENCERS = 0;
  42741. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42742. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42743. _this.IMAGEPROCESSING = false;
  42744. _this.VIGNETTE = false;
  42745. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42746. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42747. _this.TONEMAPPING = false;
  42748. _this.CONTRAST = false;
  42749. _this.COLORCURVES = false;
  42750. _this.COLORGRADING = false;
  42751. _this.COLORGRADING3D = false;
  42752. _this.SAMPLER3DGREENDEPTH = false;
  42753. _this.SAMPLER3DBGRMAP = false;
  42754. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42755. /**
  42756. * If the reflection texture on this material is in linear color space
  42757. * @hidden
  42758. */
  42759. _this.IS_REFLECTION_LINEAR = false;
  42760. /**
  42761. * If the refraction texture on this material is in linear color space
  42762. * @hidden
  42763. */
  42764. _this.IS_REFRACTION_LINEAR = false;
  42765. _this.EXPOSURE = false;
  42766. _this.rebuild();
  42767. return _this;
  42768. }
  42769. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42770. var modes = [
  42771. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42772. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42773. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42774. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42775. ];
  42776. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42777. var mode = modes_1[_i];
  42778. this[mode] = (mode === modeToEnable);
  42779. }
  42780. };
  42781. return StandardMaterialDefines;
  42782. }(BABYLON.MaterialDefines));
  42783. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42784. var StandardMaterial = /** @class */ (function (_super) {
  42785. __extends(StandardMaterial, _super);
  42786. function StandardMaterial(name, scene) {
  42787. var _this = _super.call(this, name, scene) || this;
  42788. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42789. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42790. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42791. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42792. _this.specularPower = 64;
  42793. _this._useAlphaFromDiffuseTexture = false;
  42794. _this._useEmissiveAsIllumination = false;
  42795. _this._linkEmissiveWithDiffuse = false;
  42796. _this._useSpecularOverAlpha = false;
  42797. _this._useReflectionOverAlpha = false;
  42798. _this._disableLighting = false;
  42799. _this._useObjectSpaceNormalMap = false;
  42800. _this._useParallax = false;
  42801. _this._useParallaxOcclusion = false;
  42802. _this.parallaxScaleBias = 0.05;
  42803. _this._roughness = 0;
  42804. _this.indexOfRefraction = 0.98;
  42805. _this.invertRefractionY = true;
  42806. /**
  42807. * Defines the alpha limits in alpha test mode
  42808. */
  42809. _this.alphaCutOff = 0.4;
  42810. _this._useLightmapAsShadowmap = false;
  42811. _this._useReflectionFresnelFromSpecular = false;
  42812. _this._useGlossinessFromSpecularMapAlpha = false;
  42813. _this._maxSimultaneousLights = 4;
  42814. /**
  42815. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42816. */
  42817. _this._invertNormalMapX = false;
  42818. /**
  42819. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42820. */
  42821. _this._invertNormalMapY = false;
  42822. /**
  42823. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42824. */
  42825. _this._twoSidedLighting = false;
  42826. _this._renderTargets = new BABYLON.SmartArray(16);
  42827. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42828. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42829. // Setup the default processing configuration to the scene.
  42830. _this._attachImageProcessingConfiguration(null);
  42831. _this.getRenderTargetTextures = function () {
  42832. _this._renderTargets.reset();
  42833. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42834. _this._renderTargets.push(_this._reflectionTexture);
  42835. }
  42836. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42837. _this._renderTargets.push(_this._refractionTexture);
  42838. }
  42839. return _this._renderTargets;
  42840. };
  42841. return _this;
  42842. }
  42843. ;
  42844. ;
  42845. ;
  42846. ;
  42847. ;
  42848. ;
  42849. ;
  42850. ;
  42851. ;
  42852. ;
  42853. ;
  42854. ;
  42855. ;
  42856. ;
  42857. ;
  42858. ;
  42859. ;
  42860. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42861. /**
  42862. * Gets the image processing configuration used either in this material.
  42863. */
  42864. get: function () {
  42865. return this._imageProcessingConfiguration;
  42866. },
  42867. /**
  42868. * Sets the Default image processing configuration used either in the this material.
  42869. *
  42870. * If sets to null, the scene one is in use.
  42871. */
  42872. set: function (value) {
  42873. this._attachImageProcessingConfiguration(value);
  42874. // Ensure the effect will be rebuilt.
  42875. this._markAllSubMeshesAsTexturesDirty();
  42876. },
  42877. enumerable: true,
  42878. configurable: true
  42879. });
  42880. /**
  42881. * Attaches a new image processing configuration to the Standard Material.
  42882. * @param configuration
  42883. */
  42884. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42885. var _this = this;
  42886. if (configuration === this._imageProcessingConfiguration) {
  42887. return;
  42888. }
  42889. // Detaches observer.
  42890. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42891. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42892. }
  42893. // Pick the scene configuration if needed.
  42894. if (!configuration) {
  42895. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42896. }
  42897. else {
  42898. this._imageProcessingConfiguration = configuration;
  42899. }
  42900. // Attaches observer.
  42901. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42902. _this._markAllSubMeshesAsImageProcessingDirty();
  42903. });
  42904. };
  42905. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42906. /**
  42907. * Gets wether the color curves effect is enabled.
  42908. */
  42909. get: function () {
  42910. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42911. },
  42912. /**
  42913. * Sets wether the color curves effect is enabled.
  42914. */
  42915. set: function (value) {
  42916. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42917. },
  42918. enumerable: true,
  42919. configurable: true
  42920. });
  42921. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42922. /**
  42923. * Gets wether the color grading effect is enabled.
  42924. */
  42925. get: function () {
  42926. return this.imageProcessingConfiguration.colorGradingEnabled;
  42927. },
  42928. /**
  42929. * Gets wether the color grading effect is enabled.
  42930. */
  42931. set: function (value) {
  42932. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42933. },
  42934. enumerable: true,
  42935. configurable: true
  42936. });
  42937. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42938. /**
  42939. * Gets wether tonemapping is enabled or not.
  42940. */
  42941. get: function () {
  42942. return this._imageProcessingConfiguration.toneMappingEnabled;
  42943. },
  42944. /**
  42945. * Sets wether tonemapping is enabled or not
  42946. */
  42947. set: function (value) {
  42948. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42949. },
  42950. enumerable: true,
  42951. configurable: true
  42952. });
  42953. ;
  42954. ;
  42955. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42956. /**
  42957. * The camera exposure used on this material.
  42958. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42959. * This corresponds to a photographic exposure.
  42960. */
  42961. get: function () {
  42962. return this._imageProcessingConfiguration.exposure;
  42963. },
  42964. /**
  42965. * The camera exposure used on this material.
  42966. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42967. * This corresponds to a photographic exposure.
  42968. */
  42969. set: function (value) {
  42970. this._imageProcessingConfiguration.exposure = value;
  42971. },
  42972. enumerable: true,
  42973. configurable: true
  42974. });
  42975. ;
  42976. ;
  42977. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42978. /**
  42979. * Gets The camera contrast used on this material.
  42980. */
  42981. get: function () {
  42982. return this._imageProcessingConfiguration.contrast;
  42983. },
  42984. /**
  42985. * Sets The camera contrast used on this material.
  42986. */
  42987. set: function (value) {
  42988. this._imageProcessingConfiguration.contrast = value;
  42989. },
  42990. enumerable: true,
  42991. configurable: true
  42992. });
  42993. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42994. /**
  42995. * Gets the Color Grading 2D Lookup Texture.
  42996. */
  42997. get: function () {
  42998. return this._imageProcessingConfiguration.colorGradingTexture;
  42999. },
  43000. /**
  43001. * Sets the Color Grading 2D Lookup Texture.
  43002. */
  43003. set: function (value) {
  43004. this._imageProcessingConfiguration.colorGradingTexture = value;
  43005. },
  43006. enumerable: true,
  43007. configurable: true
  43008. });
  43009. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43010. /**
  43011. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43012. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43013. * 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;
  43014. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43015. */
  43016. get: function () {
  43017. return this._imageProcessingConfiguration.colorCurves;
  43018. },
  43019. /**
  43020. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43021. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43022. * 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;
  43023. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43024. */
  43025. set: function (value) {
  43026. this._imageProcessingConfiguration.colorCurves = value;
  43027. },
  43028. enumerable: true,
  43029. configurable: true
  43030. });
  43031. StandardMaterial.prototype.getClassName = function () {
  43032. return "StandardMaterial";
  43033. };
  43034. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43035. get: function () {
  43036. return this._useLogarithmicDepth;
  43037. },
  43038. set: function (value) {
  43039. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43040. this._markAllSubMeshesAsMiscDirty();
  43041. },
  43042. enumerable: true,
  43043. configurable: true
  43044. });
  43045. StandardMaterial.prototype.needAlphaBlending = function () {
  43046. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43047. };
  43048. StandardMaterial.prototype.needAlphaTesting = function () {
  43049. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43050. };
  43051. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43052. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43053. };
  43054. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43055. return this._diffuseTexture;
  43056. };
  43057. /**
  43058. * Child classes can use it to update shaders
  43059. */
  43060. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43061. if (useInstances === void 0) { useInstances = false; }
  43062. if (subMesh.effect && this.isFrozen) {
  43063. if (this._wasPreviouslyReady && subMesh.effect) {
  43064. return true;
  43065. }
  43066. }
  43067. if (!subMesh._materialDefines) {
  43068. subMesh._materialDefines = new StandardMaterialDefines();
  43069. }
  43070. var scene = this.getScene();
  43071. var defines = subMesh._materialDefines;
  43072. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43073. if (defines._renderId === scene.getRenderId()) {
  43074. return true;
  43075. }
  43076. }
  43077. var engine = scene.getEngine();
  43078. // Lights
  43079. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43080. // Textures
  43081. if (defines._areTexturesDirty) {
  43082. defines._needUVs = false;
  43083. defines.MAINUV1 = false;
  43084. defines.MAINUV2 = false;
  43085. if (scene.texturesEnabled) {
  43086. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43087. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43088. return false;
  43089. }
  43090. else {
  43091. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43092. }
  43093. }
  43094. else {
  43095. defines.DIFFUSE = false;
  43096. }
  43097. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43098. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43099. return false;
  43100. }
  43101. else {
  43102. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43103. }
  43104. }
  43105. else {
  43106. defines.AMBIENT = false;
  43107. }
  43108. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43109. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43110. return false;
  43111. }
  43112. else {
  43113. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43114. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43115. }
  43116. }
  43117. else {
  43118. defines.OPACITY = false;
  43119. }
  43120. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43121. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43122. return false;
  43123. }
  43124. else {
  43125. defines._needNormals = true;
  43126. defines.REFLECTION = true;
  43127. defines.ROUGHNESS = (this._roughness > 0);
  43128. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43129. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43130. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43131. switch (this._reflectionTexture.coordinatesMode) {
  43132. case BABYLON.Texture.EXPLICIT_MODE:
  43133. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43134. break;
  43135. case BABYLON.Texture.PLANAR_MODE:
  43136. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43137. break;
  43138. case BABYLON.Texture.PROJECTION_MODE:
  43139. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43140. break;
  43141. case BABYLON.Texture.SKYBOX_MODE:
  43142. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43143. break;
  43144. case BABYLON.Texture.SPHERICAL_MODE:
  43145. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43146. break;
  43147. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43148. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43149. break;
  43150. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43151. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43152. break;
  43153. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43154. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43155. break;
  43156. case BABYLON.Texture.CUBIC_MODE:
  43157. case BABYLON.Texture.INVCUBIC_MODE:
  43158. default:
  43159. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43160. break;
  43161. }
  43162. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43163. }
  43164. }
  43165. else {
  43166. defines.REFLECTION = false;
  43167. }
  43168. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43169. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43170. return false;
  43171. }
  43172. else {
  43173. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43174. }
  43175. }
  43176. else {
  43177. defines.EMISSIVE = false;
  43178. }
  43179. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43180. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43181. return false;
  43182. }
  43183. else {
  43184. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43185. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43186. }
  43187. }
  43188. else {
  43189. defines.LIGHTMAP = false;
  43190. }
  43191. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43192. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43193. return false;
  43194. }
  43195. else {
  43196. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43197. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43198. }
  43199. }
  43200. else {
  43201. defines.SPECULAR = false;
  43202. }
  43203. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43204. // Bump texure can not be not blocking.
  43205. if (!this._bumpTexture.isReady()) {
  43206. return false;
  43207. }
  43208. else {
  43209. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43210. defines.PARALLAX = this._useParallax;
  43211. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43212. }
  43213. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43214. }
  43215. else {
  43216. defines.BUMP = false;
  43217. }
  43218. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43219. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43220. return false;
  43221. }
  43222. else {
  43223. defines._needUVs = true;
  43224. defines.REFRACTION = true;
  43225. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43226. }
  43227. }
  43228. else {
  43229. defines.REFRACTION = false;
  43230. }
  43231. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43232. }
  43233. else {
  43234. defines.DIFFUSE = false;
  43235. defines.AMBIENT = false;
  43236. defines.OPACITY = false;
  43237. defines.REFLECTION = false;
  43238. defines.EMISSIVE = false;
  43239. defines.LIGHTMAP = false;
  43240. defines.BUMP = false;
  43241. defines.REFRACTION = false;
  43242. }
  43243. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43244. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43245. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43246. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43247. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43248. }
  43249. if (defines._areImageProcessingDirty) {
  43250. if (!this._imageProcessingConfiguration.isReady()) {
  43251. return false;
  43252. }
  43253. this._imageProcessingConfiguration.prepareDefines(defines);
  43254. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43255. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43256. }
  43257. if (defines._areFresnelDirty) {
  43258. if (StandardMaterial.FresnelEnabled) {
  43259. // Fresnel
  43260. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43261. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43262. this._reflectionFresnelParameters) {
  43263. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43264. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43265. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43266. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43267. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43268. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43269. defines._needNormals = true;
  43270. defines.FRESNEL = true;
  43271. }
  43272. }
  43273. else {
  43274. defines.FRESNEL = false;
  43275. }
  43276. }
  43277. // Misc.
  43278. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43279. // Attribs
  43280. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43281. // Values that need to be evaluated on every frame
  43282. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43283. // Get correct effect
  43284. if (defines.isDirty) {
  43285. defines.markAsProcessed();
  43286. scene.resetCachedMaterial();
  43287. // Fallbacks
  43288. var fallbacks = new BABYLON.EffectFallbacks();
  43289. if (defines.REFLECTION) {
  43290. fallbacks.addFallback(0, "REFLECTION");
  43291. }
  43292. if (defines.SPECULAR) {
  43293. fallbacks.addFallback(0, "SPECULAR");
  43294. }
  43295. if (defines.BUMP) {
  43296. fallbacks.addFallback(0, "BUMP");
  43297. }
  43298. if (defines.PARALLAX) {
  43299. fallbacks.addFallback(1, "PARALLAX");
  43300. }
  43301. if (defines.PARALLAXOCCLUSION) {
  43302. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43303. }
  43304. if (defines.SPECULAROVERALPHA) {
  43305. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43306. }
  43307. if (defines.FOG) {
  43308. fallbacks.addFallback(1, "FOG");
  43309. }
  43310. if (defines.POINTSIZE) {
  43311. fallbacks.addFallback(0, "POINTSIZE");
  43312. }
  43313. if (defines.LOGARITHMICDEPTH) {
  43314. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43315. }
  43316. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43317. if (defines.SPECULARTERM) {
  43318. fallbacks.addFallback(0, "SPECULARTERM");
  43319. }
  43320. if (defines.DIFFUSEFRESNEL) {
  43321. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43322. }
  43323. if (defines.OPACITYFRESNEL) {
  43324. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43325. }
  43326. if (defines.REFLECTIONFRESNEL) {
  43327. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43328. }
  43329. if (defines.EMISSIVEFRESNEL) {
  43330. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43331. }
  43332. if (defines.FRESNEL) {
  43333. fallbacks.addFallback(4, "FRESNEL");
  43334. }
  43335. //Attributes
  43336. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43337. if (defines.NORMAL) {
  43338. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43339. }
  43340. if (defines.UV1) {
  43341. attribs.push(BABYLON.VertexBuffer.UVKind);
  43342. }
  43343. if (defines.UV2) {
  43344. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43345. }
  43346. if (defines.VERTEXCOLOR) {
  43347. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43348. }
  43349. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43350. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43351. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43352. var shaderName = "default";
  43353. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43354. "vFogInfos", "vFogColor", "pointSize",
  43355. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43356. "mBones",
  43357. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43358. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43359. "vReflectionPosition", "vReflectionSize",
  43360. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43361. ];
  43362. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43363. var uniformBuffers = ["Material", "Scene"];
  43364. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43365. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43366. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43367. uniformsNames: uniforms,
  43368. uniformBuffersNames: uniformBuffers,
  43369. samplers: samplers,
  43370. defines: defines,
  43371. maxSimultaneousLights: this._maxSimultaneousLights
  43372. });
  43373. if (this.customShaderNameResolve) {
  43374. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43375. }
  43376. var join = defines.toString();
  43377. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43378. attributes: attribs,
  43379. uniformsNames: uniforms,
  43380. uniformBuffersNames: uniformBuffers,
  43381. samplers: samplers,
  43382. defines: join,
  43383. fallbacks: fallbacks,
  43384. onCompiled: this.onCompiled,
  43385. onError: this.onError,
  43386. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43387. }, engine), defines);
  43388. this.buildUniformLayout();
  43389. }
  43390. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43391. return false;
  43392. }
  43393. defines._renderId = scene.getRenderId();
  43394. this._wasPreviouslyReady = true;
  43395. return true;
  43396. };
  43397. StandardMaterial.prototype.buildUniformLayout = function () {
  43398. // Order is important !
  43399. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43400. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43401. this._uniformBuffer.addUniform("opacityParts", 4);
  43402. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43403. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43404. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43405. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43406. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43407. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43408. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43409. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43410. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43411. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43412. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43413. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43414. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43415. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43416. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43417. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43418. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43419. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43420. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43421. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43422. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43423. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43424. this._uniformBuffer.addUniform("specularMatrix", 16);
  43425. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43426. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43427. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43428. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43429. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43430. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43431. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43432. this._uniformBuffer.addUniform("pointSize", 1);
  43433. this._uniformBuffer.create();
  43434. };
  43435. StandardMaterial.prototype.unbind = function () {
  43436. if (this._activeEffect) {
  43437. var needFlag = false;
  43438. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43439. this._activeEffect.setTexture("reflection2DSampler", null);
  43440. needFlag = true;
  43441. }
  43442. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43443. this._activeEffect.setTexture("refraction2DSampler", null);
  43444. needFlag = true;
  43445. }
  43446. if (needFlag) {
  43447. this._markAllSubMeshesAsTexturesDirty();
  43448. }
  43449. }
  43450. _super.prototype.unbind.call(this);
  43451. };
  43452. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43453. var scene = this.getScene();
  43454. var defines = subMesh._materialDefines;
  43455. if (!defines) {
  43456. return;
  43457. }
  43458. var effect = subMesh.effect;
  43459. if (!effect) {
  43460. return;
  43461. }
  43462. this._activeEffect = effect;
  43463. // Matrices
  43464. this.bindOnlyWorldMatrix(world);
  43465. // Normal Matrix
  43466. if (defines.OBJECTSPACE_NORMALMAP) {
  43467. world.toNormalMatrix(this._normalMatrix);
  43468. this.bindOnlyNormalMatrix(this._normalMatrix);
  43469. }
  43470. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43471. // Bones
  43472. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43473. if (mustRebind) {
  43474. this._uniformBuffer.bindToEffect(effect, "Material");
  43475. this.bindViewProjection(effect);
  43476. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43477. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43478. // Fresnel
  43479. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43480. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43481. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43482. }
  43483. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43484. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43485. }
  43486. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43487. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43488. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43489. }
  43490. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43491. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43492. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43493. }
  43494. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43495. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43496. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43497. }
  43498. }
  43499. // Textures
  43500. if (scene.texturesEnabled) {
  43501. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43502. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43503. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43504. if (this._diffuseTexture.hasAlpha) {
  43505. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43506. }
  43507. }
  43508. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43509. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43510. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43511. }
  43512. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43513. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43514. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43515. }
  43516. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43517. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43518. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43519. if (this._reflectionTexture.boundingBoxSize) {
  43520. var cubeTexture = this._reflectionTexture;
  43521. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43522. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43523. }
  43524. }
  43525. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43526. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43527. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43528. }
  43529. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43530. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43531. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43532. }
  43533. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43534. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43535. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43536. }
  43537. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43538. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43539. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43540. if (scene._mirroredCameraPosition) {
  43541. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43542. }
  43543. else {
  43544. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43545. }
  43546. }
  43547. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43548. var depth = 1.0;
  43549. if (!this._refractionTexture.isCube) {
  43550. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43551. if (this._refractionTexture.depth) {
  43552. depth = this._refractionTexture.depth;
  43553. }
  43554. }
  43555. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43556. }
  43557. }
  43558. // Point size
  43559. if (this.pointsCloud) {
  43560. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43561. }
  43562. if (defines.SPECULARTERM) {
  43563. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43564. }
  43565. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43566. // Diffuse
  43567. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43568. }
  43569. // Textures
  43570. if (scene.texturesEnabled) {
  43571. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43572. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43573. }
  43574. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43575. effect.setTexture("ambientSampler", this._ambientTexture);
  43576. }
  43577. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43578. effect.setTexture("opacitySampler", this._opacityTexture);
  43579. }
  43580. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43581. if (this._reflectionTexture.isCube) {
  43582. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43583. }
  43584. else {
  43585. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43586. }
  43587. }
  43588. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43589. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43590. }
  43591. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43592. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43593. }
  43594. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43595. effect.setTexture("specularSampler", this._specularTexture);
  43596. }
  43597. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43598. effect.setTexture("bumpSampler", this._bumpTexture);
  43599. }
  43600. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43601. var depth = 1.0;
  43602. if (this._refractionTexture.isCube) {
  43603. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43604. }
  43605. else {
  43606. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43607. }
  43608. }
  43609. }
  43610. // Clip plane
  43611. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43612. // Colors
  43613. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43614. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43615. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43616. }
  43617. if (mustRebind || !this.isFrozen) {
  43618. // Lights
  43619. if (scene.lightsEnabled && !this._disableLighting) {
  43620. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43621. }
  43622. // View
  43623. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43624. this.bindView(effect);
  43625. }
  43626. // Fog
  43627. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43628. // Morph targets
  43629. if (defines.NUM_MORPH_INFLUENCERS) {
  43630. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43631. }
  43632. // Log. depth
  43633. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43634. // image processing
  43635. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  43636. this._imageProcessingConfiguration.bind(this._activeEffect);
  43637. }
  43638. }
  43639. this._uniformBuffer.update();
  43640. this._afterBind(mesh, this._activeEffect);
  43641. };
  43642. StandardMaterial.prototype.getAnimatables = function () {
  43643. var results = [];
  43644. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43645. results.push(this._diffuseTexture);
  43646. }
  43647. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43648. results.push(this._ambientTexture);
  43649. }
  43650. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43651. results.push(this._opacityTexture);
  43652. }
  43653. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43654. results.push(this._reflectionTexture);
  43655. }
  43656. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43657. results.push(this._emissiveTexture);
  43658. }
  43659. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43660. results.push(this._specularTexture);
  43661. }
  43662. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43663. results.push(this._bumpTexture);
  43664. }
  43665. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43666. results.push(this._lightmapTexture);
  43667. }
  43668. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43669. results.push(this._refractionTexture);
  43670. }
  43671. return results;
  43672. };
  43673. StandardMaterial.prototype.getActiveTextures = function () {
  43674. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43675. if (this._diffuseTexture) {
  43676. activeTextures.push(this._diffuseTexture);
  43677. }
  43678. if (this._ambientTexture) {
  43679. activeTextures.push(this._ambientTexture);
  43680. }
  43681. if (this._opacityTexture) {
  43682. activeTextures.push(this._opacityTexture);
  43683. }
  43684. if (this._reflectionTexture) {
  43685. activeTextures.push(this._reflectionTexture);
  43686. }
  43687. if (this._emissiveTexture) {
  43688. activeTextures.push(this._emissiveTexture);
  43689. }
  43690. if (this._specularTexture) {
  43691. activeTextures.push(this._specularTexture);
  43692. }
  43693. if (this._bumpTexture) {
  43694. activeTextures.push(this._bumpTexture);
  43695. }
  43696. if (this._lightmapTexture) {
  43697. activeTextures.push(this._lightmapTexture);
  43698. }
  43699. if (this._refractionTexture) {
  43700. activeTextures.push(this._refractionTexture);
  43701. }
  43702. return activeTextures;
  43703. };
  43704. StandardMaterial.prototype.hasTexture = function (texture) {
  43705. if (_super.prototype.hasTexture.call(this, texture)) {
  43706. return true;
  43707. }
  43708. if (this._diffuseTexture === texture) {
  43709. return true;
  43710. }
  43711. if (this._ambientTexture === texture) {
  43712. return true;
  43713. }
  43714. if (this._opacityTexture === texture) {
  43715. return true;
  43716. }
  43717. if (this._reflectionTexture === texture) {
  43718. return true;
  43719. }
  43720. if (this._emissiveTexture === texture) {
  43721. return true;
  43722. }
  43723. if (this._specularTexture === texture) {
  43724. return true;
  43725. }
  43726. if (this._bumpTexture === texture) {
  43727. return true;
  43728. }
  43729. if (this._lightmapTexture === texture) {
  43730. return true;
  43731. }
  43732. if (this._refractionTexture === texture) {
  43733. return true;
  43734. }
  43735. return false;
  43736. };
  43737. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43738. if (forceDisposeTextures) {
  43739. if (this._diffuseTexture) {
  43740. this._diffuseTexture.dispose();
  43741. }
  43742. if (this._ambientTexture) {
  43743. this._ambientTexture.dispose();
  43744. }
  43745. if (this._opacityTexture) {
  43746. this._opacityTexture.dispose();
  43747. }
  43748. if (this._reflectionTexture) {
  43749. this._reflectionTexture.dispose();
  43750. }
  43751. if (this._emissiveTexture) {
  43752. this._emissiveTexture.dispose();
  43753. }
  43754. if (this._specularTexture) {
  43755. this._specularTexture.dispose();
  43756. }
  43757. if (this._bumpTexture) {
  43758. this._bumpTexture.dispose();
  43759. }
  43760. if (this._lightmapTexture) {
  43761. this._lightmapTexture.dispose();
  43762. }
  43763. if (this._refractionTexture) {
  43764. this._refractionTexture.dispose();
  43765. }
  43766. }
  43767. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43768. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43769. }
  43770. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43771. };
  43772. StandardMaterial.prototype.clone = function (name) {
  43773. var _this = this;
  43774. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43775. result.name = name;
  43776. result.id = name;
  43777. return result;
  43778. };
  43779. StandardMaterial.prototype.serialize = function () {
  43780. return BABYLON.SerializationHelper.Serialize(this);
  43781. };
  43782. // Statics
  43783. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43784. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43785. };
  43786. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43787. get: function () {
  43788. return StandardMaterial._DiffuseTextureEnabled;
  43789. },
  43790. set: function (value) {
  43791. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43792. return;
  43793. }
  43794. StandardMaterial._DiffuseTextureEnabled = value;
  43795. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43796. },
  43797. enumerable: true,
  43798. configurable: true
  43799. });
  43800. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43801. get: function () {
  43802. return StandardMaterial._AmbientTextureEnabled;
  43803. },
  43804. set: function (value) {
  43805. if (StandardMaterial._AmbientTextureEnabled === value) {
  43806. return;
  43807. }
  43808. StandardMaterial._AmbientTextureEnabled = value;
  43809. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43810. },
  43811. enumerable: true,
  43812. configurable: true
  43813. });
  43814. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43815. get: function () {
  43816. return StandardMaterial._OpacityTextureEnabled;
  43817. },
  43818. set: function (value) {
  43819. if (StandardMaterial._OpacityTextureEnabled === value) {
  43820. return;
  43821. }
  43822. StandardMaterial._OpacityTextureEnabled = value;
  43823. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43824. },
  43825. enumerable: true,
  43826. configurable: true
  43827. });
  43828. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43829. get: function () {
  43830. return StandardMaterial._ReflectionTextureEnabled;
  43831. },
  43832. set: function (value) {
  43833. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43834. return;
  43835. }
  43836. StandardMaterial._ReflectionTextureEnabled = value;
  43837. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43838. },
  43839. enumerable: true,
  43840. configurable: true
  43841. });
  43842. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43843. get: function () {
  43844. return StandardMaterial._EmissiveTextureEnabled;
  43845. },
  43846. set: function (value) {
  43847. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43848. return;
  43849. }
  43850. StandardMaterial._EmissiveTextureEnabled = value;
  43851. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43852. },
  43853. enumerable: true,
  43854. configurable: true
  43855. });
  43856. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43857. get: function () {
  43858. return StandardMaterial._SpecularTextureEnabled;
  43859. },
  43860. set: function (value) {
  43861. if (StandardMaterial._SpecularTextureEnabled === value) {
  43862. return;
  43863. }
  43864. StandardMaterial._SpecularTextureEnabled = value;
  43865. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43866. },
  43867. enumerable: true,
  43868. configurable: true
  43869. });
  43870. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43871. get: function () {
  43872. return StandardMaterial._BumpTextureEnabled;
  43873. },
  43874. set: function (value) {
  43875. if (StandardMaterial._BumpTextureEnabled === value) {
  43876. return;
  43877. }
  43878. StandardMaterial._BumpTextureEnabled = value;
  43879. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43880. },
  43881. enumerable: true,
  43882. configurable: true
  43883. });
  43884. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43885. get: function () {
  43886. return StandardMaterial._LightmapTextureEnabled;
  43887. },
  43888. set: function (value) {
  43889. if (StandardMaterial._LightmapTextureEnabled === value) {
  43890. return;
  43891. }
  43892. StandardMaterial._LightmapTextureEnabled = value;
  43893. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43894. },
  43895. enumerable: true,
  43896. configurable: true
  43897. });
  43898. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43899. get: function () {
  43900. return StandardMaterial._RefractionTextureEnabled;
  43901. },
  43902. set: function (value) {
  43903. if (StandardMaterial._RefractionTextureEnabled === value) {
  43904. return;
  43905. }
  43906. StandardMaterial._RefractionTextureEnabled = value;
  43907. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43908. },
  43909. enumerable: true,
  43910. configurable: true
  43911. });
  43912. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43913. get: function () {
  43914. return StandardMaterial._ColorGradingTextureEnabled;
  43915. },
  43916. set: function (value) {
  43917. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43918. return;
  43919. }
  43920. StandardMaterial._ColorGradingTextureEnabled = value;
  43921. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43922. },
  43923. enumerable: true,
  43924. configurable: true
  43925. });
  43926. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43927. get: function () {
  43928. return StandardMaterial._FresnelEnabled;
  43929. },
  43930. set: function (value) {
  43931. if (StandardMaterial._FresnelEnabled === value) {
  43932. return;
  43933. }
  43934. StandardMaterial._FresnelEnabled = value;
  43935. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43936. },
  43937. enumerable: true,
  43938. configurable: true
  43939. });
  43940. // Flags used to enable or disable a type of texture for all Standard Materials
  43941. StandardMaterial._DiffuseTextureEnabled = true;
  43942. StandardMaterial._AmbientTextureEnabled = true;
  43943. StandardMaterial._OpacityTextureEnabled = true;
  43944. StandardMaterial._ReflectionTextureEnabled = true;
  43945. StandardMaterial._EmissiveTextureEnabled = true;
  43946. StandardMaterial._SpecularTextureEnabled = true;
  43947. StandardMaterial._BumpTextureEnabled = true;
  43948. StandardMaterial._LightmapTextureEnabled = true;
  43949. StandardMaterial._RefractionTextureEnabled = true;
  43950. StandardMaterial._ColorGradingTextureEnabled = true;
  43951. StandardMaterial._FresnelEnabled = true;
  43952. __decorate([
  43953. BABYLON.serializeAsTexture("diffuseTexture")
  43954. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43955. __decorate([
  43956. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43957. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43958. __decorate([
  43959. BABYLON.serializeAsTexture("ambientTexture")
  43960. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43961. __decorate([
  43962. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43963. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43964. __decorate([
  43965. BABYLON.serializeAsTexture("opacityTexture")
  43966. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43967. __decorate([
  43968. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43969. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43970. __decorate([
  43971. BABYLON.serializeAsTexture("reflectionTexture")
  43972. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43973. __decorate([
  43974. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43975. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43976. __decorate([
  43977. BABYLON.serializeAsTexture("emissiveTexture")
  43978. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43979. __decorate([
  43980. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43981. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43982. __decorate([
  43983. BABYLON.serializeAsTexture("specularTexture")
  43984. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43985. __decorate([
  43986. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43987. ], StandardMaterial.prototype, "specularTexture", void 0);
  43988. __decorate([
  43989. BABYLON.serializeAsTexture("bumpTexture")
  43990. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43991. __decorate([
  43992. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43993. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43994. __decorate([
  43995. BABYLON.serializeAsTexture("lightmapTexture")
  43996. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43997. __decorate([
  43998. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43999. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44000. __decorate([
  44001. BABYLON.serializeAsTexture("refractionTexture")
  44002. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44003. __decorate([
  44004. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44005. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44006. __decorate([
  44007. BABYLON.serializeAsColor3("ambient")
  44008. ], StandardMaterial.prototype, "ambientColor", void 0);
  44009. __decorate([
  44010. BABYLON.serializeAsColor3("diffuse")
  44011. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44012. __decorate([
  44013. BABYLON.serializeAsColor3("specular")
  44014. ], StandardMaterial.prototype, "specularColor", void 0);
  44015. __decorate([
  44016. BABYLON.serializeAsColor3("emissive")
  44017. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44018. __decorate([
  44019. BABYLON.serialize()
  44020. ], StandardMaterial.prototype, "specularPower", void 0);
  44021. __decorate([
  44022. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44023. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44024. __decorate([
  44025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44026. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44027. __decorate([
  44028. BABYLON.serialize("useEmissiveAsIllumination")
  44029. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44030. __decorate([
  44031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44032. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44033. __decorate([
  44034. BABYLON.serialize("linkEmissiveWithDiffuse")
  44035. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44036. __decorate([
  44037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44038. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44039. __decorate([
  44040. BABYLON.serialize("useSpecularOverAlpha")
  44041. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44042. __decorate([
  44043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44044. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44045. __decorate([
  44046. BABYLON.serialize("useReflectionOverAlpha")
  44047. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44048. __decorate([
  44049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44050. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44051. __decorate([
  44052. BABYLON.serialize("disableLighting")
  44053. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44054. __decorate([
  44055. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44056. ], StandardMaterial.prototype, "disableLighting", void 0);
  44057. __decorate([
  44058. BABYLON.serialize("useObjectSpaceNormalMap")
  44059. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44060. __decorate([
  44061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44062. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44063. __decorate([
  44064. BABYLON.serialize("useParallax")
  44065. ], StandardMaterial.prototype, "_useParallax", void 0);
  44066. __decorate([
  44067. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44068. ], StandardMaterial.prototype, "useParallax", void 0);
  44069. __decorate([
  44070. BABYLON.serialize("useParallaxOcclusion")
  44071. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44072. __decorate([
  44073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44074. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44075. __decorate([
  44076. BABYLON.serialize()
  44077. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44078. __decorate([
  44079. BABYLON.serialize("roughness")
  44080. ], StandardMaterial.prototype, "_roughness", void 0);
  44081. __decorate([
  44082. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44083. ], StandardMaterial.prototype, "roughness", void 0);
  44084. __decorate([
  44085. BABYLON.serialize()
  44086. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44087. __decorate([
  44088. BABYLON.serialize()
  44089. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44090. __decorate([
  44091. BABYLON.serialize()
  44092. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44093. __decorate([
  44094. BABYLON.serialize("useLightmapAsShadowmap")
  44095. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44096. __decorate([
  44097. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44098. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44099. __decorate([
  44100. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44101. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44102. __decorate([
  44103. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44104. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44105. __decorate([
  44106. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44107. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44108. __decorate([
  44109. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44110. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44111. __decorate([
  44112. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44113. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44114. __decorate([
  44115. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44116. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44117. __decorate([
  44118. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44119. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44120. __decorate([
  44121. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44122. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44123. __decorate([
  44124. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44125. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44126. __decorate([
  44127. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44128. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44129. __decorate([
  44130. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44131. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44132. __decorate([
  44133. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44134. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44135. __decorate([
  44136. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44137. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44138. __decorate([
  44139. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44140. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44141. __decorate([
  44142. BABYLON.serialize("maxSimultaneousLights")
  44143. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44144. __decorate([
  44145. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44146. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44147. __decorate([
  44148. BABYLON.serialize("invertNormalMapX")
  44149. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44150. __decorate([
  44151. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44152. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44153. __decorate([
  44154. BABYLON.serialize("invertNormalMapY")
  44155. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44156. __decorate([
  44157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44158. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44159. __decorate([
  44160. BABYLON.serialize("twoSidedLighting")
  44161. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44162. __decorate([
  44163. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44164. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44165. __decorate([
  44166. BABYLON.serialize()
  44167. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44168. return StandardMaterial;
  44169. }(BABYLON.PushMaterial));
  44170. BABYLON.StandardMaterial = StandardMaterial;
  44171. })(BABYLON || (BABYLON = {}));
  44172. //# sourceMappingURL=babylon.standardMaterial.js.map
  44173. var BABYLON;
  44174. (function (BABYLON) {
  44175. /**
  44176. * Manages the defines for the PBR Material.
  44177. * @hiddenChildren
  44178. */
  44179. var PBRMaterialDefines = /** @class */ (function (_super) {
  44180. __extends(PBRMaterialDefines, _super);
  44181. /**
  44182. * Initializes the PBR Material defines.
  44183. */
  44184. function PBRMaterialDefines() {
  44185. var _this = _super.call(this) || this;
  44186. _this.PBR = true;
  44187. _this.MAINUV1 = false;
  44188. _this.MAINUV2 = false;
  44189. _this.UV1 = false;
  44190. _this.UV2 = false;
  44191. _this.ALBEDO = false;
  44192. _this.ALBEDODIRECTUV = 0;
  44193. _this.VERTEXCOLOR = false;
  44194. _this.AMBIENT = false;
  44195. _this.AMBIENTDIRECTUV = 0;
  44196. _this.AMBIENTINGRAYSCALE = false;
  44197. _this.OPACITY = false;
  44198. _this.VERTEXALPHA = false;
  44199. _this.OPACITYDIRECTUV = 0;
  44200. _this.OPACITYRGB = false;
  44201. _this.ALPHATEST = false;
  44202. _this.DEPTHPREPASS = false;
  44203. _this.ALPHABLEND = false;
  44204. _this.ALPHAFROMALBEDO = false;
  44205. _this.ALPHATESTVALUE = "0.5";
  44206. _this.SPECULAROVERALPHA = false;
  44207. _this.RADIANCEOVERALPHA = false;
  44208. _this.ALPHAFRESNEL = false;
  44209. _this.LINEARALPHAFRESNEL = false;
  44210. _this.PREMULTIPLYALPHA = false;
  44211. _this.EMISSIVE = false;
  44212. _this.EMISSIVEDIRECTUV = 0;
  44213. _this.REFLECTIVITY = false;
  44214. _this.REFLECTIVITYDIRECTUV = 0;
  44215. _this.SPECULARTERM = false;
  44216. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44217. _this.MICROSURFACEAUTOMATIC = false;
  44218. _this.LODBASEDMICROSFURACE = false;
  44219. _this.MICROSURFACEMAP = false;
  44220. _this.MICROSURFACEMAPDIRECTUV = 0;
  44221. _this.METALLICWORKFLOW = false;
  44222. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44223. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44224. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44225. _this.AOSTOREINMETALMAPRED = false;
  44226. _this.ENVIRONMENTBRDF = false;
  44227. _this.NORMAL = false;
  44228. _this.TANGENT = false;
  44229. _this.BUMP = false;
  44230. _this.BUMPDIRECTUV = 0;
  44231. _this.OBJECTSPACE_NORMALMAP = false;
  44232. _this.PARALLAX = false;
  44233. _this.PARALLAXOCCLUSION = false;
  44234. _this.NORMALXYSCALE = true;
  44235. _this.LIGHTMAP = false;
  44236. _this.LIGHTMAPDIRECTUV = 0;
  44237. _this.USELIGHTMAPASSHADOWMAP = false;
  44238. _this.GAMMALIGHTMAP = false;
  44239. _this.REFLECTION = false;
  44240. _this.REFLECTIONMAP_3D = false;
  44241. _this.REFLECTIONMAP_SPHERICAL = false;
  44242. _this.REFLECTIONMAP_PLANAR = false;
  44243. _this.REFLECTIONMAP_CUBIC = false;
  44244. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44245. _this.REFLECTIONMAP_PROJECTION = false;
  44246. _this.REFLECTIONMAP_SKYBOX = false;
  44247. _this.REFLECTIONMAP_EXPLICIT = false;
  44248. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44249. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44250. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44251. _this.INVERTCUBICMAP = false;
  44252. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44253. _this.USESPHERICALINVERTEX = false;
  44254. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44255. _this.LODINREFLECTIONALPHA = false;
  44256. _this.GAMMAREFLECTION = false;
  44257. _this.RADIANCEOCCLUSION = false;
  44258. _this.HORIZONOCCLUSION = false;
  44259. _this.REFRACTION = false;
  44260. _this.REFRACTIONMAP_3D = false;
  44261. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44262. _this.LODINREFRACTIONALPHA = false;
  44263. _this.GAMMAREFRACTION = false;
  44264. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44265. _this.INSTANCES = false;
  44266. _this.NUM_BONE_INFLUENCERS = 0;
  44267. _this.BonesPerMesh = 0;
  44268. _this.NONUNIFORMSCALING = false;
  44269. _this.MORPHTARGETS = false;
  44270. _this.MORPHTARGETS_NORMAL = false;
  44271. _this.MORPHTARGETS_TANGENT = false;
  44272. _this.NUM_MORPH_INFLUENCERS = 0;
  44273. _this.IMAGEPROCESSING = false;
  44274. _this.VIGNETTE = false;
  44275. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44276. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44277. _this.TONEMAPPING = false;
  44278. _this.CONTRAST = false;
  44279. _this.COLORCURVES = false;
  44280. _this.COLORGRADING = false;
  44281. _this.COLORGRADING3D = false;
  44282. _this.SAMPLER3DGREENDEPTH = false;
  44283. _this.SAMPLER3DBGRMAP = false;
  44284. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44285. _this.EXPOSURE = false;
  44286. _this.USEPHYSICALLIGHTFALLOFF = false;
  44287. _this.TWOSIDEDLIGHTING = false;
  44288. _this.SHADOWFLOAT = false;
  44289. _this.CLIPPLANE = false;
  44290. _this.POINTSIZE = false;
  44291. _this.FOG = false;
  44292. _this.LOGARITHMICDEPTH = false;
  44293. _this.FORCENORMALFORWARD = false;
  44294. _this.SPECULARAA = false;
  44295. _this.UNLIT = false;
  44296. _this.rebuild();
  44297. return _this;
  44298. }
  44299. /**
  44300. * Resets the PBR Material defines.
  44301. */
  44302. PBRMaterialDefines.prototype.reset = function () {
  44303. _super.prototype.reset.call(this);
  44304. this.ALPHATESTVALUE = "0.5";
  44305. this.PBR = true;
  44306. };
  44307. return PBRMaterialDefines;
  44308. }(BABYLON.MaterialDefines));
  44309. /**
  44310. * The Physically based material base class of BJS.
  44311. *
  44312. * This offers the main features of a standard PBR material.
  44313. * For more information, please refer to the documentation :
  44314. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44315. */
  44316. var PBRBaseMaterial = /** @class */ (function (_super) {
  44317. __extends(PBRBaseMaterial, _super);
  44318. /**
  44319. * Instantiates a new PBRMaterial instance.
  44320. *
  44321. * @param name The material name
  44322. * @param scene The scene the material will be use in.
  44323. */
  44324. function PBRBaseMaterial(name, scene) {
  44325. var _this = _super.call(this, name, scene) || this;
  44326. /**
  44327. * Intensity of the direct lights e.g. the four lights available in your scene.
  44328. * This impacts both the direct diffuse and specular highlights.
  44329. */
  44330. _this._directIntensity = 1.0;
  44331. /**
  44332. * Intensity of the emissive part of the material.
  44333. * This helps controlling the emissive effect without modifying the emissive color.
  44334. */
  44335. _this._emissiveIntensity = 1.0;
  44336. /**
  44337. * Intensity of the environment e.g. how much the environment will light the object
  44338. * either through harmonics for rough material or through the refelction for shiny ones.
  44339. */
  44340. _this._environmentIntensity = 1.0;
  44341. /**
  44342. * This is a special control allowing the reduction of the specular highlights coming from the
  44343. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44344. */
  44345. _this._specularIntensity = 1.0;
  44346. /**
  44347. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44348. */
  44349. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44350. /**
  44351. * Debug Control allowing disabling the bump map on this material.
  44352. */
  44353. _this._disableBumpMap = false;
  44354. /**
  44355. * AKA Occlusion Texture Intensity in other nomenclature.
  44356. */
  44357. _this._ambientTextureStrength = 1.0;
  44358. /**
  44359. * The color of a material in ambient lighting.
  44360. */
  44361. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44362. /**
  44363. * AKA Diffuse Color in other nomenclature.
  44364. */
  44365. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44366. /**
  44367. * AKA Specular Color in other nomenclature.
  44368. */
  44369. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44370. /**
  44371. * The color applied when light is reflected from a material.
  44372. */
  44373. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44374. /**
  44375. * The color applied when light is emitted from a material.
  44376. */
  44377. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44378. /**
  44379. * AKA Glossiness in other nomenclature.
  44380. */
  44381. _this._microSurface = 0.9;
  44382. /**
  44383. * source material index of refraction (IOR)' / 'destination material IOR.
  44384. */
  44385. _this._indexOfRefraction = 0.66;
  44386. /**
  44387. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44388. */
  44389. _this._invertRefractionY = false;
  44390. /**
  44391. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44392. * Materials half opaque for instance using refraction could benefit from this control.
  44393. */
  44394. _this._linkRefractionWithTransparency = false;
  44395. /**
  44396. * Specifies that the material will use the light map as a show map.
  44397. */
  44398. _this._useLightmapAsShadowmap = false;
  44399. /**
  44400. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44401. * makes the reflect vector face the model (under horizon).
  44402. */
  44403. _this._useHorizonOcclusion = true;
  44404. /**
  44405. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44406. * too much the area relying on ambient texture to define their ambient occlusion.
  44407. */
  44408. _this._useRadianceOcclusion = true;
  44409. /**
  44410. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44411. */
  44412. _this._useAlphaFromAlbedoTexture = false;
  44413. /**
  44414. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44415. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44416. */
  44417. _this._useSpecularOverAlpha = true;
  44418. /**
  44419. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44420. */
  44421. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44422. /**
  44423. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44424. */
  44425. _this._useRoughnessFromMetallicTextureAlpha = true;
  44426. /**
  44427. * Specifies if the metallic texture contains the roughness information in its green channel.
  44428. */
  44429. _this._useRoughnessFromMetallicTextureGreen = false;
  44430. /**
  44431. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44432. */
  44433. _this._useMetallnessFromMetallicTextureBlue = false;
  44434. /**
  44435. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44436. */
  44437. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44438. /**
  44439. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44440. */
  44441. _this._useAmbientInGrayScale = false;
  44442. /**
  44443. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44444. * The material will try to infer what glossiness each pixel should be.
  44445. */
  44446. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44447. /**
  44448. * BJS is using an harcoded light falloff based on a manually sets up range.
  44449. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44450. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44451. */
  44452. _this._usePhysicalLightFalloff = true;
  44453. /**
  44454. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44455. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44456. */
  44457. _this._useRadianceOverAlpha = true;
  44458. /**
  44459. * Allows using an object space normal map (instead of tangent space).
  44460. */
  44461. _this._useObjectSpaceNormalMap = false;
  44462. /**
  44463. * Allows using the bump map in parallax mode.
  44464. */
  44465. _this._useParallax = false;
  44466. /**
  44467. * Allows using the bump map in parallax occlusion mode.
  44468. */
  44469. _this._useParallaxOcclusion = false;
  44470. /**
  44471. * Controls the scale bias of the parallax mode.
  44472. */
  44473. _this._parallaxScaleBias = 0.05;
  44474. /**
  44475. * If sets to true, disables all the lights affecting the material.
  44476. */
  44477. _this._disableLighting = false;
  44478. /**
  44479. * Number of Simultaneous lights allowed on the material.
  44480. */
  44481. _this._maxSimultaneousLights = 4;
  44482. /**
  44483. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44484. */
  44485. _this._invertNormalMapX = false;
  44486. /**
  44487. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44488. */
  44489. _this._invertNormalMapY = false;
  44490. /**
  44491. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44492. */
  44493. _this._twoSidedLighting = false;
  44494. /**
  44495. * Defines the alpha limits in alpha test mode.
  44496. */
  44497. _this._alphaCutOff = 0.4;
  44498. /**
  44499. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44500. */
  44501. _this._forceAlphaTest = false;
  44502. /**
  44503. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44504. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44505. */
  44506. _this._useAlphaFresnel = false;
  44507. /**
  44508. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44509. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44510. */
  44511. _this._useLinearAlphaFresnel = false;
  44512. /**
  44513. * The transparency mode of the material.
  44514. */
  44515. _this._transparencyMode = null;
  44516. /**
  44517. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44518. * from cos thetav and roughness:
  44519. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44520. */
  44521. _this._environmentBRDFTexture = null;
  44522. /**
  44523. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44524. */
  44525. _this._forceIrradianceInFragment = false;
  44526. /**
  44527. * Force normal to face away from face.
  44528. */
  44529. _this._forceNormalForward = false;
  44530. /**
  44531. * Enables specular anti aliasing in the PBR shader.
  44532. * It will both interacts on the Geometry for analytical and IBL lighting.
  44533. * It also prefilter the roughness map based on the bump values.
  44534. */
  44535. _this._enableSpecularAntiAliasing = false;
  44536. /**
  44537. * Stores the available render targets.
  44538. */
  44539. _this._renderTargets = new BABYLON.SmartArray(16);
  44540. /**
  44541. * Sets the global ambient color for the material used in lighting calculations.
  44542. */
  44543. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44544. /**
  44545. * If set to true, no lighting calculations will be applied.
  44546. */
  44547. _this._unlit = false;
  44548. // Setup the default processing configuration to the scene.
  44549. _this._attachImageProcessingConfiguration(null);
  44550. _this.getRenderTargetTextures = function () {
  44551. _this._renderTargets.reset();
  44552. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44553. _this._renderTargets.push(_this._reflectionTexture);
  44554. }
  44555. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44556. _this._renderTargets.push(_this._refractionTexture);
  44557. }
  44558. return _this._renderTargets;
  44559. };
  44560. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44561. return _this;
  44562. }
  44563. /**
  44564. * Attaches a new image processing configuration to the PBR Material.
  44565. * @param configuration
  44566. */
  44567. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44568. var _this = this;
  44569. if (configuration === this._imageProcessingConfiguration) {
  44570. return;
  44571. }
  44572. // Detaches observer.
  44573. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44574. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44575. }
  44576. // Pick the scene configuration if needed.
  44577. if (!configuration) {
  44578. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44579. }
  44580. else {
  44581. this._imageProcessingConfiguration = configuration;
  44582. }
  44583. // Attaches observer.
  44584. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44585. _this._markAllSubMeshesAsImageProcessingDirty();
  44586. });
  44587. };
  44588. /**
  44589. * Gets the name of the material class.
  44590. */
  44591. PBRBaseMaterial.prototype.getClassName = function () {
  44592. return "PBRBaseMaterial";
  44593. };
  44594. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44595. /**
  44596. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44597. */
  44598. get: function () {
  44599. return this._useLogarithmicDepth;
  44600. },
  44601. /**
  44602. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44603. */
  44604. set: function (value) {
  44605. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44606. },
  44607. enumerable: true,
  44608. configurable: true
  44609. });
  44610. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44611. /**
  44612. * Gets the current transparency mode.
  44613. */
  44614. get: function () {
  44615. return this._transparencyMode;
  44616. },
  44617. /**
  44618. * Sets the transparency mode of the material.
  44619. */
  44620. set: function (value) {
  44621. if (this._transparencyMode === value) {
  44622. return;
  44623. }
  44624. this._transparencyMode = value;
  44625. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44626. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44627. },
  44628. enumerable: true,
  44629. configurable: true
  44630. });
  44631. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44632. /**
  44633. * Returns true if alpha blending should be disabled.
  44634. */
  44635. get: function () {
  44636. return (this._linkRefractionWithTransparency ||
  44637. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44638. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44639. },
  44640. enumerable: true,
  44641. configurable: true
  44642. });
  44643. /**
  44644. * Specifies whether or not this material should be rendered in alpha blend mode.
  44645. */
  44646. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44647. if (this._disableAlphaBlending) {
  44648. return false;
  44649. }
  44650. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44651. };
  44652. /**
  44653. * Specifies if the mesh will require alpha blending.
  44654. * @param mesh - BJS mesh.
  44655. */
  44656. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44657. if (this._disableAlphaBlending) {
  44658. return false;
  44659. }
  44660. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44661. };
  44662. /**
  44663. * Specifies whether or not this material should be rendered in alpha test mode.
  44664. */
  44665. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44666. if (this._forceAlphaTest) {
  44667. return true;
  44668. }
  44669. if (this._linkRefractionWithTransparency) {
  44670. return false;
  44671. }
  44672. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44673. };
  44674. /**
  44675. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44676. */
  44677. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44678. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44679. };
  44680. /**
  44681. * Gets the texture used for the alpha test.
  44682. */
  44683. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44684. return this._albedoTexture;
  44685. };
  44686. /**
  44687. * Specifies that the submesh is ready to be used.
  44688. * @param mesh - BJS mesh.
  44689. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44690. * @param useInstances - Specifies that instances should be used.
  44691. * @returns - boolean indicating that the submesh is ready or not.
  44692. */
  44693. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44694. if (subMesh.effect && this.isFrozen) {
  44695. if (this._wasPreviouslyReady) {
  44696. return true;
  44697. }
  44698. }
  44699. if (!subMesh._materialDefines) {
  44700. subMesh._materialDefines = new PBRMaterialDefines();
  44701. }
  44702. var defines = subMesh._materialDefines;
  44703. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44704. if (defines._renderId === this.getScene().getRenderId()) {
  44705. return true;
  44706. }
  44707. }
  44708. var scene = this.getScene();
  44709. var engine = scene.getEngine();
  44710. if (defines._areTexturesDirty) {
  44711. if (scene.texturesEnabled) {
  44712. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44713. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44714. return false;
  44715. }
  44716. }
  44717. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44718. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44719. return false;
  44720. }
  44721. }
  44722. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44723. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44724. return false;
  44725. }
  44726. }
  44727. var reflectionTexture = this._getReflectionTexture();
  44728. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44729. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44730. return false;
  44731. }
  44732. }
  44733. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44734. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44735. return false;
  44736. }
  44737. }
  44738. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44739. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44740. return false;
  44741. }
  44742. }
  44743. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44744. if (this._metallicTexture) {
  44745. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44746. return false;
  44747. }
  44748. }
  44749. else if (this._reflectivityTexture) {
  44750. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44751. return false;
  44752. }
  44753. }
  44754. if (this._microSurfaceTexture) {
  44755. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44756. return false;
  44757. }
  44758. }
  44759. }
  44760. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44761. // Bump texture cannot be not blocking.
  44762. if (!this._bumpTexture.isReady()) {
  44763. return false;
  44764. }
  44765. }
  44766. var refractionTexture = this._getRefractionTexture();
  44767. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44768. if (!refractionTexture.isReadyOrNotBlocking()) {
  44769. return false;
  44770. }
  44771. }
  44772. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44773. // This is blocking.
  44774. if (!this._environmentBRDFTexture.isReady()) {
  44775. return false;
  44776. }
  44777. }
  44778. }
  44779. }
  44780. if (defines._areImageProcessingDirty) {
  44781. if (!this._imageProcessingConfiguration.isReady()) {
  44782. return false;
  44783. }
  44784. }
  44785. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44786. mesh.createNormals(true);
  44787. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44788. }
  44789. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44790. if (effect) {
  44791. scene.resetCachedMaterial();
  44792. subMesh.setEffect(effect, defines);
  44793. this.buildUniformLayout();
  44794. }
  44795. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44796. return false;
  44797. }
  44798. defines._renderId = scene.getRenderId();
  44799. this._wasPreviouslyReady = true;
  44800. return true;
  44801. };
  44802. /**
  44803. * Specifies if the material uses metallic roughness workflow.
  44804. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44805. */
  44806. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44807. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44808. return true;
  44809. }
  44810. return false;
  44811. };
  44812. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44813. if (onCompiled === void 0) { onCompiled = null; }
  44814. if (onError === void 0) { onError = null; }
  44815. if (useInstances === void 0) { useInstances = null; }
  44816. if (useClipPlane === void 0) { useClipPlane = null; }
  44817. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44818. if (!defines.isDirty) {
  44819. return null;
  44820. }
  44821. defines.markAsProcessed();
  44822. var scene = this.getScene();
  44823. var engine = scene.getEngine();
  44824. // Fallbacks
  44825. var fallbacks = new BABYLON.EffectFallbacks();
  44826. var fallbackRank = 0;
  44827. if (defines.USESPHERICALINVERTEX) {
  44828. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44829. }
  44830. if (defines.FOG) {
  44831. fallbacks.addFallback(fallbackRank, "FOG");
  44832. }
  44833. if (defines.POINTSIZE) {
  44834. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44835. }
  44836. if (defines.LOGARITHMICDEPTH) {
  44837. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44838. }
  44839. if (defines.PARALLAX) {
  44840. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44841. }
  44842. if (defines.PARALLAXOCCLUSION) {
  44843. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44844. }
  44845. if (defines.ENVIRONMENTBRDF) {
  44846. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44847. }
  44848. if (defines.TANGENT) {
  44849. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44850. }
  44851. if (defines.BUMP) {
  44852. fallbacks.addFallback(fallbackRank++, "BUMP");
  44853. }
  44854. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44855. if (defines.SPECULARTERM) {
  44856. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44857. }
  44858. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44859. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44860. }
  44861. if (defines.LIGHTMAP) {
  44862. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44863. }
  44864. if (defines.NORMAL) {
  44865. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44866. }
  44867. if (defines.AMBIENT) {
  44868. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44869. }
  44870. if (defines.EMISSIVE) {
  44871. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44872. }
  44873. if (defines.VERTEXCOLOR) {
  44874. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44875. }
  44876. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44877. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44878. }
  44879. if (defines.MORPHTARGETS) {
  44880. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44881. }
  44882. //Attributes
  44883. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44884. if (defines.NORMAL) {
  44885. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44886. }
  44887. if (defines.TANGENT) {
  44888. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44889. }
  44890. if (defines.UV1) {
  44891. attribs.push(BABYLON.VertexBuffer.UVKind);
  44892. }
  44893. if (defines.UV2) {
  44894. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44895. }
  44896. if (defines.VERTEXCOLOR) {
  44897. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44898. }
  44899. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44900. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44901. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44902. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44903. "vFogInfos", "vFogColor", "pointSize",
  44904. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44905. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44906. "mBones",
  44907. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44908. "vLightingIntensity",
  44909. "logarithmicDepthConstant",
  44910. "vSphericalX", "vSphericalY", "vSphericalZ",
  44911. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44912. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44913. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44914. "vTangentSpaceParams"
  44915. ];
  44916. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44917. "bumpSampler", "lightmapSampler", "opacitySampler",
  44918. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44919. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44920. "microSurfaceSampler", "environmentBrdfSampler"];
  44921. var uniformBuffers = ["Material", "Scene"];
  44922. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44923. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44924. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44925. uniformsNames: uniforms,
  44926. uniformBuffersNames: uniformBuffers,
  44927. samplers: samplers,
  44928. defines: defines,
  44929. maxSimultaneousLights: this._maxSimultaneousLights
  44930. });
  44931. var join = defines.toString();
  44932. return engine.createEffect("pbr", {
  44933. attributes: attribs,
  44934. uniformsNames: uniforms,
  44935. uniformBuffersNames: uniformBuffers,
  44936. samplers: samplers,
  44937. defines: join,
  44938. fallbacks: fallbacks,
  44939. onCompiled: onCompiled,
  44940. onError: onError,
  44941. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44942. }, engine);
  44943. };
  44944. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44945. if (useInstances === void 0) { useInstances = null; }
  44946. if (useClipPlane === void 0) { useClipPlane = null; }
  44947. var scene = this.getScene();
  44948. var engine = scene.getEngine();
  44949. // Lights
  44950. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44951. defines._needNormals = true;
  44952. // Textures
  44953. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44954. if (defines._areTexturesDirty) {
  44955. defines._needUVs = false;
  44956. if (scene.texturesEnabled) {
  44957. if (scene.getEngine().getCaps().textureLOD) {
  44958. defines.LODBASEDMICROSFURACE = true;
  44959. }
  44960. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44961. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44962. }
  44963. else {
  44964. defines.ALBEDO = false;
  44965. }
  44966. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44967. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44968. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44969. }
  44970. else {
  44971. defines.AMBIENT = false;
  44972. }
  44973. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44974. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44975. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44976. }
  44977. else {
  44978. defines.OPACITY = false;
  44979. }
  44980. var reflectionTexture = this._getReflectionTexture();
  44981. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44982. defines.REFLECTION = true;
  44983. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44984. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44985. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44986. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44987. defines.INVERTCUBICMAP = true;
  44988. }
  44989. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44990. switch (reflectionTexture.coordinatesMode) {
  44991. case BABYLON.Texture.EXPLICIT_MODE:
  44992. defines.REFLECTIONMAP_EXPLICIT = true;
  44993. break;
  44994. case BABYLON.Texture.PLANAR_MODE:
  44995. defines.REFLECTIONMAP_PLANAR = true;
  44996. break;
  44997. case BABYLON.Texture.PROJECTION_MODE:
  44998. defines.REFLECTIONMAP_PROJECTION = true;
  44999. break;
  45000. case BABYLON.Texture.SKYBOX_MODE:
  45001. defines.REFLECTIONMAP_SKYBOX = true;
  45002. break;
  45003. case BABYLON.Texture.SPHERICAL_MODE:
  45004. defines.REFLECTIONMAP_SPHERICAL = true;
  45005. break;
  45006. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45007. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45008. break;
  45009. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45010. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45011. break;
  45012. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45013. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45014. break;
  45015. case BABYLON.Texture.CUBIC_MODE:
  45016. case BABYLON.Texture.INVCUBIC_MODE:
  45017. default:
  45018. defines.REFLECTIONMAP_CUBIC = true;
  45019. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45020. break;
  45021. }
  45022. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45023. if (reflectionTexture.sphericalPolynomial) {
  45024. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45025. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45026. defines.USESPHERICALINVERTEX = false;
  45027. }
  45028. else {
  45029. defines.USESPHERICALINVERTEX = true;
  45030. }
  45031. }
  45032. }
  45033. }
  45034. else {
  45035. defines.REFLECTION = false;
  45036. defines.REFLECTIONMAP_3D = false;
  45037. defines.REFLECTIONMAP_SPHERICAL = false;
  45038. defines.REFLECTIONMAP_PLANAR = false;
  45039. defines.REFLECTIONMAP_CUBIC = false;
  45040. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45041. defines.REFLECTIONMAP_PROJECTION = false;
  45042. defines.REFLECTIONMAP_SKYBOX = false;
  45043. defines.REFLECTIONMAP_EXPLICIT = false;
  45044. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45045. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45046. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45047. defines.INVERTCUBICMAP = false;
  45048. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45049. defines.USESPHERICALINVERTEX = false;
  45050. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45051. defines.LODINREFLECTIONALPHA = false;
  45052. defines.GAMMAREFLECTION = false;
  45053. }
  45054. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45055. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45056. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45057. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45058. }
  45059. else {
  45060. defines.LIGHTMAP = false;
  45061. }
  45062. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45063. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45064. }
  45065. else {
  45066. defines.EMISSIVE = false;
  45067. }
  45068. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45069. if (this._metallicTexture) {
  45070. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45071. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45072. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45073. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45074. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45075. }
  45076. else if (this._reflectivityTexture) {
  45077. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45078. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45079. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45080. }
  45081. else {
  45082. defines.REFLECTIVITY = false;
  45083. }
  45084. if (this._microSurfaceTexture) {
  45085. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45086. }
  45087. else {
  45088. defines.MICROSURFACEMAP = false;
  45089. }
  45090. }
  45091. else {
  45092. defines.REFLECTIVITY = false;
  45093. defines.MICROSURFACEMAP = false;
  45094. }
  45095. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45096. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45097. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45098. defines.PARALLAX = true;
  45099. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45100. }
  45101. else {
  45102. defines.PARALLAX = false;
  45103. }
  45104. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45105. }
  45106. else {
  45107. defines.BUMP = false;
  45108. }
  45109. var refractionTexture = this._getRefractionTexture();
  45110. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45111. defines.REFRACTION = true;
  45112. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45113. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45114. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45115. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45116. if (this._linkRefractionWithTransparency) {
  45117. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45118. }
  45119. }
  45120. else {
  45121. defines.REFRACTION = false;
  45122. }
  45123. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45124. defines.ENVIRONMENTBRDF = true;
  45125. }
  45126. else {
  45127. defines.ENVIRONMENTBRDF = false;
  45128. }
  45129. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45130. defines.ALPHAFROMALBEDO = true;
  45131. }
  45132. else {
  45133. defines.ALPHAFROMALBEDO = false;
  45134. }
  45135. }
  45136. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45137. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  45138. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45139. if (!this.backFaceCulling && this._twoSidedLighting) {
  45140. defines.TWOSIDEDLIGHTING = true;
  45141. }
  45142. else {
  45143. defines.TWOSIDEDLIGHTING = false;
  45144. }
  45145. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45146. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45147. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45148. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45149. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45150. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45151. }
  45152. if (defines._areImageProcessingDirty) {
  45153. this._imageProcessingConfiguration.prepareDefines(defines);
  45154. }
  45155. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45156. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45157. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45158. // Misc.
  45159. if (defines._areMiscDirty) {
  45160. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45161. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45162. }
  45163. // Values that need to be evaluated on every frame
  45164. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45165. // Attribs
  45166. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45167. };
  45168. /**
  45169. * Force shader compilation
  45170. */
  45171. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45172. var _this = this;
  45173. var localOptions = __assign({ clipPlane: false }, options);
  45174. var defines = new PBRMaterialDefines();
  45175. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45176. if (effect.isReady()) {
  45177. if (onCompiled) {
  45178. onCompiled(this);
  45179. }
  45180. }
  45181. else {
  45182. effect.onCompileObservable.add(function () {
  45183. if (onCompiled) {
  45184. onCompiled(_this);
  45185. }
  45186. });
  45187. }
  45188. };
  45189. /**
  45190. * Initializes the uniform buffer layout for the shader.
  45191. */
  45192. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45193. // Order is important !
  45194. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45195. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  45196. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45197. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45198. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45199. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45200. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45201. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45202. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45203. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45204. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45205. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45206. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45207. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45208. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45209. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45210. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45211. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45212. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45213. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45214. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45215. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45216. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45217. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45218. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45219. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45220. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45221. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45222. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45223. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45224. this._uniformBuffer.addUniform("pointSize", 1);
  45225. this._uniformBuffer.create();
  45226. };
  45227. /**
  45228. * Unbinds the textures.
  45229. */
  45230. PBRBaseMaterial.prototype.unbind = function () {
  45231. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45232. this._uniformBuffer.setTexture("reflectionSampler", null);
  45233. }
  45234. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45235. this._uniformBuffer.setTexture("refractionSampler", null);
  45236. }
  45237. _super.prototype.unbind.call(this);
  45238. };
  45239. /**
  45240. * Binds the submesh data.
  45241. * @param world - The world matrix.
  45242. * @param mesh - The BJS mesh.
  45243. * @param subMesh - A submesh of the BJS mesh.
  45244. */
  45245. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45246. var scene = this.getScene();
  45247. var defines = subMesh._materialDefines;
  45248. if (!defines) {
  45249. return;
  45250. }
  45251. var effect = subMesh.effect;
  45252. if (!effect) {
  45253. return;
  45254. }
  45255. this._activeEffect = effect;
  45256. // Matrices
  45257. this.bindOnlyWorldMatrix(world);
  45258. // Normal Matrix
  45259. if (defines.OBJECTSPACE_NORMALMAP) {
  45260. world.toNormalMatrix(this._normalMatrix);
  45261. this.bindOnlyNormalMatrix(this._normalMatrix);
  45262. }
  45263. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45264. // Bones
  45265. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45266. var reflectionTexture = null;
  45267. if (mustRebind) {
  45268. this._uniformBuffer.bindToEffect(effect, "Material");
  45269. this.bindViewProjection(effect);
  45270. reflectionTexture = this._getReflectionTexture();
  45271. var refractionTexture = this._getRefractionTexture();
  45272. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45273. // Texture uniforms
  45274. if (scene.texturesEnabled) {
  45275. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45276. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45277. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45278. }
  45279. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45280. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  45281. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45282. }
  45283. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45284. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45285. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45286. }
  45287. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45288. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45289. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45290. if (reflectionTexture.boundingBoxSize) {
  45291. var cubeTexture = reflectionTexture;
  45292. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45293. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45294. }
  45295. var polynomials = reflectionTexture.sphericalPolynomial;
  45296. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45297. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45298. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45299. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45300. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45301. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45302. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45303. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45304. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45305. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45306. }
  45307. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45308. }
  45309. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45310. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45311. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45312. }
  45313. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45314. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45315. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45316. }
  45317. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45318. if (this._metallicTexture) {
  45319. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45320. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45321. }
  45322. else if (this._reflectivityTexture) {
  45323. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45324. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45325. }
  45326. if (this._microSurfaceTexture) {
  45327. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45328. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45329. }
  45330. }
  45331. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45332. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45333. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45334. if (scene._mirroredCameraPosition) {
  45335. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45336. }
  45337. else {
  45338. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45339. }
  45340. }
  45341. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45342. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45343. var depth = 1.0;
  45344. if (!refractionTexture.isCube) {
  45345. if (refractionTexture.depth) {
  45346. depth = refractionTexture.depth;
  45347. }
  45348. }
  45349. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45350. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45351. }
  45352. }
  45353. // Point size
  45354. if (this.pointsCloud) {
  45355. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45356. }
  45357. // Colors
  45358. if (defines.METALLICWORKFLOW) {
  45359. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45360. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45361. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45362. }
  45363. else {
  45364. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45365. }
  45366. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45367. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45368. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45369. // Misc
  45370. this._lightingInfos.x = this._directIntensity;
  45371. this._lightingInfos.y = this._emissiveIntensity;
  45372. this._lightingInfos.z = this._environmentIntensity;
  45373. this._lightingInfos.w = this._specularIntensity;
  45374. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45375. }
  45376. // Textures
  45377. if (scene.texturesEnabled) {
  45378. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45379. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45380. }
  45381. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45382. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45383. }
  45384. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45385. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45386. }
  45387. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45388. if (defines.LODBASEDMICROSFURACE) {
  45389. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45390. }
  45391. else {
  45392. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45393. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45394. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45395. }
  45396. }
  45397. if (defines.ENVIRONMENTBRDF) {
  45398. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45399. }
  45400. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45401. if (defines.LODBASEDMICROSFURACE) {
  45402. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45403. }
  45404. else {
  45405. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45406. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45407. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45408. }
  45409. }
  45410. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45411. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45412. }
  45413. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45414. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45415. }
  45416. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45417. if (this._metallicTexture) {
  45418. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45419. }
  45420. else if (this._reflectivityTexture) {
  45421. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45422. }
  45423. if (this._microSurfaceTexture) {
  45424. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45425. }
  45426. }
  45427. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45428. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45429. }
  45430. }
  45431. // Clip plane
  45432. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45433. // Colors
  45434. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45435. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45436. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45437. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45438. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45439. }
  45440. if (mustRebind || !this.isFrozen) {
  45441. // Lights
  45442. if (scene.lightsEnabled && !this._disableLighting) {
  45443. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45444. }
  45445. // View
  45446. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45447. this.bindView(effect);
  45448. }
  45449. // Fog
  45450. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45451. // Morph targets
  45452. if (defines.NUM_MORPH_INFLUENCERS) {
  45453. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45454. }
  45455. // image processing
  45456. this._imageProcessingConfiguration.bind(this._activeEffect);
  45457. // Log. depth
  45458. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45459. }
  45460. this._uniformBuffer.update();
  45461. this._afterBind(mesh);
  45462. };
  45463. /**
  45464. * Returns the animatable textures.
  45465. * @returns - Array of animatable textures.
  45466. */
  45467. PBRBaseMaterial.prototype.getAnimatables = function () {
  45468. var results = [];
  45469. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45470. results.push(this._albedoTexture);
  45471. }
  45472. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45473. results.push(this._ambientTexture);
  45474. }
  45475. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45476. results.push(this._opacityTexture);
  45477. }
  45478. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45479. results.push(this._reflectionTexture);
  45480. }
  45481. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45482. results.push(this._emissiveTexture);
  45483. }
  45484. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45485. results.push(this._metallicTexture);
  45486. }
  45487. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45488. results.push(this._reflectivityTexture);
  45489. }
  45490. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45491. results.push(this._bumpTexture);
  45492. }
  45493. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45494. results.push(this._lightmapTexture);
  45495. }
  45496. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45497. results.push(this._refractionTexture);
  45498. }
  45499. return results;
  45500. };
  45501. /**
  45502. * Returns the texture used for reflections.
  45503. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45504. */
  45505. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45506. if (this._reflectionTexture) {
  45507. return this._reflectionTexture;
  45508. }
  45509. return this.getScene().environmentTexture;
  45510. };
  45511. /**
  45512. * Returns the texture used for refraction or null if none is used.
  45513. * @returns - Refection texture if present. If no refraction texture and refraction
  45514. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45515. */
  45516. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45517. if (this._refractionTexture) {
  45518. return this._refractionTexture;
  45519. }
  45520. if (this._linkRefractionWithTransparency) {
  45521. return this.getScene().environmentTexture;
  45522. }
  45523. return null;
  45524. };
  45525. /**
  45526. * Disposes the resources of the material.
  45527. * @param forceDisposeEffect - Forces the disposal of effects.
  45528. * @param forceDisposeTextures - Forces the disposal of all textures.
  45529. */
  45530. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45531. if (forceDisposeTextures) {
  45532. if (this._albedoTexture) {
  45533. this._albedoTexture.dispose();
  45534. }
  45535. if (this._ambientTexture) {
  45536. this._ambientTexture.dispose();
  45537. }
  45538. if (this._opacityTexture) {
  45539. this._opacityTexture.dispose();
  45540. }
  45541. if (this._reflectionTexture) {
  45542. this._reflectionTexture.dispose();
  45543. }
  45544. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45545. this._environmentBRDFTexture.dispose();
  45546. }
  45547. if (this._emissiveTexture) {
  45548. this._emissiveTexture.dispose();
  45549. }
  45550. if (this._metallicTexture) {
  45551. this._metallicTexture.dispose();
  45552. }
  45553. if (this._reflectivityTexture) {
  45554. this._reflectivityTexture.dispose();
  45555. }
  45556. if (this._bumpTexture) {
  45557. this._bumpTexture.dispose();
  45558. }
  45559. if (this._lightmapTexture) {
  45560. this._lightmapTexture.dispose();
  45561. }
  45562. if (this._refractionTexture) {
  45563. this._refractionTexture.dispose();
  45564. }
  45565. }
  45566. this._renderTargets.dispose();
  45567. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45568. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45569. }
  45570. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45571. };
  45572. /**
  45573. * Stores the reflectivity values based on metallic roughness workflow.
  45574. */
  45575. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45576. __decorate([
  45577. BABYLON.serializeAsImageProcessingConfiguration()
  45578. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45579. __decorate([
  45580. BABYLON.serialize()
  45581. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45582. __decorate([
  45583. BABYLON.serialize()
  45584. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45585. return PBRBaseMaterial;
  45586. }(BABYLON.PushMaterial));
  45587. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45588. })(BABYLON || (BABYLON = {}));
  45589. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45590. var BABYLON;
  45591. (function (BABYLON) {
  45592. /**
  45593. * The Physically based simple base material of BJS.
  45594. *
  45595. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45596. * It is used as the base class for both the specGloss and metalRough conventions.
  45597. */
  45598. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45599. __extends(PBRBaseSimpleMaterial, _super);
  45600. /**
  45601. * Instantiates a new PBRMaterial instance.
  45602. *
  45603. * @param name The material name
  45604. * @param scene The scene the material will be use in.
  45605. */
  45606. function PBRBaseSimpleMaterial(name, scene) {
  45607. var _this = _super.call(this, name, scene) || this;
  45608. /**
  45609. * Number of Simultaneous lights allowed on the material.
  45610. */
  45611. _this.maxSimultaneousLights = 4;
  45612. /**
  45613. * If sets to true, disables all the lights affecting the material.
  45614. */
  45615. _this.disableLighting = false;
  45616. /**
  45617. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45618. */
  45619. _this.invertNormalMapX = false;
  45620. /**
  45621. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45622. */
  45623. _this.invertNormalMapY = false;
  45624. /**
  45625. * Emissivie color used to self-illuminate the model.
  45626. */
  45627. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45628. /**
  45629. * Occlusion Channel Strenght.
  45630. */
  45631. _this.occlusionStrength = 1.0;
  45632. _this.useLightmapAsShadowmap = false;
  45633. _this._useAlphaFromAlbedoTexture = true;
  45634. _this._useAmbientInGrayScale = true;
  45635. return _this;
  45636. }
  45637. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45638. /**
  45639. * Gets the current double sided mode.
  45640. */
  45641. get: function () {
  45642. return this._twoSidedLighting;
  45643. },
  45644. /**
  45645. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45646. */
  45647. set: function (value) {
  45648. if (this._twoSidedLighting === value) {
  45649. return;
  45650. }
  45651. this._twoSidedLighting = value;
  45652. this.backFaceCulling = !value;
  45653. this._markAllSubMeshesAsTexturesDirty();
  45654. },
  45655. enumerable: true,
  45656. configurable: true
  45657. });
  45658. /**
  45659. * Return the active textures of the material.
  45660. */
  45661. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45662. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45663. if (this.environmentTexture) {
  45664. activeTextures.push(this.environmentTexture);
  45665. }
  45666. if (this.normalTexture) {
  45667. activeTextures.push(this.normalTexture);
  45668. }
  45669. if (this.emissiveTexture) {
  45670. activeTextures.push(this.emissiveTexture);
  45671. }
  45672. if (this.occlusionTexture) {
  45673. activeTextures.push(this.occlusionTexture);
  45674. }
  45675. if (this.lightmapTexture) {
  45676. activeTextures.push(this.lightmapTexture);
  45677. }
  45678. return activeTextures;
  45679. };
  45680. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45681. if (_super.prototype.hasTexture.call(this, texture)) {
  45682. return true;
  45683. }
  45684. if (this.lightmapTexture === texture) {
  45685. return true;
  45686. }
  45687. return false;
  45688. };
  45689. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45690. return "PBRBaseSimpleMaterial";
  45691. };
  45692. __decorate([
  45693. BABYLON.serialize(),
  45694. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45695. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45696. __decorate([
  45697. BABYLON.serialize(),
  45698. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45699. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45700. __decorate([
  45701. BABYLON.serializeAsTexture(),
  45702. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45703. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45704. __decorate([
  45705. BABYLON.serialize(),
  45706. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45707. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45708. __decorate([
  45709. BABYLON.serialize(),
  45710. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45711. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45712. __decorate([
  45713. BABYLON.serializeAsTexture(),
  45714. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45715. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45716. __decorate([
  45717. BABYLON.serializeAsColor3("emissive"),
  45718. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45719. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45720. __decorate([
  45721. BABYLON.serializeAsTexture(),
  45722. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45723. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45724. __decorate([
  45725. BABYLON.serialize(),
  45726. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45727. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45728. __decorate([
  45729. BABYLON.serializeAsTexture(),
  45730. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45731. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45732. __decorate([
  45733. BABYLON.serialize(),
  45734. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45735. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45736. __decorate([
  45737. BABYLON.serialize()
  45738. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45739. __decorate([
  45740. BABYLON.serializeAsTexture(),
  45741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45742. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45743. __decorate([
  45744. BABYLON.serialize(),
  45745. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45746. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45747. return PBRBaseSimpleMaterial;
  45748. }(BABYLON.PBRBaseMaterial));
  45749. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45750. })(BABYLON || (BABYLON = {}));
  45751. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45752. var BABYLON;
  45753. (function (BABYLON) {
  45754. /**
  45755. * The Physically based material of BJS.
  45756. *
  45757. * This offers the main features of a standard PBR material.
  45758. * For more information, please refer to the documentation :
  45759. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45760. */
  45761. var PBRMaterial = /** @class */ (function (_super) {
  45762. __extends(PBRMaterial, _super);
  45763. /**
  45764. * Instantiates a new PBRMaterial instance.
  45765. *
  45766. * @param name The material name
  45767. * @param scene The scene the material will be use in.
  45768. */
  45769. function PBRMaterial(name, scene) {
  45770. var _this = _super.call(this, name, scene) || this;
  45771. /**
  45772. * Intensity of the direct lights e.g. the four lights available in your scene.
  45773. * This impacts both the direct diffuse and specular highlights.
  45774. */
  45775. _this.directIntensity = 1.0;
  45776. /**
  45777. * Intensity of the emissive part of the material.
  45778. * This helps controlling the emissive effect without modifying the emissive color.
  45779. */
  45780. _this.emissiveIntensity = 1.0;
  45781. /**
  45782. * Intensity of the environment e.g. how much the environment will light the object
  45783. * either through harmonics for rough material or through the refelction for shiny ones.
  45784. */
  45785. _this.environmentIntensity = 1.0;
  45786. /**
  45787. * This is a special control allowing the reduction of the specular highlights coming from the
  45788. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45789. */
  45790. _this.specularIntensity = 1.0;
  45791. /**
  45792. * Debug Control allowing disabling the bump map on this material.
  45793. */
  45794. _this.disableBumpMap = false;
  45795. /**
  45796. * AKA Occlusion Texture Intensity in other nomenclature.
  45797. */
  45798. _this.ambientTextureStrength = 1.0;
  45799. /**
  45800. * The color of a material in ambient lighting.
  45801. */
  45802. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45803. /**
  45804. * AKA Diffuse Color in other nomenclature.
  45805. */
  45806. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45807. /**
  45808. * AKA Specular Color in other nomenclature.
  45809. */
  45810. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45811. /**
  45812. * The color reflected from the material.
  45813. */
  45814. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45815. /**
  45816. * The color emitted from the material.
  45817. */
  45818. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45819. /**
  45820. * AKA Glossiness in other nomenclature.
  45821. */
  45822. _this.microSurface = 1.0;
  45823. /**
  45824. * source material index of refraction (IOR)' / 'destination material IOR.
  45825. */
  45826. _this.indexOfRefraction = 0.66;
  45827. /**
  45828. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45829. */
  45830. _this.invertRefractionY = false;
  45831. /**
  45832. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45833. * Materials half opaque for instance using refraction could benefit from this control.
  45834. */
  45835. _this.linkRefractionWithTransparency = false;
  45836. _this.useLightmapAsShadowmap = false;
  45837. /**
  45838. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45839. */
  45840. _this.useAlphaFromAlbedoTexture = false;
  45841. /**
  45842. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45843. */
  45844. _this.forceAlphaTest = false;
  45845. /**
  45846. * Defines the alpha limits in alpha test mode.
  45847. */
  45848. _this.alphaCutOff = 0.4;
  45849. /**
  45850. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45851. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45852. */
  45853. _this.useSpecularOverAlpha = true;
  45854. /**
  45855. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45856. */
  45857. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45858. /**
  45859. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45860. */
  45861. _this.useRoughnessFromMetallicTextureAlpha = true;
  45862. /**
  45863. * Specifies if the metallic texture contains the roughness information in its green channel.
  45864. */
  45865. _this.useRoughnessFromMetallicTextureGreen = false;
  45866. /**
  45867. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45868. */
  45869. _this.useMetallnessFromMetallicTextureBlue = false;
  45870. /**
  45871. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45872. */
  45873. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45874. /**
  45875. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45876. */
  45877. _this.useAmbientInGrayScale = false;
  45878. /**
  45879. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45880. * The material will try to infer what glossiness each pixel should be.
  45881. */
  45882. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45883. /**
  45884. * BJS is using an harcoded light falloff based on a manually sets up range.
  45885. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45886. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45887. */
  45888. _this.usePhysicalLightFalloff = true;
  45889. /**
  45890. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45891. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45892. */
  45893. _this.useRadianceOverAlpha = true;
  45894. /**
  45895. * Allows using an object space normal map (instead of tangent space).
  45896. */
  45897. _this.useObjectSpaceNormalMap = false;
  45898. /**
  45899. * Allows using the bump map in parallax mode.
  45900. */
  45901. _this.useParallax = false;
  45902. /**
  45903. * Allows using the bump map in parallax occlusion mode.
  45904. */
  45905. _this.useParallaxOcclusion = false;
  45906. /**
  45907. * Controls the scale bias of the parallax mode.
  45908. */
  45909. _this.parallaxScaleBias = 0.05;
  45910. /**
  45911. * If sets to true, disables all the lights affecting the material.
  45912. */
  45913. _this.disableLighting = false;
  45914. /**
  45915. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45916. */
  45917. _this.forceIrradianceInFragment = false;
  45918. /**
  45919. * Number of Simultaneous lights allowed on the material.
  45920. */
  45921. _this.maxSimultaneousLights = 4;
  45922. /**
  45923. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45924. */
  45925. _this.invertNormalMapX = false;
  45926. /**
  45927. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45928. */
  45929. _this.invertNormalMapY = false;
  45930. /**
  45931. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45932. */
  45933. _this.twoSidedLighting = false;
  45934. /**
  45935. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45936. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45937. */
  45938. _this.useAlphaFresnel = false;
  45939. /**
  45940. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45941. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45942. */
  45943. _this.useLinearAlphaFresnel = false;
  45944. /**
  45945. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45946. * And/Or occlude the blended part.
  45947. */
  45948. _this.environmentBRDFTexture = null;
  45949. /**
  45950. * Force normal to face away from face.
  45951. */
  45952. _this.forceNormalForward = false;
  45953. /**
  45954. * Enables specular anti aliasing in the PBR shader.
  45955. * It will both interacts on the Geometry for analytical and IBL lighting.
  45956. * It also prefilter the roughness map based on the bump values.
  45957. */
  45958. _this.enableSpecularAntiAliasing = false;
  45959. /**
  45960. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45961. * makes the reflect vector face the model (under horizon).
  45962. */
  45963. _this.useHorizonOcclusion = true;
  45964. /**
  45965. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45966. * too much the area relying on ambient texture to define their ambient occlusion.
  45967. */
  45968. _this.useRadianceOcclusion = true;
  45969. /**
  45970. * If set to true, no lighting calculations will be applied.
  45971. */
  45972. _this.unlit = false;
  45973. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45974. return _this;
  45975. }
  45976. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45977. /**
  45978. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45979. */
  45980. get: function () {
  45981. return this._PBRMATERIAL_OPAQUE;
  45982. },
  45983. enumerable: true,
  45984. configurable: true
  45985. });
  45986. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45987. /**
  45988. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45989. */
  45990. get: function () {
  45991. return this._PBRMATERIAL_ALPHATEST;
  45992. },
  45993. enumerable: true,
  45994. configurable: true
  45995. });
  45996. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45997. /**
  45998. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45999. */
  46000. get: function () {
  46001. return this._PBRMATERIAL_ALPHABLEND;
  46002. },
  46003. enumerable: true,
  46004. configurable: true
  46005. });
  46006. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  46007. /**
  46008. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46009. * They are also discarded below the alpha cutoff threshold to improve performances.
  46010. */
  46011. get: function () {
  46012. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  46013. },
  46014. enumerable: true,
  46015. configurable: true
  46016. });
  46017. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46018. /**
  46019. * Gets the image processing configuration used either in this material.
  46020. */
  46021. get: function () {
  46022. return this._imageProcessingConfiguration;
  46023. },
  46024. /**
  46025. * Sets the Default image processing configuration used either in the this material.
  46026. *
  46027. * If sets to null, the scene one is in use.
  46028. */
  46029. set: function (value) {
  46030. this._attachImageProcessingConfiguration(value);
  46031. // Ensure the effect will be rebuilt.
  46032. this._markAllSubMeshesAsTexturesDirty();
  46033. },
  46034. enumerable: true,
  46035. configurable: true
  46036. });
  46037. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46038. /**
  46039. * Gets wether the color curves effect is enabled.
  46040. */
  46041. get: function () {
  46042. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46043. },
  46044. /**
  46045. * Sets wether the color curves effect is enabled.
  46046. */
  46047. set: function (value) {
  46048. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46049. },
  46050. enumerable: true,
  46051. configurable: true
  46052. });
  46053. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46054. /**
  46055. * Gets wether the color grading effect is enabled.
  46056. */
  46057. get: function () {
  46058. return this.imageProcessingConfiguration.colorGradingEnabled;
  46059. },
  46060. /**
  46061. * Gets wether the color grading effect is enabled.
  46062. */
  46063. set: function (value) {
  46064. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46065. },
  46066. enumerable: true,
  46067. configurable: true
  46068. });
  46069. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46070. /**
  46071. * Gets wether tonemapping is enabled or not.
  46072. */
  46073. get: function () {
  46074. return this._imageProcessingConfiguration.toneMappingEnabled;
  46075. },
  46076. /**
  46077. * Sets wether tonemapping is enabled or not
  46078. */
  46079. set: function (value) {
  46080. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46081. },
  46082. enumerable: true,
  46083. configurable: true
  46084. });
  46085. ;
  46086. ;
  46087. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46088. /**
  46089. * The camera exposure used on this material.
  46090. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46091. * This corresponds to a photographic exposure.
  46092. */
  46093. get: function () {
  46094. return this._imageProcessingConfiguration.exposure;
  46095. },
  46096. /**
  46097. * The camera exposure used on this material.
  46098. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46099. * This corresponds to a photographic exposure.
  46100. */
  46101. set: function (value) {
  46102. this._imageProcessingConfiguration.exposure = value;
  46103. },
  46104. enumerable: true,
  46105. configurable: true
  46106. });
  46107. ;
  46108. ;
  46109. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46110. /**
  46111. * Gets The camera contrast used on this material.
  46112. */
  46113. get: function () {
  46114. return this._imageProcessingConfiguration.contrast;
  46115. },
  46116. /**
  46117. * Sets The camera contrast used on this material.
  46118. */
  46119. set: function (value) {
  46120. this._imageProcessingConfiguration.contrast = value;
  46121. },
  46122. enumerable: true,
  46123. configurable: true
  46124. });
  46125. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46126. /**
  46127. * Gets the Color Grading 2D Lookup Texture.
  46128. */
  46129. get: function () {
  46130. return this._imageProcessingConfiguration.colorGradingTexture;
  46131. },
  46132. /**
  46133. * Sets the Color Grading 2D Lookup Texture.
  46134. */
  46135. set: function (value) {
  46136. this._imageProcessingConfiguration.colorGradingTexture = value;
  46137. },
  46138. enumerable: true,
  46139. configurable: true
  46140. });
  46141. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46142. /**
  46143. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46144. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46145. * 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;
  46146. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46147. */
  46148. get: function () {
  46149. return this._imageProcessingConfiguration.colorCurves;
  46150. },
  46151. /**
  46152. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46153. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46154. * 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;
  46155. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46156. */
  46157. set: function (value) {
  46158. this._imageProcessingConfiguration.colorCurves = value;
  46159. },
  46160. enumerable: true,
  46161. configurable: true
  46162. });
  46163. /**
  46164. * Returns the name of this material class.
  46165. */
  46166. PBRMaterial.prototype.getClassName = function () {
  46167. return "PBRMaterial";
  46168. };
  46169. /**
  46170. * Returns an array of the actively used textures.
  46171. * @returns - Array of BaseTextures
  46172. */
  46173. PBRMaterial.prototype.getActiveTextures = function () {
  46174. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46175. if (this._albedoTexture) {
  46176. activeTextures.push(this._albedoTexture);
  46177. }
  46178. if (this._ambientTexture) {
  46179. activeTextures.push(this._ambientTexture);
  46180. }
  46181. if (this._opacityTexture) {
  46182. activeTextures.push(this._opacityTexture);
  46183. }
  46184. if (this._reflectionTexture) {
  46185. activeTextures.push(this._reflectionTexture);
  46186. }
  46187. if (this._emissiveTexture) {
  46188. activeTextures.push(this._emissiveTexture);
  46189. }
  46190. if (this._reflectivityTexture) {
  46191. activeTextures.push(this._reflectivityTexture);
  46192. }
  46193. if (this._metallicTexture) {
  46194. activeTextures.push(this._metallicTexture);
  46195. }
  46196. if (this._microSurfaceTexture) {
  46197. activeTextures.push(this._microSurfaceTexture);
  46198. }
  46199. if (this._bumpTexture) {
  46200. activeTextures.push(this._bumpTexture);
  46201. }
  46202. if (this._lightmapTexture) {
  46203. activeTextures.push(this._lightmapTexture);
  46204. }
  46205. if (this._refractionTexture) {
  46206. activeTextures.push(this._refractionTexture);
  46207. }
  46208. return activeTextures;
  46209. };
  46210. /**
  46211. * Checks to see if a texture is used in the material.
  46212. * @param texture - Base texture to use.
  46213. * @returns - Boolean specifying if a texture is used in the material.
  46214. */
  46215. PBRMaterial.prototype.hasTexture = function (texture) {
  46216. if (_super.prototype.hasTexture.call(this, texture)) {
  46217. return true;
  46218. }
  46219. if (this._albedoTexture === texture) {
  46220. return true;
  46221. }
  46222. if (this._ambientTexture === texture) {
  46223. return true;
  46224. }
  46225. if (this._opacityTexture === texture) {
  46226. return true;
  46227. }
  46228. if (this._reflectionTexture === texture) {
  46229. return true;
  46230. }
  46231. if (this._reflectivityTexture === texture) {
  46232. return true;
  46233. }
  46234. if (this._metallicTexture === texture) {
  46235. return true;
  46236. }
  46237. if (this._microSurfaceTexture === texture) {
  46238. return true;
  46239. }
  46240. if (this._bumpTexture === texture) {
  46241. return true;
  46242. }
  46243. if (this._lightmapTexture === texture) {
  46244. return true;
  46245. }
  46246. if (this._refractionTexture === texture) {
  46247. return true;
  46248. }
  46249. return false;
  46250. };
  46251. /**
  46252. * Makes a duplicate of the current material.
  46253. * @param name - name to use for the new material.
  46254. */
  46255. PBRMaterial.prototype.clone = function (name) {
  46256. var _this = this;
  46257. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46258. clone.id = name;
  46259. clone.name = name;
  46260. return clone;
  46261. };
  46262. /**
  46263. * Serializes this PBR Material.
  46264. * @returns - An object with the serialized material.
  46265. */
  46266. PBRMaterial.prototype.serialize = function () {
  46267. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46268. serializationObject.customType = "BABYLON.PBRMaterial";
  46269. return serializationObject;
  46270. };
  46271. // Statics
  46272. /**
  46273. * Parses a PBR Material from a serialized object.
  46274. * @param source - Serialized object.
  46275. * @param scene - BJS scene instance.
  46276. * @param rootUrl - url for the scene object
  46277. * @returns - PBRMaterial
  46278. */
  46279. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46280. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46281. };
  46282. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  46283. /**
  46284. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46285. */
  46286. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  46287. /**
  46288. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46289. */
  46290. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46291. /**
  46292. * 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.
  46293. * They are also discarded below the alpha cutoff threshold to improve performances.
  46294. */
  46295. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46296. __decorate([
  46297. BABYLON.serialize(),
  46298. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46299. ], PBRMaterial.prototype, "directIntensity", void 0);
  46300. __decorate([
  46301. BABYLON.serialize(),
  46302. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46303. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46304. __decorate([
  46305. BABYLON.serialize(),
  46306. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46307. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46308. __decorate([
  46309. BABYLON.serialize(),
  46310. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46311. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46312. __decorate([
  46313. BABYLON.serialize(),
  46314. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46315. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46316. __decorate([
  46317. BABYLON.serializeAsTexture(),
  46318. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46319. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46320. __decorate([
  46321. BABYLON.serializeAsTexture(),
  46322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46323. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46324. __decorate([
  46325. BABYLON.serialize(),
  46326. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46327. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46328. __decorate([
  46329. BABYLON.serializeAsTexture(),
  46330. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46331. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46332. __decorate([
  46333. BABYLON.serializeAsTexture(),
  46334. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46335. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46336. __decorate([
  46337. BABYLON.serializeAsTexture(),
  46338. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46339. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46340. __decorate([
  46341. BABYLON.serializeAsTexture(),
  46342. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46343. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46344. __decorate([
  46345. BABYLON.serializeAsTexture(),
  46346. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46347. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46348. __decorate([
  46349. BABYLON.serialize(),
  46350. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46351. ], PBRMaterial.prototype, "metallic", void 0);
  46352. __decorate([
  46353. BABYLON.serialize(),
  46354. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46355. ], PBRMaterial.prototype, "roughness", void 0);
  46356. __decorate([
  46357. BABYLON.serializeAsTexture(),
  46358. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46359. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46360. __decorate([
  46361. BABYLON.serializeAsTexture(),
  46362. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46363. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46364. __decorate([
  46365. BABYLON.serializeAsTexture(),
  46366. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46367. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46368. __decorate([
  46369. BABYLON.serializeAsTexture(),
  46370. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46371. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46372. __decorate([
  46373. BABYLON.serializeAsColor3("ambient"),
  46374. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46375. ], PBRMaterial.prototype, "ambientColor", void 0);
  46376. __decorate([
  46377. BABYLON.serializeAsColor3("albedo"),
  46378. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46379. ], PBRMaterial.prototype, "albedoColor", void 0);
  46380. __decorate([
  46381. BABYLON.serializeAsColor3("reflectivity"),
  46382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46383. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46384. __decorate([
  46385. BABYLON.serializeAsColor3("reflection"),
  46386. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46387. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46388. __decorate([
  46389. BABYLON.serializeAsColor3("emissive"),
  46390. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46391. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46392. __decorate([
  46393. BABYLON.serialize(),
  46394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46395. ], PBRMaterial.prototype, "microSurface", void 0);
  46396. __decorate([
  46397. BABYLON.serialize(),
  46398. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46399. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46400. __decorate([
  46401. BABYLON.serialize(),
  46402. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46403. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46404. __decorate([
  46405. BABYLON.serialize(),
  46406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46407. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46408. __decorate([
  46409. BABYLON.serialize(),
  46410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46411. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46412. __decorate([
  46413. BABYLON.serialize(),
  46414. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46415. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46416. __decorate([
  46417. BABYLON.serialize(),
  46418. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46419. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46420. __decorate([
  46421. BABYLON.serialize(),
  46422. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46423. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46424. __decorate([
  46425. BABYLON.serialize(),
  46426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46427. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46428. __decorate([
  46429. BABYLON.serialize(),
  46430. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46431. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46432. __decorate([
  46433. BABYLON.serialize(),
  46434. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46435. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46436. __decorate([
  46437. BABYLON.serialize(),
  46438. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46439. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46440. __decorate([
  46441. BABYLON.serialize(),
  46442. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46443. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46444. __decorate([
  46445. BABYLON.serialize(),
  46446. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46447. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46448. __decorate([
  46449. BABYLON.serialize(),
  46450. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46451. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46452. __decorate([
  46453. BABYLON.serialize(),
  46454. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46455. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46456. __decorate([
  46457. BABYLON.serialize(),
  46458. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46459. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46460. __decorate([
  46461. BABYLON.serialize(),
  46462. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46463. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46464. __decorate([
  46465. BABYLON.serialize(),
  46466. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46467. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46468. __decorate([
  46469. BABYLON.serialize(),
  46470. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46471. ], PBRMaterial.prototype, "useParallax", void 0);
  46472. __decorate([
  46473. BABYLON.serialize(),
  46474. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46475. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46476. __decorate([
  46477. BABYLON.serialize(),
  46478. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46479. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46480. __decorate([
  46481. BABYLON.serialize(),
  46482. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46483. ], PBRMaterial.prototype, "disableLighting", void 0);
  46484. __decorate([
  46485. BABYLON.serialize(),
  46486. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46487. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46488. __decorate([
  46489. BABYLON.serialize(),
  46490. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46491. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46492. __decorate([
  46493. BABYLON.serialize(),
  46494. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46495. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46496. __decorate([
  46497. BABYLON.serialize(),
  46498. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46499. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46500. __decorate([
  46501. BABYLON.serialize(),
  46502. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46503. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46504. __decorate([
  46505. BABYLON.serialize(),
  46506. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46507. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46508. __decorate([
  46509. BABYLON.serialize(),
  46510. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46511. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46512. __decorate([
  46513. BABYLON.serializeAsTexture(),
  46514. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46515. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46516. __decorate([
  46517. BABYLON.serialize(),
  46518. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46519. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46520. __decorate([
  46521. BABYLON.serialize(),
  46522. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46523. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46524. __decorate([
  46525. BABYLON.serialize(),
  46526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46527. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46528. __decorate([
  46529. BABYLON.serialize(),
  46530. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46531. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46532. __decorate([
  46533. BABYLON.serialize(),
  46534. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46535. ], PBRMaterial.prototype, "unlit", void 0);
  46536. return PBRMaterial;
  46537. }(BABYLON.PBRBaseMaterial));
  46538. BABYLON.PBRMaterial = PBRMaterial;
  46539. })(BABYLON || (BABYLON = {}));
  46540. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46541. var BABYLON;
  46542. (function (BABYLON) {
  46543. /**
  46544. * The PBR material of BJS following the metal roughness convention.
  46545. *
  46546. * This fits to the PBR convention in the GLTF definition:
  46547. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46548. */
  46549. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46550. __extends(PBRMetallicRoughnessMaterial, _super);
  46551. /**
  46552. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46553. *
  46554. * @param name The material name
  46555. * @param scene The scene the material will be use in.
  46556. */
  46557. function PBRMetallicRoughnessMaterial(name, scene) {
  46558. var _this = _super.call(this, name, scene) || this;
  46559. _this._useRoughnessFromMetallicTextureAlpha = false;
  46560. _this._useRoughnessFromMetallicTextureGreen = true;
  46561. _this._useMetallnessFromMetallicTextureBlue = true;
  46562. _this.metallic = 1.0;
  46563. _this.roughness = 1.0;
  46564. return _this;
  46565. }
  46566. /**
  46567. * Return the currrent class name of the material.
  46568. */
  46569. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46570. return "PBRMetallicRoughnessMaterial";
  46571. };
  46572. /**
  46573. * Return the active textures of the material.
  46574. */
  46575. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46576. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46577. if (this.baseTexture) {
  46578. activeTextures.push(this.baseTexture);
  46579. }
  46580. if (this.metallicRoughnessTexture) {
  46581. activeTextures.push(this.metallicRoughnessTexture);
  46582. }
  46583. return activeTextures;
  46584. };
  46585. /**
  46586. * Checks to see if a texture is used in the material.
  46587. * @param texture - Base texture to use.
  46588. * @returns - Boolean specifying if a texture is used in the material.
  46589. */
  46590. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46591. if (_super.prototype.hasTexture.call(this, texture)) {
  46592. return true;
  46593. }
  46594. if (this.baseTexture === texture) {
  46595. return true;
  46596. }
  46597. if (this.metallicRoughnessTexture === texture) {
  46598. return true;
  46599. }
  46600. return false;
  46601. };
  46602. /**
  46603. * Makes a duplicate of the current material.
  46604. * @param name - name to use for the new material.
  46605. */
  46606. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46607. var _this = this;
  46608. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46609. clone.id = name;
  46610. clone.name = name;
  46611. return clone;
  46612. };
  46613. /**
  46614. * Serialize the material to a parsable JSON object.
  46615. */
  46616. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46617. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46618. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46619. return serializationObject;
  46620. };
  46621. /**
  46622. * Parses a JSON object correponding to the serialize function.
  46623. */
  46624. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46625. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46626. };
  46627. __decorate([
  46628. BABYLON.serializeAsColor3(),
  46629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46630. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46631. __decorate([
  46632. BABYLON.serializeAsTexture(),
  46633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46634. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46635. __decorate([
  46636. BABYLON.serialize(),
  46637. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46638. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46639. __decorate([
  46640. BABYLON.serialize(),
  46641. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46642. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46643. __decorate([
  46644. BABYLON.serializeAsTexture(),
  46645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46646. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46647. return PBRMetallicRoughnessMaterial;
  46648. }(BABYLON.PBRBaseSimpleMaterial));
  46649. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46650. })(BABYLON || (BABYLON = {}));
  46651. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46652. var BABYLON;
  46653. (function (BABYLON) {
  46654. /**
  46655. * The PBR material of BJS following the specular glossiness convention.
  46656. *
  46657. * This fits to the PBR convention in the GLTF definition:
  46658. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46659. */
  46660. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46661. __extends(PBRSpecularGlossinessMaterial, _super);
  46662. /**
  46663. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46664. *
  46665. * @param name The material name
  46666. * @param scene The scene the material will be use in.
  46667. */
  46668. function PBRSpecularGlossinessMaterial(name, scene) {
  46669. var _this = _super.call(this, name, scene) || this;
  46670. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46671. return _this;
  46672. }
  46673. /**
  46674. * Return the currrent class name of the material.
  46675. */
  46676. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46677. return "PBRSpecularGlossinessMaterial";
  46678. };
  46679. /**
  46680. * Return the active textures of the material.
  46681. */
  46682. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46683. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46684. if (this.diffuseTexture) {
  46685. activeTextures.push(this.diffuseTexture);
  46686. }
  46687. if (this.specularGlossinessTexture) {
  46688. activeTextures.push(this.specularGlossinessTexture);
  46689. }
  46690. return activeTextures;
  46691. };
  46692. /**
  46693. * Checks to see if a texture is used in the material.
  46694. * @param texture - Base texture to use.
  46695. * @returns - Boolean specifying if a texture is used in the material.
  46696. */
  46697. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46698. if (_super.prototype.hasTexture.call(this, texture)) {
  46699. return true;
  46700. }
  46701. if (this.diffuseTexture === texture) {
  46702. return true;
  46703. }
  46704. if (this.specularGlossinessTexture === texture) {
  46705. return true;
  46706. }
  46707. return false;
  46708. };
  46709. /**
  46710. * Makes a duplicate of the current material.
  46711. * @param name - name to use for the new material.
  46712. */
  46713. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46714. var _this = this;
  46715. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46716. clone.id = name;
  46717. clone.name = name;
  46718. return clone;
  46719. };
  46720. /**
  46721. * Serialize the material to a parsable JSON object.
  46722. */
  46723. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46724. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46725. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46726. return serializationObject;
  46727. };
  46728. /**
  46729. * Parses a JSON object correponding to the serialize function.
  46730. */
  46731. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46732. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46733. };
  46734. __decorate([
  46735. BABYLON.serializeAsColor3("diffuse"),
  46736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46737. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46738. __decorate([
  46739. BABYLON.serializeAsTexture(),
  46740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46741. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46742. __decorate([
  46743. BABYLON.serializeAsColor3("specular"),
  46744. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46745. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46746. __decorate([
  46747. BABYLON.serialize(),
  46748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46749. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46750. __decorate([
  46751. BABYLON.serializeAsTexture(),
  46752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46753. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46754. return PBRSpecularGlossinessMaterial;
  46755. }(BABYLON.PBRBaseSimpleMaterial));
  46756. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46757. })(BABYLON || (BABYLON = {}));
  46758. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46759. var BABYLON;
  46760. (function (BABYLON) {
  46761. BABYLON.CameraInputTypes = {};
  46762. var CameraInputsManager = /** @class */ (function () {
  46763. function CameraInputsManager(camera) {
  46764. this.attached = {};
  46765. this.camera = camera;
  46766. this.checkInputs = function () { };
  46767. }
  46768. /**
  46769. * Add an input method to a camera.
  46770. * builtin inputs example: camera.inputs.addGamepad();
  46771. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  46772. * @param input camera input method
  46773. */
  46774. CameraInputsManager.prototype.add = function (input) {
  46775. var type = input.getSimpleName();
  46776. if (this.attached[type]) {
  46777. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46778. return;
  46779. }
  46780. this.attached[type] = input;
  46781. input.camera = this.camera;
  46782. //for checkInputs, we are dynamically creating a function
  46783. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46784. if (input.checkInputs) {
  46785. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46786. }
  46787. if (this.attachedElement) {
  46788. input.attachControl(this.attachedElement);
  46789. }
  46790. };
  46791. /**
  46792. * Remove a specific input method from a camera
  46793. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46794. * @param inputToRemove camera input method
  46795. */
  46796. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46797. for (var cam in this.attached) {
  46798. var input = this.attached[cam];
  46799. if (input === inputToRemove) {
  46800. input.detachControl(this.attachedElement);
  46801. input.camera = null;
  46802. delete this.attached[cam];
  46803. this.rebuildInputCheck();
  46804. }
  46805. }
  46806. };
  46807. CameraInputsManager.prototype.removeByType = function (inputType) {
  46808. for (var cam in this.attached) {
  46809. var input = this.attached[cam];
  46810. if (input.getClassName() === inputType) {
  46811. input.detachControl(this.attachedElement);
  46812. input.camera = null;
  46813. delete this.attached[cam];
  46814. this.rebuildInputCheck();
  46815. }
  46816. }
  46817. };
  46818. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46819. var current = this.checkInputs;
  46820. return function () {
  46821. current();
  46822. fn();
  46823. };
  46824. };
  46825. CameraInputsManager.prototype.attachInput = function (input) {
  46826. if (this.attachedElement) {
  46827. input.attachControl(this.attachedElement, this.noPreventDefault);
  46828. }
  46829. };
  46830. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46831. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46832. if (this.attachedElement) {
  46833. return;
  46834. }
  46835. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46836. this.attachedElement = element;
  46837. this.noPreventDefault = noPreventDefault;
  46838. for (var cam in this.attached) {
  46839. this.attached[cam].attachControl(element, noPreventDefault);
  46840. }
  46841. };
  46842. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46843. if (disconnect === void 0) { disconnect = false; }
  46844. if (this.attachedElement !== element) {
  46845. return;
  46846. }
  46847. for (var cam in this.attached) {
  46848. this.attached[cam].detachControl(element);
  46849. if (disconnect) {
  46850. this.attached[cam].camera = null;
  46851. }
  46852. }
  46853. this.attachedElement = null;
  46854. };
  46855. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46856. this.checkInputs = function () { };
  46857. for (var cam in this.attached) {
  46858. var input = this.attached[cam];
  46859. if (input.checkInputs) {
  46860. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46861. }
  46862. }
  46863. };
  46864. /**
  46865. * Remove all attached input methods from a camera
  46866. */
  46867. CameraInputsManager.prototype.clear = function () {
  46868. if (this.attachedElement) {
  46869. this.detachElement(this.attachedElement, true);
  46870. }
  46871. this.attached = {};
  46872. this.attachedElement = null;
  46873. this.checkInputs = function () { };
  46874. };
  46875. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46876. var inputs = {};
  46877. for (var cam in this.attached) {
  46878. var input = this.attached[cam];
  46879. var res = BABYLON.SerializationHelper.Serialize(input);
  46880. inputs[input.getClassName()] = res;
  46881. }
  46882. serializedCamera.inputsmgr = inputs;
  46883. };
  46884. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46885. var parsedInputs = parsedCamera.inputsmgr;
  46886. if (parsedInputs) {
  46887. this.clear();
  46888. for (var n in parsedInputs) {
  46889. var construct = BABYLON.CameraInputTypes[n];
  46890. if (construct) {
  46891. var parsedinput = parsedInputs[n];
  46892. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46893. this.add(input);
  46894. }
  46895. }
  46896. }
  46897. else {
  46898. //2016-03-08 this part is for managing backward compatibility
  46899. for (var n in this.attached) {
  46900. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46901. if (construct) {
  46902. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46903. this.remove(this.attached[n]);
  46904. this.add(input);
  46905. }
  46906. }
  46907. }
  46908. };
  46909. return CameraInputsManager;
  46910. }());
  46911. BABYLON.CameraInputsManager = CameraInputsManager;
  46912. })(BABYLON || (BABYLON = {}));
  46913. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46914. var BABYLON;
  46915. (function (BABYLON) {
  46916. var TargetCamera = /** @class */ (function (_super) {
  46917. __extends(TargetCamera, _super);
  46918. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46919. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46920. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46921. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46922. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46923. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46924. _this.speed = 2.0;
  46925. _this.noRotationConstraint = false;
  46926. _this.lockedTarget = null;
  46927. _this._currentTarget = BABYLON.Vector3.Zero();
  46928. _this._viewMatrix = BABYLON.Matrix.Zero();
  46929. _this._camMatrix = BABYLON.Matrix.Zero();
  46930. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46931. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46932. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46933. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46934. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46935. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46936. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46937. return _this;
  46938. }
  46939. TargetCamera.prototype.getFrontPosition = function (distance) {
  46940. this.getWorldMatrix();
  46941. var direction = this.getTarget().subtract(this.position);
  46942. direction.normalize();
  46943. direction.scaleInPlace(distance);
  46944. return this.globalPosition.add(direction);
  46945. };
  46946. TargetCamera.prototype._getLockedTargetPosition = function () {
  46947. if (!this.lockedTarget) {
  46948. return null;
  46949. }
  46950. if (this.lockedTarget.absolutePosition) {
  46951. this.lockedTarget.computeWorldMatrix();
  46952. }
  46953. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46954. };
  46955. TargetCamera.prototype.storeState = function () {
  46956. this._storedPosition = this.position.clone();
  46957. this._storedRotation = this.rotation.clone();
  46958. if (this.rotationQuaternion) {
  46959. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46960. }
  46961. return _super.prototype.storeState.call(this);
  46962. };
  46963. /**
  46964. * Restored camera state. You must call storeState() first
  46965. */
  46966. TargetCamera.prototype._restoreStateValues = function () {
  46967. if (!_super.prototype._restoreStateValues.call(this)) {
  46968. return false;
  46969. }
  46970. this.position = this._storedPosition.clone();
  46971. this.rotation = this._storedRotation.clone();
  46972. if (this.rotationQuaternion) {
  46973. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46974. }
  46975. this.cameraDirection.copyFromFloats(0, 0, 0);
  46976. this.cameraRotation.copyFromFloats(0, 0);
  46977. return true;
  46978. };
  46979. // Cache
  46980. TargetCamera.prototype._initCache = function () {
  46981. _super.prototype._initCache.call(this);
  46982. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46983. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46984. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46985. };
  46986. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46987. if (!ignoreParentClass) {
  46988. _super.prototype._updateCache.call(this);
  46989. }
  46990. var lockedTargetPosition = this._getLockedTargetPosition();
  46991. if (!lockedTargetPosition) {
  46992. this._cache.lockedTarget = null;
  46993. }
  46994. else {
  46995. if (!this._cache.lockedTarget) {
  46996. this._cache.lockedTarget = lockedTargetPosition.clone();
  46997. }
  46998. else {
  46999. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  47000. }
  47001. }
  47002. this._cache.rotation.copyFrom(this.rotation);
  47003. if (this.rotationQuaternion)
  47004. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47005. };
  47006. // Synchronized
  47007. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47008. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47009. return false;
  47010. }
  47011. var lockedTargetPosition = this._getLockedTargetPosition();
  47012. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47013. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47014. };
  47015. // Methods
  47016. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47017. var engine = this.getEngine();
  47018. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47019. };
  47020. // Target
  47021. TargetCamera.prototype.setTarget = function (target) {
  47022. this.upVector.normalize();
  47023. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  47024. this._camMatrix.invert();
  47025. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47026. var vDir = target.subtract(this.position);
  47027. if (vDir.x >= 0.0) {
  47028. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47029. }
  47030. else {
  47031. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47032. }
  47033. this.rotation.z = 0;
  47034. if (isNaN(this.rotation.x)) {
  47035. this.rotation.x = 0;
  47036. }
  47037. if (isNaN(this.rotation.y)) {
  47038. this.rotation.y = 0;
  47039. }
  47040. if (isNaN(this.rotation.z)) {
  47041. this.rotation.z = 0;
  47042. }
  47043. if (this.rotationQuaternion) {
  47044. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47045. }
  47046. };
  47047. /**
  47048. * Return the current target position of the camera. This value is expressed in local space.
  47049. */
  47050. TargetCamera.prototype.getTarget = function () {
  47051. return this._currentTarget;
  47052. };
  47053. TargetCamera.prototype._decideIfNeedsToMove = function () {
  47054. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47055. };
  47056. TargetCamera.prototype._updatePosition = function () {
  47057. if (this.parent) {
  47058. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  47059. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  47060. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  47061. return;
  47062. }
  47063. this.position.addInPlace(this.cameraDirection);
  47064. };
  47065. TargetCamera.prototype._checkInputs = function () {
  47066. var needToMove = this._decideIfNeedsToMove();
  47067. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  47068. // Move
  47069. if (needToMove) {
  47070. this._updatePosition();
  47071. }
  47072. // Rotate
  47073. if (needToRotate) {
  47074. this.rotation.x += this.cameraRotation.x;
  47075. this.rotation.y += this.cameraRotation.y;
  47076. //rotate, if quaternion is set and rotation was used
  47077. if (this.rotationQuaternion) {
  47078. var len = this.rotation.lengthSquared();
  47079. if (len) {
  47080. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47081. }
  47082. }
  47083. if (!this.noRotationConstraint) {
  47084. var limit = (Math.PI / 2) * 0.95;
  47085. if (this.rotation.x > limit)
  47086. this.rotation.x = limit;
  47087. if (this.rotation.x < -limit)
  47088. this.rotation.x = -limit;
  47089. }
  47090. }
  47091. // Inertia
  47092. if (needToMove) {
  47093. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47094. this.cameraDirection.x = 0;
  47095. }
  47096. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47097. this.cameraDirection.y = 0;
  47098. }
  47099. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47100. this.cameraDirection.z = 0;
  47101. }
  47102. this.cameraDirection.scaleInPlace(this.inertia);
  47103. }
  47104. if (needToRotate) {
  47105. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47106. this.cameraRotation.x = 0;
  47107. }
  47108. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47109. this.cameraRotation.y = 0;
  47110. }
  47111. this.cameraRotation.scaleInPlace(this.inertia);
  47112. }
  47113. _super.prototype._checkInputs.call(this);
  47114. };
  47115. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47116. if (this.rotationQuaternion) {
  47117. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47118. }
  47119. else {
  47120. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47121. }
  47122. //update the up vector!
  47123. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  47124. };
  47125. TargetCamera.prototype._getViewMatrix = function () {
  47126. if (this.lockedTarget) {
  47127. this.setTarget(this._getLockedTargetPosition());
  47128. }
  47129. // Compute
  47130. this._updateCameraRotationMatrix();
  47131. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47132. // Computing target and final matrix
  47133. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47134. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  47135. return this._viewMatrix;
  47136. };
  47137. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47138. if (this.parent) {
  47139. var parentWorldMatrix = this.parent.getWorldMatrix();
  47140. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  47141. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47142. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47143. this._markSyncedWithParent();
  47144. }
  47145. else {
  47146. this._globalPosition.copyFrom(this.position);
  47147. this._globalCurrentTarget.copyFrom(target);
  47148. this._globalCurrentUpVector.copyFrom(up);
  47149. }
  47150. if (this.getScene().useRightHandedSystem) {
  47151. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47152. }
  47153. else {
  47154. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47155. }
  47156. };
  47157. /**
  47158. * @override
  47159. * Override Camera.createRigCamera
  47160. */
  47161. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47162. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47163. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47164. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47165. if (!this.rotationQuaternion) {
  47166. this.rotationQuaternion = new BABYLON.Quaternion();
  47167. }
  47168. rigCamera._cameraRigParams = {};
  47169. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47170. }
  47171. return rigCamera;
  47172. }
  47173. return null;
  47174. };
  47175. /**
  47176. * @override
  47177. * Override Camera._updateRigCameras
  47178. */
  47179. TargetCamera.prototype._updateRigCameras = function () {
  47180. var camLeft = this._rigCameras[0];
  47181. var camRight = this._rigCameras[1];
  47182. switch (this.cameraRigMode) {
  47183. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47184. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47185. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47186. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47187. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47188. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47189. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47190. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47191. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47192. camLeft.setTarget(this.getTarget());
  47193. camRight.setTarget(this.getTarget());
  47194. break;
  47195. case BABYLON.Camera.RIG_MODE_VR:
  47196. if (camLeft.rotationQuaternion) {
  47197. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47198. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47199. }
  47200. else {
  47201. camLeft.rotation.copyFrom(this.rotation);
  47202. camRight.rotation.copyFrom(this.rotation);
  47203. }
  47204. camLeft.position.copyFrom(this.position);
  47205. camRight.position.copyFrom(this.position);
  47206. break;
  47207. }
  47208. _super.prototype._updateRigCameras.call(this);
  47209. };
  47210. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47211. if (!this._rigCamTransformMatrix) {
  47212. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47213. }
  47214. var target = this.getTarget();
  47215. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47216. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47217. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47218. };
  47219. TargetCamera.prototype.getClassName = function () {
  47220. return "TargetCamera";
  47221. };
  47222. __decorate([
  47223. BABYLON.serializeAsVector3()
  47224. ], TargetCamera.prototype, "rotation", void 0);
  47225. __decorate([
  47226. BABYLON.serialize()
  47227. ], TargetCamera.prototype, "speed", void 0);
  47228. __decorate([
  47229. BABYLON.serializeAsMeshReference("lockedTargetId")
  47230. ], TargetCamera.prototype, "lockedTarget", void 0);
  47231. return TargetCamera;
  47232. }(BABYLON.Camera));
  47233. BABYLON.TargetCamera = TargetCamera;
  47234. })(BABYLON || (BABYLON = {}));
  47235. //# sourceMappingURL=babylon.targetCamera.js.map
  47236. var BABYLON;
  47237. (function (BABYLON) {
  47238. var FreeCameraMouseInput = /** @class */ (function () {
  47239. function FreeCameraMouseInput(touchEnabled) {
  47240. if (touchEnabled === void 0) { touchEnabled = true; }
  47241. this.touchEnabled = touchEnabled;
  47242. this.buttons = [0, 1, 2];
  47243. this.angularSensibility = 2000.0;
  47244. this.previousPosition = null;
  47245. }
  47246. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47247. var _this = this;
  47248. var engine = this.camera.getEngine();
  47249. if (!this._pointerInput) {
  47250. this._pointerInput = function (p, s) {
  47251. var evt = p.event;
  47252. if (engine.isInVRExclusivePointerMode) {
  47253. return;
  47254. }
  47255. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47256. return;
  47257. }
  47258. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47259. return;
  47260. }
  47261. var srcElement = (evt.srcElement || evt.target);
  47262. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47263. try {
  47264. srcElement.setPointerCapture(evt.pointerId);
  47265. }
  47266. catch (e) {
  47267. //Nothing to do with the error. Execution will continue.
  47268. }
  47269. _this.previousPosition = {
  47270. x: evt.clientX,
  47271. y: evt.clientY
  47272. };
  47273. if (!noPreventDefault) {
  47274. evt.preventDefault();
  47275. element.focus();
  47276. }
  47277. }
  47278. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47279. try {
  47280. srcElement.releasePointerCapture(evt.pointerId);
  47281. }
  47282. catch (e) {
  47283. //Nothing to do with the error.
  47284. }
  47285. _this.previousPosition = null;
  47286. if (!noPreventDefault) {
  47287. evt.preventDefault();
  47288. }
  47289. }
  47290. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47291. if (!_this.previousPosition || engine.isPointerLock) {
  47292. return;
  47293. }
  47294. var offsetX = evt.clientX - _this.previousPosition.x;
  47295. if (_this.camera.getScene().useRightHandedSystem)
  47296. offsetX *= -1;
  47297. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47298. offsetX *= -1;
  47299. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47300. var offsetY = evt.clientY - _this.previousPosition.y;
  47301. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47302. _this.previousPosition = {
  47303. x: evt.clientX,
  47304. y: evt.clientY
  47305. };
  47306. if (!noPreventDefault) {
  47307. evt.preventDefault();
  47308. }
  47309. }
  47310. };
  47311. }
  47312. this._onMouseMove = function (evt) {
  47313. if (!engine.isPointerLock) {
  47314. return;
  47315. }
  47316. if (engine.isInVRExclusivePointerMode) {
  47317. return;
  47318. }
  47319. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47320. if (_this.camera.getScene().useRightHandedSystem)
  47321. offsetX *= -1;
  47322. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47323. offsetX *= -1;
  47324. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47325. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47326. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47327. _this.previousPosition = null;
  47328. if (!noPreventDefault) {
  47329. evt.preventDefault();
  47330. }
  47331. };
  47332. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47333. element.addEventListener("mousemove", this._onMouseMove, false);
  47334. };
  47335. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47336. if (this._observer && element) {
  47337. this.camera.getScene().onPointerObservable.remove(this._observer);
  47338. if (this._onMouseMove) {
  47339. element.removeEventListener("mousemove", this._onMouseMove);
  47340. }
  47341. this._observer = null;
  47342. this._onMouseMove = null;
  47343. this.previousPosition = null;
  47344. }
  47345. };
  47346. FreeCameraMouseInput.prototype.getClassName = function () {
  47347. return "FreeCameraMouseInput";
  47348. };
  47349. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47350. return "mouse";
  47351. };
  47352. __decorate([
  47353. BABYLON.serialize()
  47354. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47355. __decorate([
  47356. BABYLON.serialize()
  47357. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47358. return FreeCameraMouseInput;
  47359. }());
  47360. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47361. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47362. })(BABYLON || (BABYLON = {}));
  47363. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47364. var BABYLON;
  47365. (function (BABYLON) {
  47366. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47367. function FreeCameraKeyboardMoveInput() {
  47368. this._keys = new Array();
  47369. this.keysUp = [38];
  47370. this.keysDown = [40];
  47371. this.keysLeft = [37];
  47372. this.keysRight = [39];
  47373. }
  47374. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47375. var _this = this;
  47376. if (this._onCanvasBlurObserver) {
  47377. return;
  47378. }
  47379. this._scene = this.camera.getScene();
  47380. this._engine = this._scene.getEngine();
  47381. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47382. _this._keys = [];
  47383. });
  47384. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47385. var evt = info.event;
  47386. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47387. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47388. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47389. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47390. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47391. var index = _this._keys.indexOf(evt.keyCode);
  47392. if (index === -1) {
  47393. _this._keys.push(evt.keyCode);
  47394. }
  47395. if (!noPreventDefault) {
  47396. evt.preventDefault();
  47397. }
  47398. }
  47399. }
  47400. else {
  47401. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47402. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47403. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47404. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47405. var index = _this._keys.indexOf(evt.keyCode);
  47406. if (index >= 0) {
  47407. _this._keys.splice(index, 1);
  47408. }
  47409. if (!noPreventDefault) {
  47410. evt.preventDefault();
  47411. }
  47412. }
  47413. }
  47414. });
  47415. };
  47416. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47417. if (this._scene) {
  47418. if (this._onKeyboardObserver) {
  47419. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47420. }
  47421. if (this._onCanvasBlurObserver) {
  47422. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47423. }
  47424. this._onKeyboardObserver = null;
  47425. this._onCanvasBlurObserver = null;
  47426. }
  47427. this._keys = [];
  47428. };
  47429. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47430. if (this._onKeyboardObserver) {
  47431. var camera = this.camera;
  47432. // Keyboard
  47433. for (var index = 0; index < this._keys.length; index++) {
  47434. var keyCode = this._keys[index];
  47435. var speed = camera._computeLocalCameraSpeed();
  47436. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47437. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47438. }
  47439. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47440. camera._localDirection.copyFromFloats(0, 0, speed);
  47441. }
  47442. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47443. camera._localDirection.copyFromFloats(speed, 0, 0);
  47444. }
  47445. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47446. camera._localDirection.copyFromFloats(0, 0, -speed);
  47447. }
  47448. if (camera.getScene().useRightHandedSystem) {
  47449. camera._localDirection.z *= -1;
  47450. }
  47451. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47452. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47453. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47454. }
  47455. }
  47456. };
  47457. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47458. return "FreeCameraKeyboardMoveInput";
  47459. };
  47460. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47461. this._keys = [];
  47462. };
  47463. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47464. return "keyboard";
  47465. };
  47466. __decorate([
  47467. BABYLON.serialize()
  47468. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47469. __decorate([
  47470. BABYLON.serialize()
  47471. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47472. __decorate([
  47473. BABYLON.serialize()
  47474. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47475. __decorate([
  47476. BABYLON.serialize()
  47477. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47478. return FreeCameraKeyboardMoveInput;
  47479. }());
  47480. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47481. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47482. })(BABYLON || (BABYLON = {}));
  47483. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47484. var BABYLON;
  47485. (function (BABYLON) {
  47486. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47487. __extends(FreeCameraInputsManager, _super);
  47488. function FreeCameraInputsManager(camera) {
  47489. return _super.call(this, camera) || this;
  47490. }
  47491. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47492. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47493. return this;
  47494. };
  47495. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47496. if (touchEnabled === void 0) { touchEnabled = true; }
  47497. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47498. return this;
  47499. };
  47500. FreeCameraInputsManager.prototype.addGamepad = function () {
  47501. this.add(new BABYLON.FreeCameraGamepadInput());
  47502. return this;
  47503. };
  47504. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47505. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47506. return this;
  47507. };
  47508. FreeCameraInputsManager.prototype.addTouch = function () {
  47509. this.add(new BABYLON.FreeCameraTouchInput());
  47510. return this;
  47511. };
  47512. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47513. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47514. return this;
  47515. };
  47516. return FreeCameraInputsManager;
  47517. }(BABYLON.CameraInputsManager));
  47518. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47519. })(BABYLON || (BABYLON = {}));
  47520. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47521. var BABYLON;
  47522. (function (BABYLON) {
  47523. var FreeCamera = /** @class */ (function (_super) {
  47524. __extends(FreeCamera, _super);
  47525. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47526. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47527. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47528. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47529. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47530. _this.checkCollisions = false;
  47531. _this.applyGravity = false;
  47532. _this._needMoveForGravity = false;
  47533. _this._oldPosition = BABYLON.Vector3.Zero();
  47534. _this._diffPosition = BABYLON.Vector3.Zero();
  47535. _this._newPosition = BABYLON.Vector3.Zero();
  47536. // Collisions
  47537. _this._collisionMask = -1;
  47538. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47539. if (collidedMesh === void 0) { collidedMesh = null; }
  47540. //TODO move this to the collision coordinator!
  47541. if (_this.getScene().workerCollisions)
  47542. newPosition.multiplyInPlace(_this._collider._radius);
  47543. var updatePosition = function (newPos) {
  47544. _this._newPosition.copyFrom(newPos);
  47545. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47546. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47547. _this.position.addInPlace(_this._diffPosition);
  47548. if (_this.onCollide && collidedMesh) {
  47549. _this.onCollide(collidedMesh);
  47550. }
  47551. }
  47552. };
  47553. updatePosition(newPosition);
  47554. };
  47555. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47556. _this.inputs.addKeyboard().addMouse();
  47557. return _this;
  47558. }
  47559. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47560. //-- begin properties for backward compatibility for inputs
  47561. /**
  47562. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47563. * Higher values reduce sensitivity.
  47564. */
  47565. get: function () {
  47566. var mouse = this.inputs.attached["mouse"];
  47567. if (mouse)
  47568. return mouse.angularSensibility;
  47569. return 0;
  47570. },
  47571. /**
  47572. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47573. * Higher values reduce sensitivity.
  47574. */
  47575. set: function (value) {
  47576. var mouse = this.inputs.attached["mouse"];
  47577. if (mouse)
  47578. mouse.angularSensibility = value;
  47579. },
  47580. enumerable: true,
  47581. configurable: true
  47582. });
  47583. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47584. get: function () {
  47585. var keyboard = this.inputs.attached["keyboard"];
  47586. if (keyboard)
  47587. return keyboard.keysUp;
  47588. return [];
  47589. },
  47590. set: function (value) {
  47591. var keyboard = this.inputs.attached["keyboard"];
  47592. if (keyboard)
  47593. keyboard.keysUp = value;
  47594. },
  47595. enumerable: true,
  47596. configurable: true
  47597. });
  47598. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47599. get: function () {
  47600. var keyboard = this.inputs.attached["keyboard"];
  47601. if (keyboard)
  47602. return keyboard.keysDown;
  47603. return [];
  47604. },
  47605. set: function (value) {
  47606. var keyboard = this.inputs.attached["keyboard"];
  47607. if (keyboard)
  47608. keyboard.keysDown = value;
  47609. },
  47610. enumerable: true,
  47611. configurable: true
  47612. });
  47613. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47614. get: function () {
  47615. var keyboard = this.inputs.attached["keyboard"];
  47616. if (keyboard)
  47617. return keyboard.keysLeft;
  47618. return [];
  47619. },
  47620. set: function (value) {
  47621. var keyboard = this.inputs.attached["keyboard"];
  47622. if (keyboard)
  47623. keyboard.keysLeft = value;
  47624. },
  47625. enumerable: true,
  47626. configurable: true
  47627. });
  47628. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47629. get: function () {
  47630. var keyboard = this.inputs.attached["keyboard"];
  47631. if (keyboard)
  47632. return keyboard.keysRight;
  47633. return [];
  47634. },
  47635. set: function (value) {
  47636. var keyboard = this.inputs.attached["keyboard"];
  47637. if (keyboard)
  47638. keyboard.keysRight = value;
  47639. },
  47640. enumerable: true,
  47641. configurable: true
  47642. });
  47643. // Controls
  47644. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47645. this.inputs.attachElement(element, noPreventDefault);
  47646. };
  47647. FreeCamera.prototype.detachControl = function (element) {
  47648. this.inputs.detachElement(element);
  47649. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47650. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47651. };
  47652. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47653. get: function () {
  47654. return this._collisionMask;
  47655. },
  47656. set: function (mask) {
  47657. this._collisionMask = !isNaN(mask) ? mask : -1;
  47658. },
  47659. enumerable: true,
  47660. configurable: true
  47661. });
  47662. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47663. var globalPosition;
  47664. if (this.parent) {
  47665. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47666. }
  47667. else {
  47668. globalPosition = this.position;
  47669. }
  47670. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47671. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47672. if (!this._collider) {
  47673. this._collider = new BABYLON.Collider();
  47674. }
  47675. this._collider._radius = this.ellipsoid;
  47676. this._collider.collisionMask = this._collisionMask;
  47677. //no need for clone, as long as gravity is not on.
  47678. var actualDisplacement = displacement;
  47679. //add gravity to the direction to prevent the dual-collision checking
  47680. if (this.applyGravity) {
  47681. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47682. actualDisplacement = displacement.add(this.getScene().gravity);
  47683. }
  47684. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47685. };
  47686. FreeCamera.prototype._checkInputs = function () {
  47687. if (!this._localDirection) {
  47688. this._localDirection = BABYLON.Vector3.Zero();
  47689. this._transformedDirection = BABYLON.Vector3.Zero();
  47690. }
  47691. this.inputs.checkInputs();
  47692. _super.prototype._checkInputs.call(this);
  47693. };
  47694. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47695. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47696. };
  47697. FreeCamera.prototype._updatePosition = function () {
  47698. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47699. this._collideWithWorld(this.cameraDirection);
  47700. }
  47701. else {
  47702. _super.prototype._updatePosition.call(this);
  47703. }
  47704. };
  47705. FreeCamera.prototype.dispose = function () {
  47706. this.inputs.clear();
  47707. _super.prototype.dispose.call(this);
  47708. };
  47709. FreeCamera.prototype.getClassName = function () {
  47710. return "FreeCamera";
  47711. };
  47712. __decorate([
  47713. BABYLON.serializeAsVector3()
  47714. ], FreeCamera.prototype, "ellipsoid", void 0);
  47715. __decorate([
  47716. BABYLON.serializeAsVector3()
  47717. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47718. __decorate([
  47719. BABYLON.serialize()
  47720. ], FreeCamera.prototype, "checkCollisions", void 0);
  47721. __decorate([
  47722. BABYLON.serialize()
  47723. ], FreeCamera.prototype, "applyGravity", void 0);
  47724. return FreeCamera;
  47725. }(BABYLON.TargetCamera));
  47726. BABYLON.FreeCamera = FreeCamera;
  47727. })(BABYLON || (BABYLON = {}));
  47728. //# sourceMappingURL=babylon.freeCamera.js.map
  47729. var BABYLON;
  47730. (function (BABYLON) {
  47731. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47732. function ArcRotateCameraKeyboardMoveInput() {
  47733. this._keys = new Array();
  47734. this.keysUp = [38];
  47735. this.keysDown = [40];
  47736. this.keysLeft = [37];
  47737. this.keysRight = [39];
  47738. this.keysReset = [220];
  47739. this.panningSensibility = 50.0;
  47740. this.zoomingSensibility = 25.0;
  47741. this.useAltToZoom = true;
  47742. }
  47743. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47744. var _this = this;
  47745. if (this._onCanvasBlurObserver) {
  47746. return;
  47747. }
  47748. this._scene = this.camera.getScene();
  47749. this._engine = this._scene.getEngine();
  47750. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47751. _this._keys = [];
  47752. });
  47753. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47754. var evt = info.event;
  47755. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47756. _this._ctrlPressed = evt.ctrlKey;
  47757. _this._altPressed = evt.altKey;
  47758. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47759. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47760. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47761. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47762. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47763. var index = _this._keys.indexOf(evt.keyCode);
  47764. if (index === -1) {
  47765. _this._keys.push(evt.keyCode);
  47766. }
  47767. if (evt.preventDefault) {
  47768. if (!noPreventDefault) {
  47769. evt.preventDefault();
  47770. }
  47771. }
  47772. }
  47773. }
  47774. else {
  47775. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47776. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47777. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47778. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47779. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47780. var index = _this._keys.indexOf(evt.keyCode);
  47781. if (index >= 0) {
  47782. _this._keys.splice(index, 1);
  47783. }
  47784. if (evt.preventDefault) {
  47785. if (!noPreventDefault) {
  47786. evt.preventDefault();
  47787. }
  47788. }
  47789. }
  47790. }
  47791. });
  47792. };
  47793. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47794. if (this._scene) {
  47795. if (this._onKeyboardObserver) {
  47796. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47797. }
  47798. if (this._onCanvasBlurObserver) {
  47799. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47800. }
  47801. this._onKeyboardObserver = null;
  47802. this._onCanvasBlurObserver = null;
  47803. }
  47804. this._keys = [];
  47805. };
  47806. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47807. if (this._onKeyboardObserver) {
  47808. var camera = this.camera;
  47809. for (var index = 0; index < this._keys.length; index++) {
  47810. var keyCode = this._keys[index];
  47811. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47812. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47813. camera.inertialPanningX -= 1 / this.panningSensibility;
  47814. }
  47815. else {
  47816. camera.inertialAlphaOffset -= 0.01;
  47817. }
  47818. }
  47819. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47820. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47821. camera.inertialPanningY += 1 / this.panningSensibility;
  47822. }
  47823. else if (this._altPressed && this.useAltToZoom) {
  47824. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47825. }
  47826. else {
  47827. camera.inertialBetaOffset -= 0.01;
  47828. }
  47829. }
  47830. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47831. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47832. camera.inertialPanningX += 1 / this.panningSensibility;
  47833. }
  47834. else {
  47835. camera.inertialAlphaOffset += 0.01;
  47836. }
  47837. }
  47838. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47839. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47840. camera.inertialPanningY -= 1 / this.panningSensibility;
  47841. }
  47842. else if (this._altPressed && this.useAltToZoom) {
  47843. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47844. }
  47845. else {
  47846. camera.inertialBetaOffset += 0.01;
  47847. }
  47848. }
  47849. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47850. camera.restoreState();
  47851. }
  47852. }
  47853. }
  47854. };
  47855. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47856. return "ArcRotateCameraKeyboardMoveInput";
  47857. };
  47858. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47859. return "keyboard";
  47860. };
  47861. __decorate([
  47862. BABYLON.serialize()
  47863. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47864. __decorate([
  47865. BABYLON.serialize()
  47866. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47867. __decorate([
  47868. BABYLON.serialize()
  47869. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47870. __decorate([
  47871. BABYLON.serialize()
  47872. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47873. __decorate([
  47874. BABYLON.serialize()
  47875. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47876. __decorate([
  47877. BABYLON.serialize()
  47878. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47879. __decorate([
  47880. BABYLON.serialize()
  47881. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47882. __decorate([
  47883. BABYLON.serialize()
  47884. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47885. return ArcRotateCameraKeyboardMoveInput;
  47886. }());
  47887. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47888. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47889. })(BABYLON || (BABYLON = {}));
  47890. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47891. var BABYLON;
  47892. (function (BABYLON) {
  47893. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47894. function ArcRotateCameraMouseWheelInput() {
  47895. this.wheelPrecision = 3.0;
  47896. /**
  47897. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47898. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47899. */
  47900. this.wheelDeltaPercentage = 0;
  47901. }
  47902. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47903. var _this = this;
  47904. this._wheel = function (p, s) {
  47905. //sanity check - this should be a PointerWheel event.
  47906. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47907. return;
  47908. var event = p.event;
  47909. var delta = 0;
  47910. if (event.wheelDelta) {
  47911. if (_this.wheelDeltaPercentage) {
  47912. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47913. if (event.wheelDelta > 0) {
  47914. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47915. }
  47916. else {
  47917. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47918. }
  47919. }
  47920. else {
  47921. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47922. }
  47923. }
  47924. else if (event.detail) {
  47925. delta = -event.detail / _this.wheelPrecision;
  47926. }
  47927. if (delta)
  47928. _this.camera.inertialRadiusOffset += delta;
  47929. if (event.preventDefault) {
  47930. if (!noPreventDefault) {
  47931. event.preventDefault();
  47932. }
  47933. }
  47934. };
  47935. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47936. };
  47937. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47938. if (this._observer && element) {
  47939. this.camera.getScene().onPointerObservable.remove(this._observer);
  47940. this._observer = null;
  47941. this._wheel = null;
  47942. }
  47943. };
  47944. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47945. return "ArcRotateCameraMouseWheelInput";
  47946. };
  47947. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47948. return "mousewheel";
  47949. };
  47950. __decorate([
  47951. BABYLON.serialize()
  47952. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47953. __decorate([
  47954. BABYLON.serialize()
  47955. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47956. return ArcRotateCameraMouseWheelInput;
  47957. }());
  47958. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47959. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47960. })(BABYLON || (BABYLON = {}));
  47961. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47962. var BABYLON;
  47963. (function (BABYLON) {
  47964. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47965. function ArcRotateCameraPointersInput() {
  47966. this.buttons = [0, 1, 2];
  47967. this.angularSensibilityX = 1000.0;
  47968. this.angularSensibilityY = 1000.0;
  47969. this.pinchPrecision = 12.0;
  47970. /**
  47971. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47972. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47973. */
  47974. this.pinchDeltaPercentage = 0;
  47975. this.panningSensibility = 1000.0;
  47976. this.multiTouchPanning = true;
  47977. this.multiTouchPanAndZoom = true;
  47978. this._isPanClick = false;
  47979. this.pinchInwards = true;
  47980. }
  47981. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47982. var _this = this;
  47983. var engine = this.camera.getEngine();
  47984. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47985. var pointA = null;
  47986. var pointB = null;
  47987. var previousPinchSquaredDistance = 0;
  47988. var initialDistance = 0;
  47989. var twoFingerActivityCount = 0;
  47990. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47991. this._pointerInput = function (p, s) {
  47992. var evt = p.event;
  47993. var isTouch = p.event.pointerType === "touch";
  47994. if (engine.isInVRExclusivePointerMode) {
  47995. return;
  47996. }
  47997. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47998. return;
  47999. }
  48000. var srcElement = (evt.srcElement || evt.target);
  48001. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48002. try {
  48003. srcElement.setPointerCapture(evt.pointerId);
  48004. }
  48005. catch (e) {
  48006. //Nothing to do with the error. Execution will continue.
  48007. }
  48008. // Manage panning with pan button click
  48009. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  48010. // manage pointers
  48011. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  48012. if (pointA === null) {
  48013. pointA = cacheSoloPointer;
  48014. }
  48015. else if (pointB === null) {
  48016. pointB = cacheSoloPointer;
  48017. }
  48018. if (!noPreventDefault) {
  48019. evt.preventDefault();
  48020. element.focus();
  48021. }
  48022. }
  48023. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48024. _this.camera.restoreState();
  48025. }
  48026. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48027. try {
  48028. srcElement.releasePointerCapture(evt.pointerId);
  48029. }
  48030. catch (e) {
  48031. //Nothing to do with the error.
  48032. }
  48033. cacheSoloPointer = null;
  48034. previousPinchSquaredDistance = 0;
  48035. previousMultiTouchPanPosition.isPaning = false;
  48036. previousMultiTouchPanPosition.isPinching = false;
  48037. twoFingerActivityCount = 0;
  48038. initialDistance = 0;
  48039. if (!isTouch) {
  48040. pointB = null; // Mouse and pen are mono pointer
  48041. }
  48042. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48043. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48044. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48045. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48046. if (engine._badOS) {
  48047. pointA = pointB = null;
  48048. }
  48049. else {
  48050. //only remove the impacted pointer in case of multitouch allowing on most
  48051. //platforms switching from rotate to zoom and pan seamlessly.
  48052. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48053. pointA = pointB;
  48054. pointB = null;
  48055. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48056. }
  48057. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48058. pointB = null;
  48059. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48060. }
  48061. else {
  48062. pointA = pointB = null;
  48063. }
  48064. }
  48065. if (!noPreventDefault) {
  48066. evt.preventDefault();
  48067. }
  48068. }
  48069. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48070. if (!noPreventDefault) {
  48071. evt.preventDefault();
  48072. }
  48073. // One button down
  48074. if (pointA && pointB === null && cacheSoloPointer) {
  48075. if (_this.panningSensibility !== 0 &&
  48076. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48077. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48078. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48079. }
  48080. else {
  48081. var offsetX = evt.clientX - cacheSoloPointer.x;
  48082. var offsetY = evt.clientY - cacheSoloPointer.y;
  48083. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48084. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48085. }
  48086. cacheSoloPointer.x = evt.clientX;
  48087. cacheSoloPointer.y = evt.clientY;
  48088. }
  48089. // Two buttons down: pinch/pan
  48090. else if (pointA && pointB) {
  48091. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48092. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48093. ed.x = evt.clientX;
  48094. ed.y = evt.clientY;
  48095. var direction = _this.pinchInwards ? 1 : -1;
  48096. var distX = pointA.x - pointB.x;
  48097. var distY = pointA.y - pointB.y;
  48098. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48099. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48100. if (previousPinchSquaredDistance === 0) {
  48101. initialDistance = pinchDistance;
  48102. previousPinchSquaredDistance = pinchSquaredDistance;
  48103. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48104. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48105. return;
  48106. }
  48107. if (_this.multiTouchPanAndZoom) {
  48108. if (_this.pinchDeltaPercentage) {
  48109. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48110. }
  48111. else {
  48112. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48113. (_this.pinchPrecision *
  48114. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48115. direction);
  48116. }
  48117. if (_this.panningSensibility !== 0) {
  48118. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48119. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48120. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48121. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48122. previousMultiTouchPanPosition.x = pointersCenterX;
  48123. previousMultiTouchPanPosition.y = pointersCenterY;
  48124. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48125. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48126. }
  48127. }
  48128. else {
  48129. twoFingerActivityCount++;
  48130. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48131. if (_this.pinchDeltaPercentage) {
  48132. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48133. }
  48134. else {
  48135. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48136. (_this.pinchPrecision *
  48137. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48138. direction);
  48139. }
  48140. previousMultiTouchPanPosition.isPaning = false;
  48141. previousMultiTouchPanPosition.isPinching = true;
  48142. }
  48143. else {
  48144. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48145. if (!previousMultiTouchPanPosition.isPaning) {
  48146. previousMultiTouchPanPosition.isPaning = true;
  48147. previousMultiTouchPanPosition.isPinching = false;
  48148. previousMultiTouchPanPosition.x = ed.x;
  48149. previousMultiTouchPanPosition.y = ed.y;
  48150. return;
  48151. }
  48152. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48153. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48154. }
  48155. }
  48156. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48157. previousMultiTouchPanPosition.x = ed.x;
  48158. previousMultiTouchPanPosition.y = ed.y;
  48159. }
  48160. }
  48161. previousPinchSquaredDistance = pinchSquaredDistance;
  48162. }
  48163. }
  48164. };
  48165. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  48166. this._onContextMenu = function (evt) {
  48167. evt.preventDefault();
  48168. };
  48169. if (!this.camera._useCtrlForPanning) {
  48170. element.addEventListener("contextmenu", this._onContextMenu, false);
  48171. }
  48172. this._onLostFocus = function () {
  48173. //this._keys = [];
  48174. pointA = pointB = null;
  48175. previousPinchSquaredDistance = 0;
  48176. previousMultiTouchPanPosition.isPaning = false;
  48177. previousMultiTouchPanPosition.isPinching = false;
  48178. twoFingerActivityCount = 0;
  48179. cacheSoloPointer = null;
  48180. initialDistance = 0;
  48181. };
  48182. this._onMouseMove = function (evt) {
  48183. if (!engine.isPointerLock) {
  48184. return;
  48185. }
  48186. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48187. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48188. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48189. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48190. if (!noPreventDefault) {
  48191. evt.preventDefault();
  48192. }
  48193. };
  48194. this._onGestureStart = function (e) {
  48195. if (window.MSGesture === undefined) {
  48196. return;
  48197. }
  48198. if (!_this._MSGestureHandler) {
  48199. _this._MSGestureHandler = new MSGesture();
  48200. _this._MSGestureHandler.target = element;
  48201. }
  48202. _this._MSGestureHandler.addPointer(e.pointerId);
  48203. };
  48204. this._onGesture = function (e) {
  48205. _this.camera.radius *= e.scale;
  48206. if (e.preventDefault) {
  48207. if (!noPreventDefault) {
  48208. e.stopPropagation();
  48209. e.preventDefault();
  48210. }
  48211. }
  48212. };
  48213. element.addEventListener("mousemove", this._onMouseMove, false);
  48214. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48215. element.addEventListener("MSGestureChange", this._onGesture, false);
  48216. BABYLON.Tools.RegisterTopRootEvents([
  48217. { name: "blur", handler: this._onLostFocus }
  48218. ]);
  48219. };
  48220. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48221. if (this._onLostFocus) {
  48222. BABYLON.Tools.UnregisterTopRootEvents([
  48223. { name: "blur", handler: this._onLostFocus }
  48224. ]);
  48225. }
  48226. if (element && this._observer) {
  48227. this.camera.getScene().onPointerObservable.remove(this._observer);
  48228. this._observer = null;
  48229. if (this._onContextMenu) {
  48230. element.removeEventListener("contextmenu", this._onContextMenu);
  48231. }
  48232. if (this._onMouseMove) {
  48233. element.removeEventListener("mousemove", this._onMouseMove);
  48234. }
  48235. if (this._onGestureStart) {
  48236. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48237. }
  48238. if (this._onGesture) {
  48239. element.removeEventListener("MSGestureChange", this._onGesture);
  48240. }
  48241. this._isPanClick = false;
  48242. this.pinchInwards = true;
  48243. this._onMouseMove = null;
  48244. this._onGestureStart = null;
  48245. this._onGesture = null;
  48246. this._MSGestureHandler = null;
  48247. this._onLostFocus = null;
  48248. this._onContextMenu = null;
  48249. }
  48250. };
  48251. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48252. return "ArcRotateCameraPointersInput";
  48253. };
  48254. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48255. return "pointers";
  48256. };
  48257. __decorate([
  48258. BABYLON.serialize()
  48259. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48260. __decorate([
  48261. BABYLON.serialize()
  48262. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48263. __decorate([
  48264. BABYLON.serialize()
  48265. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48266. __decorate([
  48267. BABYLON.serialize()
  48268. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48269. __decorate([
  48270. BABYLON.serialize()
  48271. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48272. __decorate([
  48273. BABYLON.serialize()
  48274. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48275. __decorate([
  48276. BABYLON.serialize()
  48277. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48278. __decorate([
  48279. BABYLON.serialize()
  48280. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48281. return ArcRotateCameraPointersInput;
  48282. }());
  48283. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48284. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48285. })(BABYLON || (BABYLON = {}));
  48286. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48287. var BABYLON;
  48288. (function (BABYLON) {
  48289. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48290. __extends(ArcRotateCameraInputsManager, _super);
  48291. function ArcRotateCameraInputsManager(camera) {
  48292. return _super.call(this, camera) || this;
  48293. }
  48294. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48295. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48296. return this;
  48297. };
  48298. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48299. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48300. return this;
  48301. };
  48302. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48303. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48304. return this;
  48305. };
  48306. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48307. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48308. return this;
  48309. };
  48310. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48311. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48312. return this;
  48313. };
  48314. return ArcRotateCameraInputsManager;
  48315. }(BABYLON.CameraInputsManager));
  48316. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48317. })(BABYLON || (BABYLON = {}));
  48318. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48319. var BABYLON;
  48320. (function (BABYLON) {
  48321. var ArcRotateCamera = /** @class */ (function (_super) {
  48322. __extends(ArcRotateCamera, _super);
  48323. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48324. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48325. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48326. _this.inertialAlphaOffset = 0;
  48327. _this.inertialBetaOffset = 0;
  48328. _this.inertialRadiusOffset = 0;
  48329. _this.lowerAlphaLimit = null;
  48330. _this.upperAlphaLimit = null;
  48331. _this.lowerBetaLimit = 0.01;
  48332. _this.upperBetaLimit = Math.PI;
  48333. _this.lowerRadiusLimit = null;
  48334. _this.upperRadiusLimit = null;
  48335. _this.inertialPanningX = 0;
  48336. _this.inertialPanningY = 0;
  48337. _this.pinchToPanMaxDistance = 20;
  48338. _this.panningDistanceLimit = null;
  48339. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48340. _this.panningInertia = 0.9;
  48341. //-- end properties for backward compatibility for inputs
  48342. _this.zoomOnFactor = 1;
  48343. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48344. _this.allowUpsideDown = true;
  48345. _this._viewMatrix = new BABYLON.Matrix();
  48346. // Panning
  48347. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48348. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48349. _this.checkCollisions = false;
  48350. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48351. _this._previousPosition = BABYLON.Vector3.Zero();
  48352. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48353. _this._newPosition = BABYLON.Vector3.Zero();
  48354. _this._computationVector = BABYLON.Vector3.Zero();
  48355. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48356. if (collidedMesh === void 0) { collidedMesh = null; }
  48357. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48358. newPosition.multiplyInPlace(_this._collider._radius);
  48359. }
  48360. if (!collidedMesh) {
  48361. _this._previousPosition.copyFrom(_this.position);
  48362. }
  48363. else {
  48364. _this.setPosition(newPosition);
  48365. if (_this.onCollide) {
  48366. _this.onCollide(collidedMesh);
  48367. }
  48368. }
  48369. // Recompute because of constraints
  48370. var cosa = Math.cos(_this.alpha);
  48371. var sina = Math.sin(_this.alpha);
  48372. var cosb = Math.cos(_this.beta);
  48373. var sinb = Math.sin(_this.beta);
  48374. if (sinb === 0) {
  48375. sinb = 0.0001;
  48376. }
  48377. var target = _this._getTargetPosition();
  48378. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48379. target.addToRef(_this._computationVector, _this._newPosition);
  48380. _this.position.copyFrom(_this._newPosition);
  48381. var up = _this.upVector;
  48382. if (_this.allowUpsideDown && _this.beta < 0) {
  48383. up = up.clone();
  48384. up = up.negate();
  48385. }
  48386. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  48387. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48388. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48389. _this._collisionTriggered = false;
  48390. };
  48391. _this._target = BABYLON.Vector3.Zero();
  48392. if (target) {
  48393. _this.setTarget(target);
  48394. }
  48395. _this.alpha = alpha;
  48396. _this.beta = beta;
  48397. _this.radius = radius;
  48398. _this.getViewMatrix();
  48399. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48400. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48401. return _this;
  48402. }
  48403. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48404. get: function () {
  48405. return this._target;
  48406. },
  48407. set: function (value) {
  48408. this.setTarget(value);
  48409. },
  48410. enumerable: true,
  48411. configurable: true
  48412. });
  48413. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48414. //-- begin properties for backward compatibility for inputs
  48415. get: function () {
  48416. var pointers = this.inputs.attached["pointers"];
  48417. if (pointers)
  48418. return pointers.angularSensibilityX;
  48419. return 0;
  48420. },
  48421. set: function (value) {
  48422. var pointers = this.inputs.attached["pointers"];
  48423. if (pointers) {
  48424. pointers.angularSensibilityX = value;
  48425. }
  48426. },
  48427. enumerable: true,
  48428. configurable: true
  48429. });
  48430. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48431. get: function () {
  48432. var pointers = this.inputs.attached["pointers"];
  48433. if (pointers)
  48434. return pointers.angularSensibilityY;
  48435. return 0;
  48436. },
  48437. set: function (value) {
  48438. var pointers = this.inputs.attached["pointers"];
  48439. if (pointers) {
  48440. pointers.angularSensibilityY = value;
  48441. }
  48442. },
  48443. enumerable: true,
  48444. configurable: true
  48445. });
  48446. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48447. get: function () {
  48448. var pointers = this.inputs.attached["pointers"];
  48449. if (pointers)
  48450. return pointers.pinchPrecision;
  48451. return 0;
  48452. },
  48453. set: function (value) {
  48454. var pointers = this.inputs.attached["pointers"];
  48455. if (pointers) {
  48456. pointers.pinchPrecision = value;
  48457. }
  48458. },
  48459. enumerable: true,
  48460. configurable: true
  48461. });
  48462. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48463. get: function () {
  48464. var pointers = this.inputs.attached["pointers"];
  48465. if (pointers)
  48466. return pointers.pinchDeltaPercentage;
  48467. return 0;
  48468. },
  48469. set: function (value) {
  48470. var pointers = this.inputs.attached["pointers"];
  48471. if (pointers) {
  48472. pointers.pinchDeltaPercentage = value;
  48473. }
  48474. },
  48475. enumerable: true,
  48476. configurable: true
  48477. });
  48478. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48479. get: function () {
  48480. var pointers = this.inputs.attached["pointers"];
  48481. if (pointers)
  48482. return pointers.panningSensibility;
  48483. return 0;
  48484. },
  48485. set: function (value) {
  48486. var pointers = this.inputs.attached["pointers"];
  48487. if (pointers) {
  48488. pointers.panningSensibility = value;
  48489. }
  48490. },
  48491. enumerable: true,
  48492. configurable: true
  48493. });
  48494. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48495. get: function () {
  48496. var keyboard = this.inputs.attached["keyboard"];
  48497. if (keyboard)
  48498. return keyboard.keysUp;
  48499. return [];
  48500. },
  48501. set: function (value) {
  48502. var keyboard = this.inputs.attached["keyboard"];
  48503. if (keyboard)
  48504. keyboard.keysUp = value;
  48505. },
  48506. enumerable: true,
  48507. configurable: true
  48508. });
  48509. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48510. get: function () {
  48511. var keyboard = this.inputs.attached["keyboard"];
  48512. if (keyboard)
  48513. return keyboard.keysDown;
  48514. return [];
  48515. },
  48516. set: function (value) {
  48517. var keyboard = this.inputs.attached["keyboard"];
  48518. if (keyboard)
  48519. keyboard.keysDown = value;
  48520. },
  48521. enumerable: true,
  48522. configurable: true
  48523. });
  48524. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48525. get: function () {
  48526. var keyboard = this.inputs.attached["keyboard"];
  48527. if (keyboard)
  48528. return keyboard.keysLeft;
  48529. return [];
  48530. },
  48531. set: function (value) {
  48532. var keyboard = this.inputs.attached["keyboard"];
  48533. if (keyboard)
  48534. keyboard.keysLeft = value;
  48535. },
  48536. enumerable: true,
  48537. configurable: true
  48538. });
  48539. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48540. get: function () {
  48541. var keyboard = this.inputs.attached["keyboard"];
  48542. if (keyboard)
  48543. return keyboard.keysRight;
  48544. return [];
  48545. },
  48546. set: function (value) {
  48547. var keyboard = this.inputs.attached["keyboard"];
  48548. if (keyboard)
  48549. keyboard.keysRight = value;
  48550. },
  48551. enumerable: true,
  48552. configurable: true
  48553. });
  48554. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48555. get: function () {
  48556. var mousewheel = this.inputs.attached["mousewheel"];
  48557. if (mousewheel)
  48558. return mousewheel.wheelPrecision;
  48559. return 0;
  48560. },
  48561. set: function (value) {
  48562. var mousewheel = this.inputs.attached["mousewheel"];
  48563. if (mousewheel)
  48564. mousewheel.wheelPrecision = value;
  48565. },
  48566. enumerable: true,
  48567. configurable: true
  48568. });
  48569. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48570. get: function () {
  48571. var mousewheel = this.inputs.attached["mousewheel"];
  48572. if (mousewheel)
  48573. return mousewheel.wheelDeltaPercentage;
  48574. return 0;
  48575. },
  48576. set: function (value) {
  48577. var mousewheel = this.inputs.attached["mousewheel"];
  48578. if (mousewheel)
  48579. mousewheel.wheelDeltaPercentage = value;
  48580. },
  48581. enumerable: true,
  48582. configurable: true
  48583. });
  48584. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48585. get: function () {
  48586. return this._bouncingBehavior;
  48587. },
  48588. enumerable: true,
  48589. configurable: true
  48590. });
  48591. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48592. get: function () {
  48593. return this._bouncingBehavior != null;
  48594. },
  48595. set: function (value) {
  48596. if (value === this.useBouncingBehavior) {
  48597. return;
  48598. }
  48599. if (value) {
  48600. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48601. this.addBehavior(this._bouncingBehavior);
  48602. }
  48603. else if (this._bouncingBehavior) {
  48604. this.removeBehavior(this._bouncingBehavior);
  48605. this._bouncingBehavior = null;
  48606. }
  48607. },
  48608. enumerable: true,
  48609. configurable: true
  48610. });
  48611. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48612. get: function () {
  48613. return this._framingBehavior;
  48614. },
  48615. enumerable: true,
  48616. configurable: true
  48617. });
  48618. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48619. get: function () {
  48620. return this._framingBehavior != null;
  48621. },
  48622. set: function (value) {
  48623. if (value === this.useFramingBehavior) {
  48624. return;
  48625. }
  48626. if (value) {
  48627. this._framingBehavior = new BABYLON.FramingBehavior();
  48628. this.addBehavior(this._framingBehavior);
  48629. }
  48630. else if (this._framingBehavior) {
  48631. this.removeBehavior(this._framingBehavior);
  48632. this._framingBehavior = null;
  48633. }
  48634. },
  48635. enumerable: true,
  48636. configurable: true
  48637. });
  48638. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48639. get: function () {
  48640. return this._autoRotationBehavior;
  48641. },
  48642. enumerable: true,
  48643. configurable: true
  48644. });
  48645. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48646. get: function () {
  48647. return this._autoRotationBehavior != null;
  48648. },
  48649. set: function (value) {
  48650. if (value === this.useAutoRotationBehavior) {
  48651. return;
  48652. }
  48653. if (value) {
  48654. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48655. this.addBehavior(this._autoRotationBehavior);
  48656. }
  48657. else if (this._autoRotationBehavior) {
  48658. this.removeBehavior(this._autoRotationBehavior);
  48659. this._autoRotationBehavior = null;
  48660. }
  48661. },
  48662. enumerable: true,
  48663. configurable: true
  48664. });
  48665. // Cache
  48666. ArcRotateCamera.prototype._initCache = function () {
  48667. _super.prototype._initCache.call(this);
  48668. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48669. this._cache.alpha = undefined;
  48670. this._cache.beta = undefined;
  48671. this._cache.radius = undefined;
  48672. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48673. };
  48674. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48675. if (!ignoreParentClass) {
  48676. _super.prototype._updateCache.call(this);
  48677. }
  48678. this._cache._target.copyFrom(this._getTargetPosition());
  48679. this._cache.alpha = this.alpha;
  48680. this._cache.beta = this.beta;
  48681. this._cache.radius = this.radius;
  48682. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48683. };
  48684. ArcRotateCamera.prototype._getTargetPosition = function () {
  48685. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48686. var pos = this._targetHost.getAbsolutePosition();
  48687. if (this._targetBoundingCenter) {
  48688. pos.addToRef(this._targetBoundingCenter, this._target);
  48689. }
  48690. else {
  48691. this._target.copyFrom(pos);
  48692. }
  48693. }
  48694. var lockedTargetPosition = this._getLockedTargetPosition();
  48695. if (lockedTargetPosition) {
  48696. return lockedTargetPosition;
  48697. }
  48698. return this._target;
  48699. };
  48700. ArcRotateCamera.prototype.storeState = function () {
  48701. this._storedAlpha = this.alpha;
  48702. this._storedBeta = this.beta;
  48703. this._storedRadius = this.radius;
  48704. this._storedTarget = this._getTargetPosition().clone();
  48705. return _super.prototype.storeState.call(this);
  48706. };
  48707. /**
  48708. * Restored camera state. You must call storeState() first
  48709. */
  48710. ArcRotateCamera.prototype._restoreStateValues = function () {
  48711. if (!_super.prototype._restoreStateValues.call(this)) {
  48712. return false;
  48713. }
  48714. this.alpha = this._storedAlpha;
  48715. this.beta = this._storedBeta;
  48716. this.radius = this._storedRadius;
  48717. this.setTarget(this._storedTarget.clone());
  48718. this.inertialAlphaOffset = 0;
  48719. this.inertialBetaOffset = 0;
  48720. this.inertialRadiusOffset = 0;
  48721. this.inertialPanningX = 0;
  48722. this.inertialPanningY = 0;
  48723. return true;
  48724. };
  48725. // Synchronized
  48726. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48727. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48728. return false;
  48729. return this._cache._target.equals(this._getTargetPosition())
  48730. && this._cache.alpha === this.alpha
  48731. && this._cache.beta === this.beta
  48732. && this._cache.radius === this.radius
  48733. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48734. };
  48735. // Methods
  48736. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48737. var _this = this;
  48738. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48739. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48740. this._useCtrlForPanning = useCtrlForPanning;
  48741. this._panningMouseButton = panningMouseButton;
  48742. this.inputs.attachElement(element, noPreventDefault);
  48743. this._reset = function () {
  48744. _this.inertialAlphaOffset = 0;
  48745. _this.inertialBetaOffset = 0;
  48746. _this.inertialRadiusOffset = 0;
  48747. _this.inertialPanningX = 0;
  48748. _this.inertialPanningY = 0;
  48749. };
  48750. };
  48751. ArcRotateCamera.prototype.detachControl = function (element) {
  48752. this.inputs.detachElement(element);
  48753. if (this._reset) {
  48754. this._reset();
  48755. }
  48756. };
  48757. ArcRotateCamera.prototype._checkInputs = function () {
  48758. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48759. if (this._collisionTriggered) {
  48760. return;
  48761. }
  48762. this.inputs.checkInputs();
  48763. // Inertia
  48764. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48765. var inertialAlphaOffset = this.inertialAlphaOffset;
  48766. if (this.beta <= 0)
  48767. inertialAlphaOffset *= -1;
  48768. if (this.getScene().useRightHandedSystem)
  48769. inertialAlphaOffset *= -1;
  48770. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48771. inertialAlphaOffset *= -1;
  48772. this.alpha += inertialAlphaOffset;
  48773. this.beta += this.inertialBetaOffset;
  48774. this.radius -= this.inertialRadiusOffset;
  48775. this.inertialAlphaOffset *= this.inertia;
  48776. this.inertialBetaOffset *= this.inertia;
  48777. this.inertialRadiusOffset *= this.inertia;
  48778. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48779. this.inertialAlphaOffset = 0;
  48780. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48781. this.inertialBetaOffset = 0;
  48782. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48783. this.inertialRadiusOffset = 0;
  48784. }
  48785. // Panning inertia
  48786. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48787. if (!this._localDirection) {
  48788. this._localDirection = BABYLON.Vector3.Zero();
  48789. this._transformedDirection = BABYLON.Vector3.Zero();
  48790. }
  48791. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48792. this._localDirection.multiplyInPlace(this.panningAxis);
  48793. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48794. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48795. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48796. if (!this.panningAxis.y) {
  48797. this._transformedDirection.y = 0;
  48798. }
  48799. if (!this._targetHost) {
  48800. if (this.panningDistanceLimit) {
  48801. this._transformedDirection.addInPlace(this._target);
  48802. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48803. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48804. this._target.copyFrom(this._transformedDirection);
  48805. }
  48806. }
  48807. else {
  48808. this._target.addInPlace(this._transformedDirection);
  48809. }
  48810. }
  48811. this.inertialPanningX *= this.panningInertia;
  48812. this.inertialPanningY *= this.panningInertia;
  48813. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48814. this.inertialPanningX = 0;
  48815. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48816. this.inertialPanningY = 0;
  48817. }
  48818. // Limits
  48819. this._checkLimits();
  48820. _super.prototype._checkInputs.call(this);
  48821. };
  48822. ArcRotateCamera.prototype._checkLimits = function () {
  48823. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48824. if (this.allowUpsideDown && this.beta > Math.PI) {
  48825. this.beta = this.beta - (2 * Math.PI);
  48826. }
  48827. }
  48828. else {
  48829. if (this.beta < this.lowerBetaLimit) {
  48830. this.beta = this.lowerBetaLimit;
  48831. }
  48832. }
  48833. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48834. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48835. this.beta = this.beta + (2 * Math.PI);
  48836. }
  48837. }
  48838. else {
  48839. if (this.beta > this.upperBetaLimit) {
  48840. this.beta = this.upperBetaLimit;
  48841. }
  48842. }
  48843. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  48844. this.alpha = this.lowerAlphaLimit;
  48845. }
  48846. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48847. this.alpha = this.upperAlphaLimit;
  48848. }
  48849. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48850. this.radius = this.lowerRadiusLimit;
  48851. }
  48852. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48853. this.radius = this.upperRadiusLimit;
  48854. }
  48855. };
  48856. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48857. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48858. this.radius = this._computationVector.length();
  48859. if (this.radius === 0) {
  48860. this.radius = 0.0001; // Just to avoid division by zero
  48861. }
  48862. // Alpha
  48863. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48864. if (this._computationVector.z < 0) {
  48865. this.alpha = 2 * Math.PI - this.alpha;
  48866. }
  48867. // Beta
  48868. this.beta = Math.acos(this._computationVector.y / this.radius);
  48869. this._checkLimits();
  48870. };
  48871. ArcRotateCamera.prototype.setPosition = function (position) {
  48872. if (this.position.equals(position)) {
  48873. return;
  48874. }
  48875. this.position.copyFrom(position);
  48876. this.rebuildAnglesAndRadius();
  48877. };
  48878. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48879. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48880. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48881. if (target.getBoundingInfo) {
  48882. if (toBoundingCenter) {
  48883. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48884. }
  48885. else {
  48886. this._targetBoundingCenter = null;
  48887. }
  48888. this._targetHost = target;
  48889. this._target = this._getTargetPosition();
  48890. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48891. }
  48892. else {
  48893. var newTarget = target;
  48894. var currentTarget = this._getTargetPosition();
  48895. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48896. return;
  48897. }
  48898. this._targetHost = null;
  48899. this._target = newTarget;
  48900. this._targetBoundingCenter = null;
  48901. this.onMeshTargetChangedObservable.notifyObservers(null);
  48902. }
  48903. this.rebuildAnglesAndRadius();
  48904. };
  48905. ArcRotateCamera.prototype._getViewMatrix = function () {
  48906. // Compute
  48907. var cosa = Math.cos(this.alpha);
  48908. var sina = Math.sin(this.alpha);
  48909. var cosb = Math.cos(this.beta);
  48910. var sinb = Math.sin(this.beta);
  48911. if (sinb === 0) {
  48912. sinb = 0.0001;
  48913. }
  48914. var target = this._getTargetPosition();
  48915. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48916. target.addToRef(this._computationVector, this._newPosition);
  48917. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48918. if (!this._collider) {
  48919. this._collider = new BABYLON.Collider();
  48920. }
  48921. this._collider._radius = this.collisionRadius;
  48922. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48923. this._collisionTriggered = true;
  48924. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48925. }
  48926. else {
  48927. this.position.copyFrom(this._newPosition);
  48928. var up = this.upVector;
  48929. if (this.allowUpsideDown && sinb < 0) {
  48930. up = up.clone();
  48931. up = up.negate();
  48932. }
  48933. this._computeViewMatrix(this.position, target, up);
  48934. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48935. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48936. }
  48937. this._currentTarget = target;
  48938. return this._viewMatrix;
  48939. };
  48940. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48941. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48942. meshes = meshes || this.getScene().meshes;
  48943. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48944. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48945. this.radius = distance * this.zoomOnFactor;
  48946. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48947. };
  48948. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48949. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48950. var meshesOrMinMaxVector;
  48951. var distance;
  48952. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48953. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48954. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48955. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48956. }
  48957. else { //minMaxVector and distance
  48958. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48959. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48960. distance = minMaxVectorAndDistance.distance;
  48961. }
  48962. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48963. if (!doNotUpdateMaxZ) {
  48964. this.maxZ = distance * 2;
  48965. }
  48966. };
  48967. /**
  48968. * @override
  48969. * Override Camera.createRigCamera
  48970. */
  48971. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48972. var alphaShift = 0;
  48973. switch (this.cameraRigMode) {
  48974. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48975. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48976. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48977. case BABYLON.Camera.RIG_MODE_VR:
  48978. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48979. break;
  48980. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48981. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48982. break;
  48983. }
  48984. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48985. rigCam._cameraRigParams = {};
  48986. return rigCam;
  48987. };
  48988. /**
  48989. * @override
  48990. * Override Camera._updateRigCameras
  48991. */
  48992. ArcRotateCamera.prototype._updateRigCameras = function () {
  48993. var camLeft = this._rigCameras[0];
  48994. var camRight = this._rigCameras[1];
  48995. camLeft.beta = camRight.beta = this.beta;
  48996. camLeft.radius = camRight.radius = this.radius;
  48997. switch (this.cameraRigMode) {
  48998. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48999. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49000. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49001. case BABYLON.Camera.RIG_MODE_VR:
  49002. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49003. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49004. break;
  49005. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49006. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49007. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49008. break;
  49009. }
  49010. _super.prototype._updateRigCameras.call(this);
  49011. };
  49012. ArcRotateCamera.prototype.dispose = function () {
  49013. this.inputs.clear();
  49014. _super.prototype.dispose.call(this);
  49015. };
  49016. ArcRotateCamera.prototype.getClassName = function () {
  49017. return "ArcRotateCamera";
  49018. };
  49019. __decorate([
  49020. BABYLON.serialize()
  49021. ], ArcRotateCamera.prototype, "alpha", void 0);
  49022. __decorate([
  49023. BABYLON.serialize()
  49024. ], ArcRotateCamera.prototype, "beta", void 0);
  49025. __decorate([
  49026. BABYLON.serialize()
  49027. ], ArcRotateCamera.prototype, "radius", void 0);
  49028. __decorate([
  49029. BABYLON.serializeAsVector3("target")
  49030. ], ArcRotateCamera.prototype, "_target", void 0);
  49031. __decorate([
  49032. BABYLON.serialize()
  49033. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49034. __decorate([
  49035. BABYLON.serialize()
  49036. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49037. __decorate([
  49038. BABYLON.serialize()
  49039. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49040. __decorate([
  49041. BABYLON.serialize()
  49042. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49043. __decorate([
  49044. BABYLON.serialize()
  49045. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49046. __decorate([
  49047. BABYLON.serialize()
  49048. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49049. __decorate([
  49050. BABYLON.serialize()
  49051. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49052. __decorate([
  49053. BABYLON.serialize()
  49054. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49055. __decorate([
  49056. BABYLON.serialize()
  49057. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49058. __decorate([
  49059. BABYLON.serialize()
  49060. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49061. __decorate([
  49062. BABYLON.serialize()
  49063. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49064. __decorate([
  49065. BABYLON.serialize()
  49066. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49067. __decorate([
  49068. BABYLON.serialize()
  49069. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49070. __decorate([
  49071. BABYLON.serializeAsVector3()
  49072. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49073. __decorate([
  49074. BABYLON.serialize()
  49075. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49076. __decorate([
  49077. BABYLON.serialize()
  49078. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49079. __decorate([
  49080. BABYLON.serialize()
  49081. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49082. return ArcRotateCamera;
  49083. }(BABYLON.TargetCamera));
  49084. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49085. })(BABYLON || (BABYLON = {}));
  49086. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49087. var BABYLON;
  49088. (function (BABYLON) {
  49089. /**
  49090. * The HemisphericLight simulates the ambient environment light,
  49091. * so the passed direction is the light reflection direction, not the incoming direction.
  49092. */
  49093. var HemisphericLight = /** @class */ (function (_super) {
  49094. __extends(HemisphericLight, _super);
  49095. /**
  49096. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49097. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49098. * The HemisphericLight can't cast shadows.
  49099. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49100. * @param name The friendly name of the light
  49101. * @param direction The direction of the light reflection
  49102. * @param scene The scene the light belongs to
  49103. */
  49104. function HemisphericLight(name, direction, scene) {
  49105. var _this = _super.call(this, name, scene) || this;
  49106. /**
  49107. * The groundColor is the light in the opposite direction to the one specified during creation.
  49108. * 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.
  49109. */
  49110. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49111. _this.direction = direction || BABYLON.Vector3.Up();
  49112. return _this;
  49113. }
  49114. HemisphericLight.prototype._buildUniformLayout = function () {
  49115. this._uniformBuffer.addUniform("vLightData", 4);
  49116. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49117. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49118. this._uniformBuffer.addUniform("vLightGround", 3);
  49119. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49120. this._uniformBuffer.addUniform("depthValues", 2);
  49121. this._uniformBuffer.create();
  49122. };
  49123. /**
  49124. * Returns the string "HemisphericLight".
  49125. * @return The class name
  49126. */
  49127. HemisphericLight.prototype.getClassName = function () {
  49128. return "HemisphericLight";
  49129. };
  49130. /**
  49131. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49132. * Returns the updated direction.
  49133. * @param target The target the direction should point to
  49134. * @return The computed direction
  49135. */
  49136. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49137. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49138. return this.direction;
  49139. };
  49140. /**
  49141. * Returns the shadow generator associated to the light.
  49142. * @returns Always null for hemispheric lights because it does not support shadows.
  49143. */
  49144. HemisphericLight.prototype.getShadowGenerator = function () {
  49145. return null;
  49146. };
  49147. /**
  49148. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49149. * @param effect The effect to update
  49150. * @param lightIndex The index of the light in the effect to update
  49151. * @returns The hemispheric light
  49152. */
  49153. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49154. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49155. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49156. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49157. return this;
  49158. };
  49159. /**
  49160. * @hidden internal use only.
  49161. */
  49162. HemisphericLight.prototype._getWorldMatrix = function () {
  49163. if (!this._worldMatrix) {
  49164. this._worldMatrix = BABYLON.Matrix.Identity();
  49165. }
  49166. return this._worldMatrix;
  49167. };
  49168. /**
  49169. * Returns the integer 3.
  49170. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49171. */
  49172. HemisphericLight.prototype.getTypeID = function () {
  49173. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49174. };
  49175. __decorate([
  49176. BABYLON.serializeAsColor3()
  49177. ], HemisphericLight.prototype, "groundColor", void 0);
  49178. __decorate([
  49179. BABYLON.serializeAsVector3()
  49180. ], HemisphericLight.prototype, "direction", void 0);
  49181. return HemisphericLight;
  49182. }(BABYLON.Light));
  49183. BABYLON.HemisphericLight = HemisphericLight;
  49184. })(BABYLON || (BABYLON = {}));
  49185. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49186. var BABYLON;
  49187. (function (BABYLON) {
  49188. /**
  49189. * Base implementation IShadowLight
  49190. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49191. */
  49192. var ShadowLight = /** @class */ (function (_super) {
  49193. __extends(ShadowLight, _super);
  49194. function ShadowLight() {
  49195. var _this = _super !== null && _super.apply(this, arguments) || this;
  49196. _this._needProjectionMatrixCompute = true;
  49197. return _this;
  49198. }
  49199. ShadowLight.prototype._setPosition = function (value) {
  49200. this._position = value;
  49201. };
  49202. Object.defineProperty(ShadowLight.prototype, "position", {
  49203. /**
  49204. * Sets the position the shadow will be casted from. Also use as the light position for both
  49205. * point and spot lights.
  49206. */
  49207. get: function () {
  49208. return this._position;
  49209. },
  49210. /**
  49211. * Sets the position the shadow will be casted from. Also use as the light position for both
  49212. * point and spot lights.
  49213. */
  49214. set: function (value) {
  49215. this._setPosition(value);
  49216. },
  49217. enumerable: true,
  49218. configurable: true
  49219. });
  49220. ShadowLight.prototype._setDirection = function (value) {
  49221. this._direction = value;
  49222. };
  49223. Object.defineProperty(ShadowLight.prototype, "direction", {
  49224. /**
  49225. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49226. * Also use as the light direction on spot and directional lights.
  49227. */
  49228. get: function () {
  49229. return this._direction;
  49230. },
  49231. /**
  49232. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49233. * Also use as the light direction on spot and directional lights.
  49234. */
  49235. set: function (value) {
  49236. this._setDirection(value);
  49237. },
  49238. enumerable: true,
  49239. configurable: true
  49240. });
  49241. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49242. /**
  49243. * Gets the shadow projection clipping minimum z value.
  49244. */
  49245. get: function () {
  49246. return this._shadowMinZ;
  49247. },
  49248. /**
  49249. * Sets the shadow projection clipping minimum z value.
  49250. */
  49251. set: function (value) {
  49252. this._shadowMinZ = value;
  49253. this.forceProjectionMatrixCompute();
  49254. },
  49255. enumerable: true,
  49256. configurable: true
  49257. });
  49258. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49259. /**
  49260. * Sets the shadow projection clipping maximum z value.
  49261. */
  49262. get: function () {
  49263. return this._shadowMaxZ;
  49264. },
  49265. /**
  49266. * Gets the shadow projection clipping maximum z value.
  49267. */
  49268. set: function (value) {
  49269. this._shadowMaxZ = value;
  49270. this.forceProjectionMatrixCompute();
  49271. },
  49272. enumerable: true,
  49273. configurable: true
  49274. });
  49275. /**
  49276. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49277. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49278. */
  49279. ShadowLight.prototype.computeTransformedInformation = function () {
  49280. if (this.parent && this.parent.getWorldMatrix) {
  49281. if (!this.transformedPosition) {
  49282. this.transformedPosition = BABYLON.Vector3.Zero();
  49283. }
  49284. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49285. // In case the direction is present.
  49286. if (this.direction) {
  49287. if (!this.transformedDirection) {
  49288. this.transformedDirection = BABYLON.Vector3.Zero();
  49289. }
  49290. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49291. }
  49292. return true;
  49293. }
  49294. return false;
  49295. };
  49296. /**
  49297. * Return the depth scale used for the shadow map.
  49298. * @returns the depth scale.
  49299. */
  49300. ShadowLight.prototype.getDepthScale = function () {
  49301. return 50.0;
  49302. };
  49303. /**
  49304. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49305. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49306. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49307. */
  49308. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49309. return this.transformedDirection ? this.transformedDirection : this.direction;
  49310. };
  49311. /**
  49312. * Returns the ShadowLight absolute position in the World.
  49313. * @returns the position vector in world space
  49314. */
  49315. ShadowLight.prototype.getAbsolutePosition = function () {
  49316. return this.transformedPosition ? this.transformedPosition : this.position;
  49317. };
  49318. /**
  49319. * Sets the ShadowLight direction toward the passed target.
  49320. * @param target The point tot target in local space
  49321. * @returns the updated ShadowLight direction
  49322. */
  49323. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49324. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49325. return this.direction;
  49326. };
  49327. /**
  49328. * Returns the light rotation in euler definition.
  49329. * @returns the x y z rotation in local space.
  49330. */
  49331. ShadowLight.prototype.getRotation = function () {
  49332. this.direction.normalize();
  49333. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49334. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49335. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49336. };
  49337. /**
  49338. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49339. * @returns true if a cube texture needs to be use
  49340. */
  49341. ShadowLight.prototype.needCube = function () {
  49342. return false;
  49343. };
  49344. /**
  49345. * Detects if the projection matrix requires to be recomputed this frame.
  49346. * @returns true if it requires to be recomputed otherwise, false.
  49347. */
  49348. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49349. return this._needProjectionMatrixCompute;
  49350. };
  49351. /**
  49352. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49353. */
  49354. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49355. this._needProjectionMatrixCompute = true;
  49356. };
  49357. /**
  49358. * Get the world matrix of the sahdow lights.
  49359. * @hidden Internal Use Only
  49360. */
  49361. ShadowLight.prototype._getWorldMatrix = function () {
  49362. if (!this._worldMatrix) {
  49363. this._worldMatrix = BABYLON.Matrix.Identity();
  49364. }
  49365. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49366. return this._worldMatrix;
  49367. };
  49368. /**
  49369. * Gets the minZ used for shadow according to both the scene and the light.
  49370. * @param activeCamera The camera we are returning the min for
  49371. * @returns the depth min z
  49372. */
  49373. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49374. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49375. };
  49376. /**
  49377. * Gets the maxZ used for shadow according to both the scene and the light.
  49378. * @param activeCamera The camera we are returning the max for
  49379. * @returns the depth max z
  49380. */
  49381. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49382. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49383. };
  49384. /**
  49385. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49386. * @param matrix The materix to updated with the projection information
  49387. * @param viewMatrix The transform matrix of the light
  49388. * @param renderList The list of mesh to render in the map
  49389. * @returns The current light
  49390. */
  49391. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49392. if (this.customProjectionMatrixBuilder) {
  49393. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49394. }
  49395. else {
  49396. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49397. }
  49398. return this;
  49399. };
  49400. __decorate([
  49401. BABYLON.serializeAsVector3()
  49402. ], ShadowLight.prototype, "position", null);
  49403. __decorate([
  49404. BABYLON.serializeAsVector3()
  49405. ], ShadowLight.prototype, "direction", null);
  49406. __decorate([
  49407. BABYLON.serialize()
  49408. ], ShadowLight.prototype, "shadowMinZ", null);
  49409. __decorate([
  49410. BABYLON.serialize()
  49411. ], ShadowLight.prototype, "shadowMaxZ", null);
  49412. return ShadowLight;
  49413. }(BABYLON.Light));
  49414. BABYLON.ShadowLight = ShadowLight;
  49415. })(BABYLON || (BABYLON = {}));
  49416. //# sourceMappingURL=babylon.shadowLight.js.map
  49417. var BABYLON;
  49418. (function (BABYLON) {
  49419. /**
  49420. * A point light is a light defined by an unique point in world space.
  49421. * The light is emitted in every direction from this point.
  49422. * A good example of a point light is a standard light bulb.
  49423. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49424. */
  49425. var PointLight = /** @class */ (function (_super) {
  49426. __extends(PointLight, _super);
  49427. /**
  49428. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49429. * A PointLight emits the light in every direction.
  49430. * It can cast shadows.
  49431. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49432. * ```javascript
  49433. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49434. * ```
  49435. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49436. * @param name The light friendly name
  49437. * @param position The position of the point light in the scene
  49438. * @param scene The scene the lights belongs to
  49439. */
  49440. function PointLight(name, position, scene) {
  49441. var _this = _super.call(this, name, scene) || this;
  49442. _this._shadowAngle = Math.PI / 2;
  49443. _this.position = position;
  49444. return _this;
  49445. }
  49446. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49447. /**
  49448. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49449. * This specifies what angle the shadow will use to be created.
  49450. *
  49451. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49452. */
  49453. get: function () {
  49454. return this._shadowAngle;
  49455. },
  49456. /**
  49457. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49458. * This specifies what angle the shadow will use to be created.
  49459. *
  49460. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49461. */
  49462. set: function (value) {
  49463. this._shadowAngle = value;
  49464. this.forceProjectionMatrixCompute();
  49465. },
  49466. enumerable: true,
  49467. configurable: true
  49468. });
  49469. Object.defineProperty(PointLight.prototype, "direction", {
  49470. /**
  49471. * Gets the direction if it has been set.
  49472. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49473. */
  49474. get: function () {
  49475. return this._direction;
  49476. },
  49477. /**
  49478. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49479. */
  49480. set: function (value) {
  49481. var previousNeedCube = this.needCube();
  49482. this._direction = value;
  49483. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49484. this._shadowGenerator.recreateShadowMap();
  49485. }
  49486. },
  49487. enumerable: true,
  49488. configurable: true
  49489. });
  49490. /**
  49491. * Returns the string "PointLight"
  49492. * @returns the class name
  49493. */
  49494. PointLight.prototype.getClassName = function () {
  49495. return "PointLight";
  49496. };
  49497. /**
  49498. * Returns the integer 0.
  49499. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49500. */
  49501. PointLight.prototype.getTypeID = function () {
  49502. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49503. };
  49504. /**
  49505. * Specifies wether or not the shadowmap should be a cube texture.
  49506. * @returns true if the shadowmap needs to be a cube texture.
  49507. */
  49508. PointLight.prototype.needCube = function () {
  49509. return !this.direction;
  49510. };
  49511. /**
  49512. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49513. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49514. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49515. */
  49516. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49517. if (this.direction) {
  49518. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49519. }
  49520. else {
  49521. switch (faceIndex) {
  49522. case 0:
  49523. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49524. case 1:
  49525. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49526. case 2:
  49527. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49528. case 3:
  49529. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49530. case 4:
  49531. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49532. case 5:
  49533. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49534. }
  49535. }
  49536. return BABYLON.Vector3.Zero();
  49537. };
  49538. /**
  49539. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49540. * - fov = PI / 2
  49541. * - aspect ratio : 1.0
  49542. * - z-near and far equal to the active camera minZ and maxZ.
  49543. * Returns the PointLight.
  49544. */
  49545. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49546. var activeCamera = this.getScene().activeCamera;
  49547. if (!activeCamera) {
  49548. return;
  49549. }
  49550. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49551. };
  49552. PointLight.prototype._buildUniformLayout = function () {
  49553. this._uniformBuffer.addUniform("vLightData", 4);
  49554. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49555. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49556. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49557. this._uniformBuffer.addUniform("depthValues", 2);
  49558. this._uniformBuffer.create();
  49559. };
  49560. /**
  49561. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49562. * @param effect The effect to update
  49563. * @param lightIndex The index of the light in the effect to update
  49564. * @returns The point light
  49565. */
  49566. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49567. if (this.computeTransformedInformation()) {
  49568. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49569. return this;
  49570. }
  49571. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49572. return this;
  49573. };
  49574. __decorate([
  49575. BABYLON.serialize()
  49576. ], PointLight.prototype, "shadowAngle", null);
  49577. return PointLight;
  49578. }(BABYLON.ShadowLight));
  49579. BABYLON.PointLight = PointLight;
  49580. })(BABYLON || (BABYLON = {}));
  49581. //# sourceMappingURL=babylon.pointLight.js.map
  49582. var BABYLON;
  49583. (function (BABYLON) {
  49584. /**
  49585. * A directional light is defined by a direction (what a surprise!).
  49586. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49587. * 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.
  49588. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49589. */
  49590. var DirectionalLight = /** @class */ (function (_super) {
  49591. __extends(DirectionalLight, _super);
  49592. /**
  49593. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49594. * The directional light is emitted from everywhere in the given direction.
  49595. * It can cast shawdows.
  49596. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49597. * @param name The friendly name of the light
  49598. * @param direction The direction of the light
  49599. * @param scene The scene the light belongs to
  49600. */
  49601. function DirectionalLight(name, direction, scene) {
  49602. var _this = _super.call(this, name, scene) || this;
  49603. _this._shadowFrustumSize = 0;
  49604. _this._shadowOrthoScale = 0.1;
  49605. /**
  49606. * Automatically compute the projection matrix to best fit (including all the casters)
  49607. * on each frame.
  49608. */
  49609. _this.autoUpdateExtends = true;
  49610. // Cache
  49611. _this._orthoLeft = Number.MAX_VALUE;
  49612. _this._orthoRight = Number.MIN_VALUE;
  49613. _this._orthoTop = Number.MIN_VALUE;
  49614. _this._orthoBottom = Number.MAX_VALUE;
  49615. _this.position = direction.scale(-1.0);
  49616. _this.direction = direction;
  49617. return _this;
  49618. }
  49619. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49620. /**
  49621. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49622. */
  49623. get: function () {
  49624. return this._shadowFrustumSize;
  49625. },
  49626. /**
  49627. * Specifies a fix frustum size for the shadow generation.
  49628. */
  49629. set: function (value) {
  49630. this._shadowFrustumSize = value;
  49631. this.forceProjectionMatrixCompute();
  49632. },
  49633. enumerable: true,
  49634. configurable: true
  49635. });
  49636. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49637. /**
  49638. * Gets the shadow projection scale against the optimal computed one.
  49639. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49640. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49641. */
  49642. get: function () {
  49643. return this._shadowOrthoScale;
  49644. },
  49645. /**
  49646. * Sets the shadow projection scale against the optimal computed one.
  49647. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49648. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49649. */
  49650. set: function (value) {
  49651. this._shadowOrthoScale = value;
  49652. this.forceProjectionMatrixCompute();
  49653. },
  49654. enumerable: true,
  49655. configurable: true
  49656. });
  49657. /**
  49658. * Returns the string "DirectionalLight".
  49659. * @return The class name
  49660. */
  49661. DirectionalLight.prototype.getClassName = function () {
  49662. return "DirectionalLight";
  49663. };
  49664. /**
  49665. * Returns the integer 1.
  49666. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49667. */
  49668. DirectionalLight.prototype.getTypeID = function () {
  49669. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49670. };
  49671. /**
  49672. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49673. * Returns the DirectionalLight Shadow projection matrix.
  49674. */
  49675. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49676. if (this.shadowFrustumSize > 0) {
  49677. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49678. }
  49679. else {
  49680. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49681. }
  49682. };
  49683. /**
  49684. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49685. * Returns the DirectionalLight Shadow projection matrix.
  49686. */
  49687. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49688. var activeCamera = this.getScene().activeCamera;
  49689. if (!activeCamera) {
  49690. return;
  49691. }
  49692. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49693. };
  49694. /**
  49695. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49696. * Returns the DirectionalLight Shadow projection matrix.
  49697. */
  49698. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49699. var activeCamera = this.getScene().activeCamera;
  49700. if (!activeCamera) {
  49701. return;
  49702. }
  49703. // Check extends
  49704. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49705. var tempVector3 = BABYLON.Vector3.Zero();
  49706. this._orthoLeft = Number.MAX_VALUE;
  49707. this._orthoRight = Number.MIN_VALUE;
  49708. this._orthoTop = Number.MIN_VALUE;
  49709. this._orthoBottom = Number.MAX_VALUE;
  49710. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49711. var mesh = renderList[meshIndex];
  49712. if (!mesh) {
  49713. continue;
  49714. }
  49715. var boundingInfo = mesh.getBoundingInfo();
  49716. var boundingBox = boundingInfo.boundingBox;
  49717. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49718. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49719. if (tempVector3.x < this._orthoLeft)
  49720. this._orthoLeft = tempVector3.x;
  49721. if (tempVector3.y < this._orthoBottom)
  49722. this._orthoBottom = tempVector3.y;
  49723. if (tempVector3.x > this._orthoRight)
  49724. this._orthoRight = tempVector3.x;
  49725. if (tempVector3.y > this._orthoTop)
  49726. this._orthoTop = tempVector3.y;
  49727. }
  49728. }
  49729. }
  49730. var xOffset = this._orthoRight - this._orthoLeft;
  49731. var yOffset = this._orthoTop - this._orthoBottom;
  49732. 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);
  49733. };
  49734. DirectionalLight.prototype._buildUniformLayout = function () {
  49735. this._uniformBuffer.addUniform("vLightData", 4);
  49736. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49737. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49738. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49739. this._uniformBuffer.addUniform("depthValues", 2);
  49740. this._uniformBuffer.create();
  49741. };
  49742. /**
  49743. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49744. * @param effect The effect to update
  49745. * @param lightIndex The index of the light in the effect to update
  49746. * @returns The directional light
  49747. */
  49748. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49749. if (this.computeTransformedInformation()) {
  49750. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49751. return this;
  49752. }
  49753. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49754. return this;
  49755. };
  49756. /**
  49757. * Gets the minZ used for shadow according to both the scene and the light.
  49758. *
  49759. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49760. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49761. * @param activeCamera The camera we are returning the min for
  49762. * @returns the depth min z
  49763. */
  49764. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49765. return 1;
  49766. };
  49767. /**
  49768. * Gets the maxZ used for shadow according to both the scene and the light.
  49769. *
  49770. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49771. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49772. * @param activeCamera The camera we are returning the max for
  49773. * @returns the depth max z
  49774. */
  49775. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49776. return 1;
  49777. };
  49778. __decorate([
  49779. BABYLON.serialize()
  49780. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49781. __decorate([
  49782. BABYLON.serialize()
  49783. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49784. __decorate([
  49785. BABYLON.serialize()
  49786. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49787. return DirectionalLight;
  49788. }(BABYLON.ShadowLight));
  49789. BABYLON.DirectionalLight = DirectionalLight;
  49790. })(BABYLON || (BABYLON = {}));
  49791. //# sourceMappingURL=babylon.directionalLight.js.map
  49792. var BABYLON;
  49793. (function (BABYLON) {
  49794. /**
  49795. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49796. * These values define a cone of light starting from the position, emitting toward the direction.
  49797. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49798. * and the exponent defines the speed of the decay of the light with distance (reach).
  49799. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49800. */
  49801. var SpotLight = /** @class */ (function (_super) {
  49802. __extends(SpotLight, _super);
  49803. /**
  49804. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49805. * It can cast shadows.
  49806. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49807. * @param name The light friendly name
  49808. * @param position The position of the spot light in the scene
  49809. * @param direction The direction of the light in the scene
  49810. * @param angle The cone angle of the light in Radians
  49811. * @param exponent The light decay speed with the distance from the emission spot
  49812. * @param scene The scene the lights belongs to
  49813. */
  49814. function SpotLight(name, position, direction, angle, exponent, scene) {
  49815. var _this = _super.call(this, name, scene) || this;
  49816. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49817. _this._projectionTextureLightNear = 1e-6;
  49818. _this._projectionTextureLightFar = 1000.0;
  49819. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49820. _this._projectionTextureViewLightDirty = true;
  49821. _this._projectionTextureProjectionLightDirty = true;
  49822. _this._projectionTextureDirty = true;
  49823. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49824. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49825. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49826. _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);
  49827. _this.position = position;
  49828. _this.direction = direction;
  49829. _this.angle = angle;
  49830. _this.exponent = exponent;
  49831. return _this;
  49832. }
  49833. Object.defineProperty(SpotLight.prototype, "angle", {
  49834. /**
  49835. * Gets the cone angle of the spot light in Radians.
  49836. */
  49837. get: function () {
  49838. return this._angle;
  49839. },
  49840. /**
  49841. * Sets the cone angle of the spot light in Radians.
  49842. */
  49843. set: function (value) {
  49844. this._angle = value;
  49845. this._projectionTextureProjectionLightDirty = true;
  49846. this.forceProjectionMatrixCompute();
  49847. },
  49848. enumerable: true,
  49849. configurable: true
  49850. });
  49851. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49852. /**
  49853. * Allows scaling the angle of the light for shadow generation only.
  49854. */
  49855. get: function () {
  49856. return this._shadowAngleScale;
  49857. },
  49858. /**
  49859. * Allows scaling the angle of the light for shadow generation only.
  49860. */
  49861. set: function (value) {
  49862. this._shadowAngleScale = value;
  49863. this.forceProjectionMatrixCompute();
  49864. },
  49865. enumerable: true,
  49866. configurable: true
  49867. });
  49868. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49869. /**
  49870. * Allows reading the projecton texture
  49871. */
  49872. get: function () {
  49873. return this._projectionTextureMatrix;
  49874. },
  49875. enumerable: true,
  49876. configurable: true
  49877. });
  49878. ;
  49879. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49880. /**
  49881. * Gets the near clip of the Spotlight for texture projection.
  49882. */
  49883. get: function () {
  49884. return this._projectionTextureLightNear;
  49885. },
  49886. /**
  49887. * Sets the near clip of the Spotlight for texture projection.
  49888. */
  49889. set: function (value) {
  49890. this._projectionTextureLightNear = value;
  49891. this._projectionTextureProjectionLightDirty = true;
  49892. },
  49893. enumerable: true,
  49894. configurable: true
  49895. });
  49896. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49897. /**
  49898. * Gets the far clip of the Spotlight for texture projection.
  49899. */
  49900. get: function () {
  49901. return this._projectionTextureLightFar;
  49902. },
  49903. /**
  49904. * Sets the far clip of the Spotlight for texture projection.
  49905. */
  49906. set: function (value) {
  49907. this._projectionTextureLightFar = value;
  49908. this._projectionTextureProjectionLightDirty = true;
  49909. },
  49910. enumerable: true,
  49911. configurable: true
  49912. });
  49913. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49914. /**
  49915. * Gets the Up vector of the Spotlight for texture projection.
  49916. */
  49917. get: function () {
  49918. return this._projectionTextureUpDirection;
  49919. },
  49920. /**
  49921. * Sets the Up vector of the Spotlight for texture projection.
  49922. */
  49923. set: function (value) {
  49924. this._projectionTextureUpDirection = value;
  49925. this._projectionTextureProjectionLightDirty = true;
  49926. },
  49927. enumerable: true,
  49928. configurable: true
  49929. });
  49930. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49931. /**
  49932. * Gets the projection texture of the light.
  49933. */
  49934. get: function () {
  49935. return this._projectionTexture;
  49936. },
  49937. /**
  49938. * Sets the projection texture of the light.
  49939. */
  49940. set: function (value) {
  49941. this._projectionTexture = value;
  49942. this._projectionTextureDirty = true;
  49943. },
  49944. enumerable: true,
  49945. configurable: true
  49946. });
  49947. /**
  49948. * Returns the string "SpotLight".
  49949. * @returns the class name
  49950. */
  49951. SpotLight.prototype.getClassName = function () {
  49952. return "SpotLight";
  49953. };
  49954. /**
  49955. * Returns the integer 2.
  49956. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49957. */
  49958. SpotLight.prototype.getTypeID = function () {
  49959. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49960. };
  49961. /**
  49962. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49963. */
  49964. SpotLight.prototype._setDirection = function (value) {
  49965. _super.prototype._setDirection.call(this, value);
  49966. this._projectionTextureViewLightDirty = true;
  49967. };
  49968. /**
  49969. * Overrides the position setter to recompute the projection texture view light Matrix.
  49970. */
  49971. SpotLight.prototype._setPosition = function (value) {
  49972. _super.prototype._setPosition.call(this, value);
  49973. this._projectionTextureViewLightDirty = true;
  49974. };
  49975. /**
  49976. * 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.
  49977. * Returns the SpotLight.
  49978. */
  49979. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49980. var activeCamera = this.getScene().activeCamera;
  49981. if (!activeCamera) {
  49982. return;
  49983. }
  49984. this._shadowAngleScale = this._shadowAngleScale || 1;
  49985. var angle = this._shadowAngleScale * this._angle;
  49986. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49987. };
  49988. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49989. this._projectionTextureViewLightDirty = false;
  49990. this._projectionTextureDirty = true;
  49991. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49992. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49993. };
  49994. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49995. this._projectionTextureProjectionLightDirty = false;
  49996. this._projectionTextureDirty = true;
  49997. var light_far = this.projectionTextureLightFar;
  49998. var light_near = this.projectionTextureLightNear;
  49999. var P = light_far / (light_far - light_near);
  50000. var Q = -P * light_near;
  50001. var S = 1.0 / Math.tan(this._angle / 2.0);
  50002. var A = 1.0;
  50003. 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);
  50004. };
  50005. /**
  50006. * Main function for light texture projection matrix computing.
  50007. */
  50008. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50009. this._projectionTextureDirty = false;
  50010. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50011. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50012. };
  50013. SpotLight.prototype._buildUniformLayout = function () {
  50014. this._uniformBuffer.addUniform("vLightData", 4);
  50015. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50016. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50017. this._uniformBuffer.addUniform("vLightDirection", 3);
  50018. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50019. this._uniformBuffer.addUniform("depthValues", 2);
  50020. this._uniformBuffer.create();
  50021. };
  50022. /**
  50023. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50024. * @param effect The effect to update
  50025. * @param lightIndex The index of the light in the effect to update
  50026. * @returns The spot light
  50027. */
  50028. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50029. var normalizeDirection;
  50030. if (this.computeTransformedInformation()) {
  50031. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50032. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50033. }
  50034. else {
  50035. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50036. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50037. }
  50038. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  50039. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50040. if (this._projectionTextureViewLightDirty) {
  50041. this._computeProjectionTextureViewLightMatrix();
  50042. }
  50043. if (this._projectionTextureProjectionLightDirty) {
  50044. this._computeProjectionTextureProjectionLightMatrix();
  50045. }
  50046. if (this._projectionTextureDirty) {
  50047. this._computeProjectionTextureMatrix();
  50048. }
  50049. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50050. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50051. }
  50052. return this;
  50053. };
  50054. /**
  50055. * Disposes the light and the associated resources.
  50056. */
  50057. SpotLight.prototype.dispose = function () {
  50058. _super.prototype.dispose.call(this);
  50059. if (this._projectionTexture) {
  50060. this._projectionTexture.dispose();
  50061. }
  50062. };
  50063. __decorate([
  50064. BABYLON.serialize()
  50065. ], SpotLight.prototype, "angle", null);
  50066. __decorate([
  50067. BABYLON.serialize()
  50068. ], SpotLight.prototype, "shadowAngleScale", null);
  50069. __decorate([
  50070. BABYLON.serialize()
  50071. ], SpotLight.prototype, "exponent", void 0);
  50072. __decorate([
  50073. BABYLON.serialize()
  50074. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50075. __decorate([
  50076. BABYLON.serialize()
  50077. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50078. __decorate([
  50079. BABYLON.serialize()
  50080. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50081. __decorate([
  50082. BABYLON.serializeAsTexture("projectedLightTexture")
  50083. ], SpotLight.prototype, "_projectionTexture", void 0);
  50084. return SpotLight;
  50085. }(BABYLON.ShadowLight));
  50086. BABYLON.SpotLight = SpotLight;
  50087. })(BABYLON || (BABYLON = {}));
  50088. //# sourceMappingURL=babylon.spotLight.js.map
  50089. var BABYLON;
  50090. (function (BABYLON) {
  50091. /**
  50092. * Class used to override all child animations of a given target
  50093. */
  50094. var AnimationPropertiesOverride = /** @class */ (function () {
  50095. function AnimationPropertiesOverride() {
  50096. /**
  50097. * Gets or sets a value indicating if animation blending must be used
  50098. */
  50099. this.enableBlending = false;
  50100. /**
  50101. * Gets or sets the blending speed to use when enableBlending is true
  50102. */
  50103. this.blendingSpeed = 0.01;
  50104. /**
  50105. * Gets or sets the default loop mode to use
  50106. */
  50107. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50108. }
  50109. return AnimationPropertiesOverride;
  50110. }());
  50111. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50112. })(BABYLON || (BABYLON = {}));
  50113. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50114. var BABYLON;
  50115. (function (BABYLON) {
  50116. /**
  50117. * Represents the range of an animation
  50118. */
  50119. var AnimationRange = /** @class */ (function () {
  50120. /**
  50121. * Initializes the range of an animation
  50122. * @param name The name of the animation range
  50123. * @param from The starting frame of the animation
  50124. * @param to The ending frame of the animation
  50125. */
  50126. function AnimationRange(
  50127. /**The name of the animation range**/
  50128. name,
  50129. /**The starting frame of the animation */
  50130. from,
  50131. /**The ending frame of the animation*/
  50132. to) {
  50133. this.name = name;
  50134. this.from = from;
  50135. this.to = to;
  50136. }
  50137. /**
  50138. * Makes a copy of the animation range
  50139. * @returns A copy of the animation range
  50140. */
  50141. AnimationRange.prototype.clone = function () {
  50142. return new AnimationRange(this.name, this.from, this.to);
  50143. };
  50144. return AnimationRange;
  50145. }());
  50146. BABYLON.AnimationRange = AnimationRange;
  50147. /**
  50148. * Composed of a frame, and an action function
  50149. */
  50150. var AnimationEvent = /** @class */ (function () {
  50151. /**
  50152. * Initializes the animation event
  50153. * @param frame The frame for which the event is triggered
  50154. * @param action The event to perform when triggered
  50155. * @param onlyOnce Specifies if the event should be triggered only once
  50156. */
  50157. function AnimationEvent(
  50158. /** The frame for which the event is triggered **/
  50159. frame,
  50160. /** The event to perform when triggered **/
  50161. action,
  50162. /** Specifies if the event should be triggered only once**/
  50163. onlyOnce) {
  50164. this.frame = frame;
  50165. this.action = action;
  50166. this.onlyOnce = onlyOnce;
  50167. /**
  50168. * Specifies if the animation event is done
  50169. */
  50170. this.isDone = false;
  50171. }
  50172. return AnimationEvent;
  50173. }());
  50174. BABYLON.AnimationEvent = AnimationEvent;
  50175. /**
  50176. * A cursor which tracks a point on a path
  50177. */
  50178. var PathCursor = /** @class */ (function () {
  50179. /**
  50180. * Initializes the path cursor
  50181. * @param path The path to track
  50182. */
  50183. function PathCursor(path) {
  50184. this.path = path;
  50185. /**
  50186. * Stores path cursor callbacks for when an onchange event is triggered
  50187. */
  50188. this._onchange = new Array();
  50189. /**
  50190. * The value of the path cursor
  50191. */
  50192. this.value = 0;
  50193. /**
  50194. * The animation array of the path cursor
  50195. */
  50196. this.animations = new Array();
  50197. }
  50198. /**
  50199. * Gets the cursor point on the path
  50200. * @returns A point on the path cursor at the cursor location
  50201. */
  50202. PathCursor.prototype.getPoint = function () {
  50203. var point = this.path.getPointAtLengthPosition(this.value);
  50204. return new BABYLON.Vector3(point.x, 0, point.y);
  50205. };
  50206. /**
  50207. * Moves the cursor ahead by the step amount
  50208. * @param step The amount to move the cursor forward
  50209. * @returns This path cursor
  50210. */
  50211. PathCursor.prototype.moveAhead = function (step) {
  50212. if (step === void 0) { step = 0.002; }
  50213. this.move(step);
  50214. return this;
  50215. };
  50216. /**
  50217. * Moves the cursor behind by the step amount
  50218. * @param step The amount to move the cursor back
  50219. * @returns This path cursor
  50220. */
  50221. PathCursor.prototype.moveBack = function (step) {
  50222. if (step === void 0) { step = 0.002; }
  50223. this.move(-step);
  50224. return this;
  50225. };
  50226. /**
  50227. * Moves the cursor by the step amount
  50228. * If the step amount is greater than one, an exception is thrown
  50229. * @param step The amount to move the cursor
  50230. * @returns This path cursor
  50231. */
  50232. PathCursor.prototype.move = function (step) {
  50233. if (Math.abs(step) > 1) {
  50234. throw "step size should be less than 1.";
  50235. }
  50236. this.value += step;
  50237. this.ensureLimits();
  50238. this.raiseOnChange();
  50239. return this;
  50240. };
  50241. /**
  50242. * Ensures that the value is limited between zero and one
  50243. * @returns This path cursor
  50244. */
  50245. PathCursor.prototype.ensureLimits = function () {
  50246. while (this.value > 1) {
  50247. this.value -= 1;
  50248. }
  50249. while (this.value < 0) {
  50250. this.value += 1;
  50251. }
  50252. return this;
  50253. };
  50254. /**
  50255. * Runs onchange callbacks on change (used by the animation engine)
  50256. * @returns This path cursor
  50257. */
  50258. PathCursor.prototype.raiseOnChange = function () {
  50259. var _this = this;
  50260. this._onchange.forEach(function (f) { return f(_this); });
  50261. return this;
  50262. };
  50263. /**
  50264. * Executes a function on change
  50265. * @param f A path cursor onchange callback
  50266. * @returns This path cursor
  50267. */
  50268. PathCursor.prototype.onchange = function (f) {
  50269. this._onchange.push(f);
  50270. return this;
  50271. };
  50272. return PathCursor;
  50273. }());
  50274. BABYLON.PathCursor = PathCursor;
  50275. /**
  50276. * Enum for the animation key frame interpolation type
  50277. */
  50278. var AnimationKeyInterpolation;
  50279. (function (AnimationKeyInterpolation) {
  50280. /**
  50281. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50282. */
  50283. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50284. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50285. /**
  50286. * Class used to store any kind of animation
  50287. */
  50288. var Animation = /** @class */ (function () {
  50289. /**
  50290. * Initializes the animation
  50291. * @param name Name of the animation
  50292. * @param targetProperty Property to animate
  50293. * @param framePerSecond The frames per second of the animation
  50294. * @param dataType The data type of the animation
  50295. * @param loopMode The loop mode of the animation
  50296. * @param enableBlendings Specifies if blending should be enabled
  50297. */
  50298. function Animation(
  50299. /**Name of the animation */
  50300. name,
  50301. /**Property to animate */
  50302. targetProperty,
  50303. /**The frames per second of the animation */
  50304. framePerSecond,
  50305. /**The data type of the animation */
  50306. dataType,
  50307. /**The loop mode of the animation */
  50308. loopMode,
  50309. /**Specifies if blending should be enabled */
  50310. enableBlending) {
  50311. this.name = name;
  50312. this.targetProperty = targetProperty;
  50313. this.framePerSecond = framePerSecond;
  50314. this.dataType = dataType;
  50315. this.loopMode = loopMode;
  50316. this.enableBlending = enableBlending;
  50317. /**
  50318. * @hidden Internal use only
  50319. */
  50320. this._runtimeAnimations = new Array();
  50321. /**
  50322. * The set of event that will be linked to this animation
  50323. */
  50324. this._events = new Array();
  50325. /**
  50326. * Stores the blending speed of the animation
  50327. */
  50328. this.blendingSpeed = 0.01;
  50329. /**
  50330. * Stores the animation ranges for the animation
  50331. */
  50332. this._ranges = {};
  50333. this.targetPropertyPath = targetProperty.split(".");
  50334. this.dataType = dataType;
  50335. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50336. }
  50337. /**
  50338. * @hidden Internal use
  50339. */
  50340. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50341. var dataType = undefined;
  50342. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50343. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50344. }
  50345. else if (from instanceof BABYLON.Quaternion) {
  50346. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50347. }
  50348. else if (from instanceof BABYLON.Vector3) {
  50349. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50350. }
  50351. else if (from instanceof BABYLON.Vector2) {
  50352. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50353. }
  50354. else if (from instanceof BABYLON.Color3) {
  50355. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50356. }
  50357. else if (from instanceof BABYLON.Size) {
  50358. dataType = Animation.ANIMATIONTYPE_SIZE;
  50359. }
  50360. if (dataType == undefined) {
  50361. return null;
  50362. }
  50363. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50364. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50365. animation.setKeys(keys);
  50366. if (easingFunction !== undefined) {
  50367. animation.setEasingFunction(easingFunction);
  50368. }
  50369. return animation;
  50370. };
  50371. /**
  50372. * Sets up an animation
  50373. * @param property The property to animate
  50374. * @param animationType The animation type to apply
  50375. * @param framePerSecond The frames per second of the animation
  50376. * @param easingFunction The easing function used in the animation
  50377. * @returns The created animation
  50378. */
  50379. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50380. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50381. animation.setEasingFunction(easingFunction);
  50382. return animation;
  50383. };
  50384. /**
  50385. * Create and start an animation on a node
  50386. * @param name defines the name of the global animation that will be run on all nodes
  50387. * @param node defines the root node where the animation will take place
  50388. * @param targetProperty defines property to animate
  50389. * @param framePerSecond defines the number of frame per second yo use
  50390. * @param totalFrame defines the number of frames in total
  50391. * @param from defines the initial value
  50392. * @param to defines the final value
  50393. * @param loopMode defines which loop mode you want to use (off by default)
  50394. * @param easingFunction defines the easing function to use (linear by default)
  50395. * @param onAnimationEnd defines the callback to call when animation end
  50396. * @returns the animatable created for this animation
  50397. */
  50398. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50399. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50400. if (!animation) {
  50401. return null;
  50402. }
  50403. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50404. };
  50405. /**
  50406. * Create and start an animation on a node and its descendants
  50407. * @param name defines the name of the global animation that will be run on all nodes
  50408. * @param node defines the root node where the animation will take place
  50409. * @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
  50410. * @param targetProperty defines property to animate
  50411. * @param framePerSecond defines the number of frame per second to use
  50412. * @param totalFrame defines the number of frames in total
  50413. * @param from defines the initial value
  50414. * @param to defines the final value
  50415. * @param loopMode defines which loop mode you want to use (off by default)
  50416. * @param easingFunction defines the easing function to use (linear by default)
  50417. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50418. * @returns the list of animatables created for all nodes
  50419. * @example https://www.babylonjs-playground.com/#MH0VLI
  50420. */
  50421. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50422. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50423. if (!animation) {
  50424. return null;
  50425. }
  50426. var scene = node.getScene();
  50427. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50428. };
  50429. /**
  50430. * Creates a new animation, merges it with the existing animations and starts it
  50431. * @param name Name of the animation
  50432. * @param node Node which contains the scene that begins the animations
  50433. * @param targetProperty Specifies which property to animate
  50434. * @param framePerSecond The frames per second of the animation
  50435. * @param totalFrame The total number of frames
  50436. * @param from The frame at the beginning of the animation
  50437. * @param to The frame at the end of the animation
  50438. * @param loopMode Specifies the loop mode of the animation
  50439. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50440. * @param onAnimationEnd Callback to run once the animation is complete
  50441. * @returns Nullable animation
  50442. */
  50443. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50444. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50445. if (!animation) {
  50446. return null;
  50447. }
  50448. node.animations.push(animation);
  50449. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50450. };
  50451. /**
  50452. * Transition property of the Camera to the target Value
  50453. * @param property The property to transition
  50454. * @param targetValue The target Value of the property
  50455. * @param host The object where the property to animate belongs
  50456. * @param scene Scene used to run the animation
  50457. * @param frameRate Framerate (in frame/s) to use
  50458. * @param transition The transition type we want to use
  50459. * @param duration The duration of the animation, in milliseconds
  50460. * @param onAnimationEnd Callback trigger at the end of the animation
  50461. * @returns Nullable animation
  50462. */
  50463. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50464. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50465. if (duration <= 0) {
  50466. host[property] = targetValue;
  50467. if (onAnimationEnd) {
  50468. onAnimationEnd();
  50469. }
  50470. return null;
  50471. }
  50472. var endFrame = frameRate * (duration / 1000);
  50473. transition.setKeys([{
  50474. frame: 0,
  50475. value: host[property].clone ? host[property].clone() : host[property]
  50476. },
  50477. {
  50478. frame: endFrame,
  50479. value: targetValue
  50480. }]);
  50481. if (!host.animations) {
  50482. host.animations = [];
  50483. }
  50484. host.animations.push(transition);
  50485. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50486. animation.onAnimationEnd = onAnimationEnd;
  50487. return animation;
  50488. };
  50489. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50490. /**
  50491. * Return the array of runtime animations currently using this animation
  50492. */
  50493. get: function () {
  50494. return this._runtimeAnimations;
  50495. },
  50496. enumerable: true,
  50497. configurable: true
  50498. });
  50499. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50500. /**
  50501. * Specifies if any of the runtime animations are currently running
  50502. */
  50503. get: function () {
  50504. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50505. var runtimeAnimation = _a[_i];
  50506. if (!runtimeAnimation.isStopped) {
  50507. return true;
  50508. }
  50509. }
  50510. return false;
  50511. },
  50512. enumerable: true,
  50513. configurable: true
  50514. });
  50515. // Methods
  50516. /**
  50517. * Converts the animation to a string
  50518. * @param fullDetails support for multiple levels of logging within scene loading
  50519. * @returns String form of the animation
  50520. */
  50521. Animation.prototype.toString = function (fullDetails) {
  50522. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50523. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50524. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50525. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50526. if (fullDetails) {
  50527. ret += ", Ranges: {";
  50528. var first = true;
  50529. for (var name in this._ranges) {
  50530. if (first) {
  50531. ret += ", ";
  50532. first = false;
  50533. }
  50534. ret += name;
  50535. }
  50536. ret += "}";
  50537. }
  50538. return ret;
  50539. };
  50540. /**
  50541. * Add an event to this animation
  50542. * @param event Event to add
  50543. */
  50544. Animation.prototype.addEvent = function (event) {
  50545. this._events.push(event);
  50546. };
  50547. /**
  50548. * Remove all events found at the given frame
  50549. * @param frame The frame to remove events from
  50550. */
  50551. Animation.prototype.removeEvents = function (frame) {
  50552. for (var index = 0; index < this._events.length; index++) {
  50553. if (this._events[index].frame === frame) {
  50554. this._events.splice(index, 1);
  50555. index--;
  50556. }
  50557. }
  50558. };
  50559. /**
  50560. * Retrieves all the events from the animation
  50561. * @returns Events from the animation
  50562. */
  50563. Animation.prototype.getEvents = function () {
  50564. return this._events;
  50565. };
  50566. /**
  50567. * Creates an animation range
  50568. * @param name Name of the animation range
  50569. * @param from Starting frame of the animation range
  50570. * @param to Ending frame of the animation
  50571. */
  50572. Animation.prototype.createRange = function (name, from, to) {
  50573. // check name not already in use; could happen for bones after serialized
  50574. if (!this._ranges[name]) {
  50575. this._ranges[name] = new AnimationRange(name, from, to);
  50576. }
  50577. };
  50578. /**
  50579. * Deletes an animation range by name
  50580. * @param name Name of the animation range to delete
  50581. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50582. */
  50583. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50584. if (deleteFrames === void 0) { deleteFrames = true; }
  50585. var range = this._ranges[name];
  50586. if (!range) {
  50587. return;
  50588. }
  50589. if (deleteFrames) {
  50590. var from = range.from;
  50591. var to = range.to;
  50592. // this loop MUST go high to low for multiple splices to work
  50593. for (var key = this._keys.length - 1; key >= 0; key--) {
  50594. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50595. this._keys.splice(key, 1);
  50596. }
  50597. }
  50598. }
  50599. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50600. };
  50601. /**
  50602. * Gets the animation range by name, or null if not defined
  50603. * @param name Name of the animation range
  50604. * @returns Nullable animation range
  50605. */
  50606. Animation.prototype.getRange = function (name) {
  50607. return this._ranges[name];
  50608. };
  50609. /**
  50610. * Gets the key frames from the animation
  50611. * @returns The key frames of the animation
  50612. */
  50613. Animation.prototype.getKeys = function () {
  50614. return this._keys;
  50615. };
  50616. /**
  50617. * Gets the highest frame rate of the animation
  50618. * @returns Highest frame rate of the animation
  50619. */
  50620. Animation.prototype.getHighestFrame = function () {
  50621. var ret = 0;
  50622. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50623. if (ret < this._keys[key].frame) {
  50624. ret = this._keys[key].frame;
  50625. }
  50626. }
  50627. return ret;
  50628. };
  50629. /**
  50630. * Gets the easing function of the animation
  50631. * @returns Easing function of the animation
  50632. */
  50633. Animation.prototype.getEasingFunction = function () {
  50634. return this._easingFunction;
  50635. };
  50636. /**
  50637. * Sets the easing function of the animation
  50638. * @param easingFunction A custom mathematical formula for animation
  50639. */
  50640. Animation.prototype.setEasingFunction = function (easingFunction) {
  50641. this._easingFunction = easingFunction;
  50642. };
  50643. /**
  50644. * Interpolates a scalar linearly
  50645. * @param startValue Start value of the animation curve
  50646. * @param endValue End value of the animation curve
  50647. * @param gradient Scalar amount to interpolate
  50648. * @returns Interpolated scalar value
  50649. */
  50650. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50651. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50652. };
  50653. /**
  50654. * Interpolates a scalar cubically
  50655. * @param startValue Start value of the animation curve
  50656. * @param outTangent End tangent of the animation
  50657. * @param endValue End value of the animation curve
  50658. * @param inTangent Start tangent of the animation curve
  50659. * @param gradient Scalar amount to interpolate
  50660. * @returns Interpolated scalar value
  50661. */
  50662. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50663. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50664. };
  50665. /**
  50666. * Interpolates a quaternion using a spherical linear interpolation
  50667. * @param startValue Start value of the animation curve
  50668. * @param endValue End value of the animation curve
  50669. * @param gradient Scalar amount to interpolate
  50670. * @returns Interpolated quaternion value
  50671. */
  50672. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50673. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50674. };
  50675. /**
  50676. * Interpolates a quaternion cubically
  50677. * @param startValue Start value of the animation curve
  50678. * @param outTangent End tangent of the animation curve
  50679. * @param endValue End value of the animation curve
  50680. * @param inTangent Start tangent of the animation curve
  50681. * @param gradient Scalar amount to interpolate
  50682. * @returns Interpolated quaternion value
  50683. */
  50684. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50685. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50686. };
  50687. /**
  50688. * Interpolates a Vector3 linearl
  50689. * @param startValue Start value of the animation curve
  50690. * @param endValue End value of the animation curve
  50691. * @param gradient Scalar amount to interpolate
  50692. * @returns Interpolated scalar value
  50693. */
  50694. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50695. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50696. };
  50697. /**
  50698. * Interpolates a Vector3 cubically
  50699. * @param startValue Start value of the animation curve
  50700. * @param outTangent End tangent of the animation
  50701. * @param endValue End value of the animation curve
  50702. * @param inTangent Start tangent of the animation curve
  50703. * @param gradient Scalar amount to interpolate
  50704. * @returns InterpolatedVector3 value
  50705. */
  50706. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50707. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50708. };
  50709. /**
  50710. * Interpolates a Vector2 linearly
  50711. * @param startValue Start value of the animation curve
  50712. * @param endValue End value of the animation curve
  50713. * @param gradient Scalar amount to interpolate
  50714. * @returns Interpolated Vector2 value
  50715. */
  50716. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50717. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50718. };
  50719. /**
  50720. * Interpolates a Vector2 cubically
  50721. * @param startValue Start value of the animation curve
  50722. * @param outTangent End tangent of the animation
  50723. * @param endValue End value of the animation curve
  50724. * @param inTangent Start tangent of the animation curve
  50725. * @param gradient Scalar amount to interpolate
  50726. * @returns Interpolated Vector2 value
  50727. */
  50728. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50729. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50730. };
  50731. /**
  50732. * Interpolates a size linearly
  50733. * @param startValue Start value of the animation curve
  50734. * @param endValue End value of the animation curve
  50735. * @param gradient Scalar amount to interpolate
  50736. * @returns Interpolated Size value
  50737. */
  50738. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50739. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50740. };
  50741. /**
  50742. * Interpolates a Color3 linearly
  50743. * @param startValue Start value of the animation curve
  50744. * @param endValue End value of the animation curve
  50745. * @param gradient Scalar amount to interpolate
  50746. * @returns Interpolated Color3 value
  50747. */
  50748. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50749. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50750. };
  50751. /**
  50752. * @hidden Internal use only
  50753. */
  50754. Animation.prototype._getKeyValue = function (value) {
  50755. if (typeof value === "function") {
  50756. return value();
  50757. }
  50758. return value;
  50759. };
  50760. /**
  50761. * @hidden Internal use only
  50762. */
  50763. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50764. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50765. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50766. }
  50767. var keys = this.getKeys();
  50768. // Try to get a hash to find the right key
  50769. 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));
  50770. if (keys[startKeyIndex].frame >= currentFrame) {
  50771. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50772. startKeyIndex--;
  50773. }
  50774. }
  50775. for (var key = startKeyIndex; key < keys.length; key++) {
  50776. var endKey = keys[key + 1];
  50777. if (endKey.frame >= currentFrame) {
  50778. var startKey = keys[key];
  50779. var startValue = this._getKeyValue(startKey.value);
  50780. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50781. return startValue;
  50782. }
  50783. var endValue = this._getKeyValue(endKey.value);
  50784. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50785. var frameDelta = endKey.frame - startKey.frame;
  50786. // gradient : percent of currentFrame between the frame inf and the frame sup
  50787. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50788. // check for easingFunction and correction of gradient
  50789. var easingFunction = this.getEasingFunction();
  50790. if (easingFunction != null) {
  50791. gradient = easingFunction.ease(gradient);
  50792. }
  50793. switch (this.dataType) {
  50794. // Float
  50795. case Animation.ANIMATIONTYPE_FLOAT:
  50796. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50797. switch (loopMode) {
  50798. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50799. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50800. return floatValue;
  50801. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50802. return offsetValue * repeatCount + floatValue;
  50803. }
  50804. break;
  50805. // Quaternion
  50806. case Animation.ANIMATIONTYPE_QUATERNION:
  50807. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50808. switch (loopMode) {
  50809. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50810. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50811. return quatValue;
  50812. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50813. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50814. }
  50815. return quatValue;
  50816. // Vector3
  50817. case Animation.ANIMATIONTYPE_VECTOR3:
  50818. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50819. switch (loopMode) {
  50820. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50821. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50822. return vec3Value;
  50823. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50824. return vec3Value.add(offsetValue.scale(repeatCount));
  50825. }
  50826. // Vector2
  50827. case Animation.ANIMATIONTYPE_VECTOR2:
  50828. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50829. switch (loopMode) {
  50830. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50831. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50832. return vec2Value;
  50833. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50834. return vec2Value.add(offsetValue.scale(repeatCount));
  50835. }
  50836. // Size
  50837. case Animation.ANIMATIONTYPE_SIZE:
  50838. switch (loopMode) {
  50839. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50840. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50841. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50842. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50843. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50844. }
  50845. // Color3
  50846. case Animation.ANIMATIONTYPE_COLOR3:
  50847. switch (loopMode) {
  50848. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50849. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50850. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50851. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50852. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50853. }
  50854. // Matrix
  50855. case Animation.ANIMATIONTYPE_MATRIX:
  50856. switch (loopMode) {
  50857. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50858. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50859. if (Animation.AllowMatricesInterpolation) {
  50860. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50861. }
  50862. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50863. return startValue;
  50864. }
  50865. default:
  50866. break;
  50867. }
  50868. break;
  50869. }
  50870. }
  50871. return this._getKeyValue(keys[keys.length - 1].value);
  50872. };
  50873. /**
  50874. * Defines the function to use to interpolate matrices
  50875. * @param startValue defines the start matrix
  50876. * @param endValue defines the end matrix
  50877. * @param gradient defines the gradient between both matrices
  50878. * @param result defines an optional target matrix where to store the interpolation
  50879. * @returns the interpolated matrix
  50880. */
  50881. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50882. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50883. if (result) {
  50884. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50885. return result;
  50886. }
  50887. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50888. }
  50889. if (result) {
  50890. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50891. return result;
  50892. }
  50893. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50894. };
  50895. /**
  50896. * Makes a copy of the animation
  50897. * @returns Cloned animation
  50898. */
  50899. Animation.prototype.clone = function () {
  50900. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50901. clone.enableBlending = this.enableBlending;
  50902. clone.blendingSpeed = this.blendingSpeed;
  50903. if (this._keys) {
  50904. clone.setKeys(this._keys);
  50905. }
  50906. if (this._ranges) {
  50907. clone._ranges = {};
  50908. for (var name in this._ranges) {
  50909. var range = this._ranges[name];
  50910. if (!range) {
  50911. continue;
  50912. }
  50913. clone._ranges[name] = range.clone();
  50914. }
  50915. }
  50916. return clone;
  50917. };
  50918. /**
  50919. * Sets the key frames of the animation
  50920. * @param values The animation key frames to set
  50921. */
  50922. Animation.prototype.setKeys = function (values) {
  50923. this._keys = values.slice(0);
  50924. };
  50925. /**
  50926. * Serializes the animation to an object
  50927. * @returns Serialized object
  50928. */
  50929. Animation.prototype.serialize = function () {
  50930. var serializationObject = {};
  50931. serializationObject.name = this.name;
  50932. serializationObject.property = this.targetProperty;
  50933. serializationObject.framePerSecond = this.framePerSecond;
  50934. serializationObject.dataType = this.dataType;
  50935. serializationObject.loopBehavior = this.loopMode;
  50936. serializationObject.enableBlending = this.enableBlending;
  50937. serializationObject.blendingSpeed = this.blendingSpeed;
  50938. var dataType = this.dataType;
  50939. serializationObject.keys = [];
  50940. var keys = this.getKeys();
  50941. for (var index = 0; index < keys.length; index++) {
  50942. var animationKey = keys[index];
  50943. var key = {};
  50944. key.frame = animationKey.frame;
  50945. switch (dataType) {
  50946. case Animation.ANIMATIONTYPE_FLOAT:
  50947. key.values = [animationKey.value];
  50948. break;
  50949. case Animation.ANIMATIONTYPE_QUATERNION:
  50950. case Animation.ANIMATIONTYPE_MATRIX:
  50951. case Animation.ANIMATIONTYPE_VECTOR3:
  50952. case Animation.ANIMATIONTYPE_COLOR3:
  50953. key.values = animationKey.value.asArray();
  50954. break;
  50955. }
  50956. serializationObject.keys.push(key);
  50957. }
  50958. serializationObject.ranges = [];
  50959. for (var name in this._ranges) {
  50960. var source = this._ranges[name];
  50961. if (!source) {
  50962. continue;
  50963. }
  50964. var range = {};
  50965. range.name = name;
  50966. range.from = source.from;
  50967. range.to = source.to;
  50968. serializationObject.ranges.push(range);
  50969. }
  50970. return serializationObject;
  50971. };
  50972. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50973. /**
  50974. * Get the float animation type
  50975. */
  50976. get: function () {
  50977. return Animation._ANIMATIONTYPE_FLOAT;
  50978. },
  50979. enumerable: true,
  50980. configurable: true
  50981. });
  50982. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50983. /**
  50984. * Get the Vector3 animation type
  50985. */
  50986. get: function () {
  50987. return Animation._ANIMATIONTYPE_VECTOR3;
  50988. },
  50989. enumerable: true,
  50990. configurable: true
  50991. });
  50992. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50993. /**
  50994. * Get the Vectpr2 animation type
  50995. */
  50996. get: function () {
  50997. return Animation._ANIMATIONTYPE_VECTOR2;
  50998. },
  50999. enumerable: true,
  51000. configurable: true
  51001. });
  51002. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51003. /**
  51004. * Get the Size animation type
  51005. */
  51006. get: function () {
  51007. return Animation._ANIMATIONTYPE_SIZE;
  51008. },
  51009. enumerable: true,
  51010. configurable: true
  51011. });
  51012. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51013. /**
  51014. * Get the Quaternion animation type
  51015. */
  51016. get: function () {
  51017. return Animation._ANIMATIONTYPE_QUATERNION;
  51018. },
  51019. enumerable: true,
  51020. configurable: true
  51021. });
  51022. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51023. /**
  51024. * Get the Matrix animation type
  51025. */
  51026. get: function () {
  51027. return Animation._ANIMATIONTYPE_MATRIX;
  51028. },
  51029. enumerable: true,
  51030. configurable: true
  51031. });
  51032. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51033. /**
  51034. * Get the Color3 animation type
  51035. */
  51036. get: function () {
  51037. return Animation._ANIMATIONTYPE_COLOR3;
  51038. },
  51039. enumerable: true,
  51040. configurable: true
  51041. });
  51042. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51043. /**
  51044. * Get the Relative Loop Mode
  51045. */
  51046. get: function () {
  51047. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51048. },
  51049. enumerable: true,
  51050. configurable: true
  51051. });
  51052. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51053. /**
  51054. * Get the Cycle Loop Mode
  51055. */
  51056. get: function () {
  51057. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51058. },
  51059. enumerable: true,
  51060. configurable: true
  51061. });
  51062. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51063. /**
  51064. * Get the Constant Loop Mode
  51065. */
  51066. get: function () {
  51067. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51068. },
  51069. enumerable: true,
  51070. configurable: true
  51071. });
  51072. /**
  51073. * Parses an animation object and creates an animation
  51074. * @param parsedAnimation Parsed animation object
  51075. * @returns Animation object
  51076. */
  51077. Animation.Parse = function (parsedAnimation) {
  51078. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51079. var dataType = parsedAnimation.dataType;
  51080. var keys = [];
  51081. var data;
  51082. var index;
  51083. if (parsedAnimation.enableBlending) {
  51084. animation.enableBlending = parsedAnimation.enableBlending;
  51085. }
  51086. if (parsedAnimation.blendingSpeed) {
  51087. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51088. }
  51089. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51090. var key = parsedAnimation.keys[index];
  51091. var inTangent;
  51092. var outTangent;
  51093. switch (dataType) {
  51094. case Animation.ANIMATIONTYPE_FLOAT:
  51095. data = key.values[0];
  51096. if (key.values.length >= 1) {
  51097. inTangent = key.values[1];
  51098. }
  51099. if (key.values.length >= 2) {
  51100. outTangent = key.values[2];
  51101. }
  51102. break;
  51103. case Animation.ANIMATIONTYPE_QUATERNION:
  51104. data = BABYLON.Quaternion.FromArray(key.values);
  51105. if (key.values.length >= 8) {
  51106. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51107. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51108. inTangent = _inTangent;
  51109. }
  51110. }
  51111. if (key.values.length >= 12) {
  51112. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51113. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51114. outTangent = _outTangent;
  51115. }
  51116. }
  51117. break;
  51118. case Animation.ANIMATIONTYPE_MATRIX:
  51119. data = BABYLON.Matrix.FromArray(key.values);
  51120. break;
  51121. case Animation.ANIMATIONTYPE_COLOR3:
  51122. data = BABYLON.Color3.FromArray(key.values);
  51123. break;
  51124. case Animation.ANIMATIONTYPE_VECTOR3:
  51125. default:
  51126. data = BABYLON.Vector3.FromArray(key.values);
  51127. break;
  51128. }
  51129. var keyData = {};
  51130. keyData.frame = key.frame;
  51131. keyData.value = data;
  51132. if (inTangent != undefined) {
  51133. keyData.inTangent = inTangent;
  51134. }
  51135. if (outTangent != undefined) {
  51136. keyData.outTangent = outTangent;
  51137. }
  51138. keys.push(keyData);
  51139. }
  51140. animation.setKeys(keys);
  51141. if (parsedAnimation.ranges) {
  51142. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51143. data = parsedAnimation.ranges[index];
  51144. animation.createRange(data.name, data.from, data.to);
  51145. }
  51146. }
  51147. return animation;
  51148. };
  51149. /**
  51150. * Appends the serialized animations from the source animations
  51151. * @param source Source containing the animations
  51152. * @param destination Target to store the animations
  51153. */
  51154. Animation.AppendSerializedAnimations = function (source, destination) {
  51155. if (source.animations) {
  51156. destination.animations = [];
  51157. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51158. var animation = source.animations[animationIndex];
  51159. destination.animations.push(animation.serialize());
  51160. }
  51161. }
  51162. };
  51163. /**
  51164. * Use matrix interpolation instead of using direct key value when animating matrices
  51165. */
  51166. Animation.AllowMatricesInterpolation = false;
  51167. /**
  51168. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51169. */
  51170. Animation.AllowMatrixDecomposeForInterpolation = true;
  51171. // Statics
  51172. /**
  51173. * Float animation type
  51174. */
  51175. Animation._ANIMATIONTYPE_FLOAT = 0;
  51176. /**
  51177. * Vector3 animation type
  51178. */
  51179. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51180. /**
  51181. * Quaternion animation type
  51182. */
  51183. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51184. /**
  51185. * Matrix animation type
  51186. */
  51187. Animation._ANIMATIONTYPE_MATRIX = 3;
  51188. /**
  51189. * Color3 animation type
  51190. */
  51191. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51192. /**
  51193. * Vector2 animation type
  51194. */
  51195. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51196. /**
  51197. * Size animation type
  51198. */
  51199. Animation._ANIMATIONTYPE_SIZE = 6;
  51200. /**
  51201. * Relative Loop Mode
  51202. */
  51203. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51204. /**
  51205. * Cycle Loop Mode
  51206. */
  51207. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51208. /**
  51209. * Constant Loop Mode
  51210. */
  51211. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51212. return Animation;
  51213. }());
  51214. BABYLON.Animation = Animation;
  51215. })(BABYLON || (BABYLON = {}));
  51216. //# sourceMappingURL=babylon.animation.js.map
  51217. var BABYLON;
  51218. (function (BABYLON) {
  51219. /**
  51220. * This class defines the direct association between an animation and a target
  51221. */
  51222. var TargetedAnimation = /** @class */ (function () {
  51223. function TargetedAnimation() {
  51224. }
  51225. return TargetedAnimation;
  51226. }());
  51227. BABYLON.TargetedAnimation = TargetedAnimation;
  51228. /**
  51229. * Use this class to create coordinated animations on multiple targets
  51230. */
  51231. var AnimationGroup = /** @class */ (function () {
  51232. function AnimationGroup(name, scene) {
  51233. if (scene === void 0) { scene = null; }
  51234. this.name = name;
  51235. this._targetedAnimations = new Array();
  51236. this._animatables = new Array();
  51237. this._from = Number.MAX_VALUE;
  51238. this._to = -Number.MAX_VALUE;
  51239. this._speedRatio = 1;
  51240. this.onAnimationEndObservable = new BABYLON.Observable();
  51241. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51242. this._scene.animationGroups.push(this);
  51243. }
  51244. Object.defineProperty(AnimationGroup.prototype, "from", {
  51245. /**
  51246. * Gets the first frame
  51247. */
  51248. get: function () {
  51249. return this._from;
  51250. },
  51251. enumerable: true,
  51252. configurable: true
  51253. });
  51254. Object.defineProperty(AnimationGroup.prototype, "to", {
  51255. /**
  51256. * Gets the last frame
  51257. */
  51258. get: function () {
  51259. return this._to;
  51260. },
  51261. enumerable: true,
  51262. configurable: true
  51263. });
  51264. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51265. /**
  51266. * Define if the animations are started
  51267. */
  51268. get: function () {
  51269. return this._isStarted;
  51270. },
  51271. enumerable: true,
  51272. configurable: true
  51273. });
  51274. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51275. /**
  51276. * Gets or sets the speed ratio to use for all animations
  51277. */
  51278. get: function () {
  51279. return this._speedRatio;
  51280. },
  51281. /**
  51282. * Gets or sets the speed ratio to use for all animations
  51283. */
  51284. set: function (value) {
  51285. if (this._speedRatio === value) {
  51286. return;
  51287. }
  51288. this._speedRatio = value;
  51289. for (var index = 0; index < this._animatables.length; index++) {
  51290. var animatable = this._animatables[index];
  51291. animatable.speedRatio = this._speedRatio;
  51292. }
  51293. },
  51294. enumerable: true,
  51295. configurable: true
  51296. });
  51297. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51298. /**
  51299. * Gets the targeted animations for this animation group
  51300. */
  51301. get: function () {
  51302. return this._targetedAnimations;
  51303. },
  51304. enumerable: true,
  51305. configurable: true
  51306. });
  51307. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51308. /**
  51309. * returning the list of animatables controlled by this animation group.
  51310. */
  51311. get: function () {
  51312. return this._animatables;
  51313. },
  51314. enumerable: true,
  51315. configurable: true
  51316. });
  51317. /**
  51318. * Add an animation (with its target) in the group
  51319. * @param animation defines the animation we want to add
  51320. * @param target defines the target of the animation
  51321. * @returns the {BABYLON.TargetedAnimation} object
  51322. */
  51323. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51324. var targetedAnimation = {
  51325. animation: animation,
  51326. target: target
  51327. };
  51328. var keys = animation.getKeys();
  51329. if (this._from > keys[0].frame) {
  51330. this._from = keys[0].frame;
  51331. }
  51332. if (this._to < keys[keys.length - 1].frame) {
  51333. this._to = keys[keys.length - 1].frame;
  51334. }
  51335. this._targetedAnimations.push(targetedAnimation);
  51336. return targetedAnimation;
  51337. };
  51338. /**
  51339. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51340. * It can add constant keys at begin or end
  51341. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  51342. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  51343. */
  51344. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51345. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  51346. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  51347. beginFrame = Math.max(beginFrame, this._from);
  51348. endFrame = Math.min(endFrame, this._to);
  51349. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51350. var targetedAnimation = this._targetedAnimations[index];
  51351. var keys = targetedAnimation.animation.getKeys();
  51352. var startKey = keys[0];
  51353. var endKey = keys[keys.length - 1];
  51354. if (startKey.frame > beginFrame) {
  51355. var newKey = {
  51356. frame: beginFrame,
  51357. value: startKey.value,
  51358. inTangent: startKey.inTangent,
  51359. outTangent: startKey.outTangent,
  51360. interpolation: startKey.interpolation
  51361. };
  51362. keys.splice(0, 0, newKey);
  51363. }
  51364. if (endKey.frame < endFrame) {
  51365. var newKey = {
  51366. frame: endFrame,
  51367. value: endKey.value,
  51368. inTangent: endKey.outTangent,
  51369. outTangent: endKey.outTangent,
  51370. interpolation: endKey.interpolation
  51371. };
  51372. keys.push(newKey);
  51373. }
  51374. }
  51375. return this;
  51376. };
  51377. /**
  51378. * Start all animations on given targets
  51379. * @param loop defines if animations must loop
  51380. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51381. * @param from defines the from key (optional)
  51382. * @param to defines the to key (optional)
  51383. * @returns the current animation group
  51384. */
  51385. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51386. var _this = this;
  51387. if (loop === void 0) { loop = false; }
  51388. if (speedRatio === void 0) { speedRatio = 1; }
  51389. if (this._isStarted || this._targetedAnimations.length === 0) {
  51390. return this;
  51391. }
  51392. var _loop_1 = function (targetedAnimation) {
  51393. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio, function () {
  51394. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51395. }));
  51396. };
  51397. var this_1 = this;
  51398. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51399. var targetedAnimation = _a[_i];
  51400. _loop_1(targetedAnimation);
  51401. }
  51402. this._speedRatio = speedRatio;
  51403. this._isStarted = true;
  51404. return this;
  51405. };
  51406. /**
  51407. * Pause all animations
  51408. */
  51409. AnimationGroup.prototype.pause = function () {
  51410. if (!this._isStarted) {
  51411. return this;
  51412. }
  51413. for (var index = 0; index < this._animatables.length; index++) {
  51414. var animatable = this._animatables[index];
  51415. animatable.pause();
  51416. }
  51417. return this;
  51418. };
  51419. /**
  51420. * Play all animations to initial state
  51421. * This function will start() the animations if they were not started or will restart() them if they were paused
  51422. * @param loop defines if animations must loop
  51423. */
  51424. AnimationGroup.prototype.play = function (loop) {
  51425. if (this.isStarted) {
  51426. if (loop !== undefined) {
  51427. for (var index = 0; index < this._animatables.length; index++) {
  51428. var animatable = this._animatables[index];
  51429. animatable.loopAnimation = loop;
  51430. }
  51431. }
  51432. this.restart();
  51433. }
  51434. else {
  51435. this.start(loop, this._speedRatio);
  51436. }
  51437. return this;
  51438. };
  51439. /**
  51440. * Reset all animations to initial state
  51441. */
  51442. AnimationGroup.prototype.reset = function () {
  51443. if (!this._isStarted) {
  51444. return this;
  51445. }
  51446. for (var index = 0; index < this._animatables.length; index++) {
  51447. var animatable = this._animatables[index];
  51448. animatable.reset();
  51449. }
  51450. return this;
  51451. };
  51452. /**
  51453. * Restart animations from key 0
  51454. */
  51455. AnimationGroup.prototype.restart = function () {
  51456. if (!this._isStarted) {
  51457. return this;
  51458. }
  51459. for (var index = 0; index < this._animatables.length; index++) {
  51460. var animatable = this._animatables[index];
  51461. animatable.restart();
  51462. }
  51463. return this;
  51464. };
  51465. /**
  51466. * Stop all animations
  51467. */
  51468. AnimationGroup.prototype.stop = function () {
  51469. if (!this._isStarted) {
  51470. return this;
  51471. }
  51472. for (var index = 0; index < this._animatables.length; index++) {
  51473. var animatable = this._animatables[index];
  51474. animatable.stop();
  51475. }
  51476. this._isStarted = false;
  51477. return this;
  51478. };
  51479. /**
  51480. * Set animation weight for all animatables
  51481. * @param weight defines the weight to use
  51482. * @return the animationGroup
  51483. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51484. */
  51485. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51486. for (var index = 0; index < this._animatables.length; index++) {
  51487. var animatable = this._animatables[index];
  51488. animatable.weight = weight;
  51489. }
  51490. return this;
  51491. };
  51492. /**
  51493. * Synchronize and normalize all animatables with a source animatable
  51494. * @param root defines the root animatable to synchronize with
  51495. * @return the animationGroup
  51496. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51497. */
  51498. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51499. for (var index = 0; index < this._animatables.length; index++) {
  51500. var animatable = this._animatables[index];
  51501. animatable.syncWith(root);
  51502. }
  51503. return this;
  51504. };
  51505. /**
  51506. * Goes to a specific frame in this animation group
  51507. * @param frame the frame number to go to
  51508. * @return the animationGroup
  51509. */
  51510. AnimationGroup.prototype.goToFrame = function (frame) {
  51511. if (!this._isStarted) {
  51512. return this;
  51513. }
  51514. for (var index = 0; index < this._animatables.length; index++) {
  51515. var animatable = this._animatables[index];
  51516. animatable.goToFrame(frame);
  51517. }
  51518. return this;
  51519. };
  51520. /**
  51521. * Dispose all associated resources
  51522. */
  51523. AnimationGroup.prototype.dispose = function () {
  51524. this._targetedAnimations = [];
  51525. this._animatables = [];
  51526. var index = this._scene.animationGroups.indexOf(this);
  51527. if (index > -1) {
  51528. this._scene.animationGroups.splice(index, 1);
  51529. }
  51530. };
  51531. return AnimationGroup;
  51532. }());
  51533. BABYLON.AnimationGroup = AnimationGroup;
  51534. })(BABYLON || (BABYLON = {}));
  51535. //# sourceMappingURL=babylon.animationGroup.js.map
  51536. var BABYLON;
  51537. (function (BABYLON) {
  51538. /**
  51539. * Defines a runtime animation
  51540. */
  51541. var RuntimeAnimation = /** @class */ (function () {
  51542. /**
  51543. * Create a new RuntimeAnimation object
  51544. * @param target defines the target of the animation
  51545. * @param animation defines the source animation object
  51546. * @param scene defines the hosting scene
  51547. * @param host defines the initiating Animatable
  51548. */
  51549. function RuntimeAnimation(target, animation, scene, host) {
  51550. /**
  51551. * The current frame of the runtime animation
  51552. */
  51553. this._currentFrame = 0;
  51554. /**
  51555. * The offsets cache of the runtime animation
  51556. */
  51557. this._offsetsCache = {};
  51558. /**
  51559. * The high limits cache of the runtime animation
  51560. */
  51561. this._highLimitsCache = {};
  51562. /**
  51563. * Specifies if the runtime animation has been stopped
  51564. */
  51565. this._stopped = false;
  51566. /**
  51567. * The blending factor of the runtime animation
  51568. */
  51569. this._blendingFactor = 0;
  51570. /**
  51571. * The target path of the runtime animation
  51572. */
  51573. this._targetPath = "";
  51574. /**
  51575. * The weight of the runtime animation
  51576. */
  51577. this._weight = 1.0;
  51578. /**
  51579. * The ratio offset of the runtime animation
  51580. */
  51581. this._ratioOffset = 0;
  51582. /**
  51583. * The previous delay of the runtime animation
  51584. */
  51585. this._previousDelay = 0;
  51586. /**
  51587. * The previous ratio of the runtime animation
  51588. */
  51589. this._previousRatio = 0;
  51590. this._animation = animation;
  51591. this._target = target;
  51592. this._scene = scene;
  51593. this._host = host;
  51594. animation._runtimeAnimations.push(this);
  51595. }
  51596. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51597. /**
  51598. * Gets the current frame of the runtime animation
  51599. */
  51600. get: function () {
  51601. return this._currentFrame;
  51602. },
  51603. enumerable: true,
  51604. configurable: true
  51605. });
  51606. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51607. /**
  51608. * Gets the weight of the runtime animation
  51609. */
  51610. get: function () {
  51611. return this._weight;
  51612. },
  51613. enumerable: true,
  51614. configurable: true
  51615. });
  51616. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  51617. /**
  51618. * Gets the original value of the runtime animation
  51619. */
  51620. get: function () {
  51621. return this._originalValue;
  51622. },
  51623. enumerable: true,
  51624. configurable: true
  51625. });
  51626. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51627. /**
  51628. * Gets the current value of the runtime animation
  51629. */
  51630. get: function () {
  51631. return this._currentValue;
  51632. },
  51633. enumerable: true,
  51634. configurable: true
  51635. });
  51636. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51637. /**
  51638. * Gets the target path of the runtime animation
  51639. */
  51640. get: function () {
  51641. return this._targetPath;
  51642. },
  51643. enumerable: true,
  51644. configurable: true
  51645. });
  51646. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51647. /**
  51648. * Gets the actual target of the runtime animation
  51649. */
  51650. get: function () {
  51651. return this._activeTarget;
  51652. },
  51653. enumerable: true,
  51654. configurable: true
  51655. });
  51656. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51657. /**
  51658. * Gets the animation from the runtime animation
  51659. */
  51660. get: function () {
  51661. return this._animation;
  51662. },
  51663. enumerable: true,
  51664. configurable: true
  51665. });
  51666. /**
  51667. * Resets the runtime animation to the beginning
  51668. */
  51669. RuntimeAnimation.prototype.reset = function () {
  51670. this._offsetsCache = {};
  51671. this._highLimitsCache = {};
  51672. this._currentFrame = 0;
  51673. this._blendingFactor = 0;
  51674. this._originalValue = null;
  51675. };
  51676. /**
  51677. * Specifies if the runtime animation is stopped
  51678. * @returns Boolean specifying if the runtime animation is stopped
  51679. */
  51680. RuntimeAnimation.prototype.isStopped = function () {
  51681. return this._stopped;
  51682. };
  51683. /**
  51684. * Disposes of the runtime animation
  51685. */
  51686. RuntimeAnimation.prototype.dispose = function () {
  51687. var index = this._animation.runtimeAnimations.indexOf(this);
  51688. if (index > -1) {
  51689. this._animation.runtimeAnimations.splice(index, 1);
  51690. }
  51691. };
  51692. /**
  51693. * Interpolates the animation from the current frame
  51694. * @param currentFrame The frame to interpolate the animation to
  51695. * @param repeatCount The number of times that the animation should loop
  51696. * @param loopMode The type of looping mode to use
  51697. * @param offsetValue Animation offset value
  51698. * @param highLimitValue The high limit value
  51699. * @returns The interpolated value
  51700. */
  51701. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51702. this._currentFrame = currentFrame;
  51703. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51704. this._workValue = BABYLON.Matrix.Zero();
  51705. }
  51706. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51707. };
  51708. /**
  51709. * Affect the interpolated value to the target
  51710. * @param currentValue defines the value computed by the animation
  51711. * @param weight defines the weight to apply to this value
  51712. */
  51713. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51714. if (weight === void 0) { weight = 1.0; }
  51715. if (this._target instanceof Array) {
  51716. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51717. var target = _a[_i];
  51718. this._setValue(target, currentValue, weight);
  51719. }
  51720. }
  51721. else {
  51722. this._setValue(this._target, currentValue, weight);
  51723. }
  51724. };
  51725. /**
  51726. * Sets the value of the runtime animation
  51727. * @param target The target property of the runtime animation
  51728. * @param currentValue The current value to use for the runtime animation
  51729. * @param weight The weight to use for the runtime animation (Defaults to 1.0)
  51730. */
  51731. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight) {
  51732. if (weight === void 0) { weight = 1.0; }
  51733. // Set value
  51734. var path;
  51735. var destination;
  51736. var targetPropertyPath = this._animation.targetPropertyPath;
  51737. if (targetPropertyPath.length > 1) {
  51738. var property = target[targetPropertyPath[0]];
  51739. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51740. property = property[targetPropertyPath[index]];
  51741. }
  51742. path = targetPropertyPath[targetPropertyPath.length - 1];
  51743. destination = property;
  51744. }
  51745. else {
  51746. path = targetPropertyPath[0];
  51747. destination = target;
  51748. }
  51749. this._targetPath = path;
  51750. this._activeTarget = destination;
  51751. this._weight = weight;
  51752. // Blending
  51753. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51754. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51755. if (enableBlending && this._blendingFactor <= 1.0) {
  51756. if (!this._originalBlendValue) {
  51757. var originalValue = destination[path];
  51758. if (originalValue.clone) {
  51759. this._originalBlendValue = originalValue.clone();
  51760. }
  51761. else {
  51762. this._originalBlendValue = originalValue;
  51763. }
  51764. }
  51765. }
  51766. if (weight !== -1.0) {
  51767. if (!this._originalValue) {
  51768. var originalValue = void 0;
  51769. if (destination.getRestPose && path === "_matrix") { // For bones
  51770. originalValue = destination.getRestPose();
  51771. }
  51772. else {
  51773. originalValue = destination[path];
  51774. }
  51775. if (originalValue.clone) {
  51776. this._originalValue = originalValue.clone();
  51777. }
  51778. else {
  51779. this._originalValue = originalValue;
  51780. }
  51781. }
  51782. }
  51783. if (enableBlending && this._blendingFactor <= 1.0) {
  51784. if (this._originalBlendValue.m) { // Matrix
  51785. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51786. if (this._currentValue) {
  51787. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51788. }
  51789. else {
  51790. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51791. }
  51792. }
  51793. else {
  51794. if (this._currentValue) {
  51795. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51796. }
  51797. else {
  51798. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51799. }
  51800. }
  51801. }
  51802. else {
  51803. var constructor = this._originalBlendValue.constructor;
  51804. if (constructor.Lerp) { // Lerp supported
  51805. this._currentValue = constructor.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51806. }
  51807. else if (constructor.Slerp) { // Slerp supported
  51808. this._currentValue = constructor.Slerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51809. }
  51810. else if (this._originalBlendValue.toFixed) { // Number
  51811. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  51812. }
  51813. else { // Blending not supported
  51814. this._currentValue = currentValue;
  51815. }
  51816. }
  51817. this._blendingFactor += blendingSpeed;
  51818. }
  51819. else {
  51820. this._currentValue = currentValue;
  51821. }
  51822. if (weight !== -1.0) {
  51823. this._scene._registerTargetForLateAnimationBinding(this);
  51824. }
  51825. else {
  51826. destination[path] = this._currentValue;
  51827. }
  51828. if (target.markAsDirty) {
  51829. target.markAsDirty(this._animation.targetProperty);
  51830. }
  51831. };
  51832. /**
  51833. * Gets the loop pmode of the runtime animation
  51834. * @returns Loop Mode
  51835. */
  51836. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51837. if (this._target && this._target.animationPropertiesOverride) {
  51838. return this._target.animationPropertiesOverride.loopMode;
  51839. }
  51840. return this._animation.loopMode;
  51841. };
  51842. /**
  51843. * Move the current animation to a given frame
  51844. * @param frame defines the frame to move to
  51845. */
  51846. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51847. var keys = this._animation.getKeys();
  51848. if (frame < keys[0].frame) {
  51849. frame = keys[0].frame;
  51850. }
  51851. else if (frame > keys[keys.length - 1].frame) {
  51852. frame = keys[keys.length - 1].frame;
  51853. }
  51854. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51855. this.setValue(currentValue, -1);
  51856. };
  51857. /**
  51858. * @hidden Internal use only
  51859. */
  51860. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51861. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51862. this._ratioOffset = this._previousRatio - newRatio;
  51863. };
  51864. /**
  51865. * Execute the current animation
  51866. * @param delay defines the delay to add to the current frame
  51867. * @param from defines the lower bound of the animation range
  51868. * @param to defines the upper bound of the animation range
  51869. * @param loop defines if the current animation must loop
  51870. * @param speedRatio defines the current speed ratio
  51871. * @param weight defines the weight of the animation (default is -1 so no weight)
  51872. * @returns a boolean indicating if the animation has ended
  51873. */
  51874. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51875. if (weight === void 0) { weight = -1.0; }
  51876. var targetPropertyPath = this._animation.targetPropertyPath;
  51877. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51878. this._stopped = true;
  51879. return false;
  51880. }
  51881. var returnValue = true;
  51882. var keys = this._animation.getKeys();
  51883. // Adding a start key at frame 0 if missing
  51884. if (keys[0].frame !== 0) {
  51885. var newKey = { frame: 0, value: keys[0].value };
  51886. keys.splice(0, 0, newKey);
  51887. }
  51888. // Check limits
  51889. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51890. from = keys[0].frame;
  51891. }
  51892. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51893. to = keys[keys.length - 1].frame;
  51894. }
  51895. //to and from cannot be the same key
  51896. if (from === to) {
  51897. if (from > keys[0].frame) {
  51898. from--;
  51899. }
  51900. else if (to < keys[keys.length - 1].frame) {
  51901. to++;
  51902. }
  51903. }
  51904. // Compute ratio
  51905. var range = to - from;
  51906. var offsetValue;
  51907. // ratio represents the frame delta between from and to
  51908. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51909. var highLimitValue = 0;
  51910. this._previousDelay = delay;
  51911. this._previousRatio = ratio;
  51912. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) { // If we are out of range and not looping get back to caller
  51913. returnValue = false;
  51914. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51915. }
  51916. else {
  51917. // Get max value if required
  51918. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51919. var keyOffset = to.toString() + from.toString();
  51920. if (!this._offsetsCache[keyOffset]) {
  51921. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51922. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51923. switch (this._animation.dataType) {
  51924. // Float
  51925. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51926. this._offsetsCache[keyOffset] = toValue - fromValue;
  51927. break;
  51928. // Quaternion
  51929. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51930. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51931. break;
  51932. // Vector3
  51933. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51934. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51935. // Vector2
  51936. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51937. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51938. // Size
  51939. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51940. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51941. // Color3
  51942. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51943. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51944. default:
  51945. break;
  51946. }
  51947. this._highLimitsCache[keyOffset] = toValue;
  51948. }
  51949. highLimitValue = this._highLimitsCache[keyOffset];
  51950. offsetValue = this._offsetsCache[keyOffset];
  51951. }
  51952. }
  51953. if (offsetValue === undefined) {
  51954. switch (this._animation.dataType) {
  51955. // Float
  51956. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51957. offsetValue = 0;
  51958. break;
  51959. // Quaternion
  51960. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51961. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51962. break;
  51963. // Vector3
  51964. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51965. offsetValue = BABYLON.Vector3.Zero();
  51966. break;
  51967. // Vector2
  51968. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51969. offsetValue = BABYLON.Vector2.Zero();
  51970. break;
  51971. // Size
  51972. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51973. offsetValue = BABYLON.Size.Zero();
  51974. break;
  51975. // Color3
  51976. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51977. offsetValue = BABYLON.Color3.Black();
  51978. }
  51979. }
  51980. // Compute value
  51981. var repeatCount = (ratio / range) >> 0;
  51982. var currentFrame = returnValue ? from + ratio % range : to;
  51983. // Need to normalize?
  51984. if (this._host && this._host.syncRoot) {
  51985. var syncRoot = this._host.syncRoot;
  51986. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51987. currentFrame = from + (to - from) * hostNormalizedFrame;
  51988. }
  51989. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51990. // Set value
  51991. this.setValue(currentValue, weight);
  51992. // Check events
  51993. var events = this._animation.getEvents();
  51994. for (var index = 0; index < events.length; index++) {
  51995. // Make sure current frame has passed event frame and that event frame is within the current range
  51996. // Also, handle both forward and reverse animations
  51997. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51998. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51999. var event = events[index];
  52000. if (!event.isDone) {
  52001. // If event should be done only once, remove it.
  52002. if (event.onlyOnce) {
  52003. events.splice(index, 1);
  52004. index--;
  52005. }
  52006. event.isDone = true;
  52007. event.action();
  52008. } // Don't do anything if the event has already be done.
  52009. }
  52010. else if (events[index].isDone && !events[index].onlyOnce) {
  52011. // reset event, the animation is looping
  52012. events[index].isDone = false;
  52013. }
  52014. }
  52015. if (!returnValue) {
  52016. this._stopped = true;
  52017. }
  52018. return returnValue;
  52019. };
  52020. return RuntimeAnimation;
  52021. }());
  52022. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52023. })(BABYLON || (BABYLON = {}));
  52024. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52025. var BABYLON;
  52026. (function (BABYLON) {
  52027. var Animatable = /** @class */ (function () {
  52028. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  52029. if (fromFrame === void 0) { fromFrame = 0; }
  52030. if (toFrame === void 0) { toFrame = 100; }
  52031. if (loopAnimation === void 0) { loopAnimation = false; }
  52032. if (speedRatio === void 0) { speedRatio = 1.0; }
  52033. this.target = target;
  52034. this.fromFrame = fromFrame;
  52035. this.toFrame = toFrame;
  52036. this.loopAnimation = loopAnimation;
  52037. this.onAnimationEnd = onAnimationEnd;
  52038. this._localDelayOffset = null;
  52039. this._pausedDelay = null;
  52040. this._runtimeAnimations = new Array();
  52041. this._paused = false;
  52042. this._speedRatio = 1;
  52043. this._weight = -1.0;
  52044. this.animationStarted = false;
  52045. this._scene = scene;
  52046. if (animations) {
  52047. this.appendAnimations(target, animations);
  52048. }
  52049. this._speedRatio = speedRatio;
  52050. scene._activeAnimatables.push(this);
  52051. }
  52052. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52053. /**
  52054. * Gets the root Animatable used to synchronize and normalize animations
  52055. */
  52056. get: function () {
  52057. return this._syncRoot;
  52058. },
  52059. enumerable: true,
  52060. configurable: true
  52061. });
  52062. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52063. /**
  52064. * Gets the current frame of the first RuntimeAnimation
  52065. * Used to synchronize Animatables
  52066. */
  52067. get: function () {
  52068. if (this._runtimeAnimations.length === 0) {
  52069. return 0;
  52070. }
  52071. return this._runtimeAnimations[0].currentFrame;
  52072. },
  52073. enumerable: true,
  52074. configurable: true
  52075. });
  52076. Object.defineProperty(Animatable.prototype, "weight", {
  52077. /**
  52078. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52079. */
  52080. get: function () {
  52081. return this._weight;
  52082. },
  52083. set: function (value) {
  52084. if (value === -1) { // -1 is ok and means no weight
  52085. this._weight = -1;
  52086. return;
  52087. }
  52088. // Else weight must be in [0, 1] range
  52089. this._weight = Math.min(Math.max(value, 0), 1.0);
  52090. },
  52091. enumerable: true,
  52092. configurable: true
  52093. });
  52094. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52095. /**
  52096. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52097. */
  52098. get: function () {
  52099. return this._speedRatio;
  52100. },
  52101. set: function (value) {
  52102. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52103. var animation = this._runtimeAnimations[index];
  52104. animation._prepareForSpeedRatioChange(value);
  52105. }
  52106. this._speedRatio = value;
  52107. },
  52108. enumerable: true,
  52109. configurable: true
  52110. });
  52111. // Methods
  52112. /**
  52113. * Synchronize and normalize current Animatable with a source Animatable
  52114. * This is useful when using animation weights and when animations are not of the same length
  52115. * @param root defines the root Animatable to synchronize with
  52116. * @returns the current Animatable
  52117. */
  52118. Animatable.prototype.syncWith = function (root) {
  52119. this._syncRoot = root;
  52120. if (root) {
  52121. // Make sure this animatable will animate after the root
  52122. var index = this._scene._activeAnimatables.indexOf(this);
  52123. if (index > -1) {
  52124. this._scene._activeAnimatables.splice(index, 1);
  52125. this._scene._activeAnimatables.push(this);
  52126. }
  52127. }
  52128. return this;
  52129. };
  52130. Animatable.prototype.getAnimations = function () {
  52131. return this._runtimeAnimations;
  52132. };
  52133. Animatable.prototype.appendAnimations = function (target, animations) {
  52134. for (var index = 0; index < animations.length; index++) {
  52135. var animation = animations[index];
  52136. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52137. }
  52138. };
  52139. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52140. var runtimeAnimations = this._runtimeAnimations;
  52141. for (var index = 0; index < runtimeAnimations.length; index++) {
  52142. if (runtimeAnimations[index].animation.targetProperty === property) {
  52143. return runtimeAnimations[index].animation;
  52144. }
  52145. }
  52146. return null;
  52147. };
  52148. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52149. var runtimeAnimations = this._runtimeAnimations;
  52150. for (var index = 0; index < runtimeAnimations.length; index++) {
  52151. if (runtimeAnimations[index].animation.targetProperty === property) {
  52152. return runtimeAnimations[index];
  52153. }
  52154. }
  52155. return null;
  52156. };
  52157. Animatable.prototype.reset = function () {
  52158. var runtimeAnimations = this._runtimeAnimations;
  52159. for (var index = 0; index < runtimeAnimations.length; index++) {
  52160. runtimeAnimations[index].reset();
  52161. }
  52162. // Reset to original value
  52163. for (index = 0; index < runtimeAnimations.length; index++) {
  52164. var animation = runtimeAnimations[index];
  52165. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  52166. }
  52167. this._localDelayOffset = null;
  52168. this._pausedDelay = null;
  52169. };
  52170. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52171. var runtimeAnimations = this._runtimeAnimations;
  52172. for (var index = 0; index < runtimeAnimations.length; index++) {
  52173. runtimeAnimations[index].animation.enableBlending = true;
  52174. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52175. }
  52176. };
  52177. Animatable.prototype.disableBlending = function () {
  52178. var runtimeAnimations = this._runtimeAnimations;
  52179. for (var index = 0; index < runtimeAnimations.length; index++) {
  52180. runtimeAnimations[index].animation.enableBlending = false;
  52181. }
  52182. };
  52183. Animatable.prototype.goToFrame = function (frame) {
  52184. var runtimeAnimations = this._runtimeAnimations;
  52185. if (runtimeAnimations[0]) {
  52186. var fps = runtimeAnimations[0].animation.framePerSecond;
  52187. var currentFrame = runtimeAnimations[0].currentFrame;
  52188. var adjustTime = frame - currentFrame;
  52189. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52190. if (this._localDelayOffset === null) {
  52191. this._localDelayOffset = 0;
  52192. }
  52193. this._localDelayOffset -= delay;
  52194. }
  52195. for (var index = 0; index < runtimeAnimations.length; index++) {
  52196. runtimeAnimations[index].goToFrame(frame);
  52197. }
  52198. };
  52199. Animatable.prototype.pause = function () {
  52200. if (this._paused) {
  52201. return;
  52202. }
  52203. this._paused = true;
  52204. };
  52205. Animatable.prototype.restart = function () {
  52206. this._paused = false;
  52207. };
  52208. Animatable.prototype.stop = function (animationName) {
  52209. if (animationName) {
  52210. var idx = this._scene._activeAnimatables.indexOf(this);
  52211. if (idx > -1) {
  52212. var runtimeAnimations = this._runtimeAnimations;
  52213. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52214. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  52215. continue;
  52216. }
  52217. runtimeAnimations[index].dispose();
  52218. runtimeAnimations.splice(index, 1);
  52219. }
  52220. if (runtimeAnimations.length == 0) {
  52221. this._scene._activeAnimatables.splice(idx, 1);
  52222. if (this.onAnimationEnd) {
  52223. this.onAnimationEnd();
  52224. }
  52225. }
  52226. }
  52227. }
  52228. else {
  52229. var index = this._scene._activeAnimatables.indexOf(this);
  52230. if (index > -1) {
  52231. this._scene._activeAnimatables.splice(index, 1);
  52232. var runtimeAnimations = this._runtimeAnimations;
  52233. for (var index = 0; index < runtimeAnimations.length; index++) {
  52234. runtimeAnimations[index].dispose();
  52235. }
  52236. if (this.onAnimationEnd) {
  52237. this.onAnimationEnd();
  52238. }
  52239. }
  52240. }
  52241. };
  52242. Animatable.prototype._animate = function (delay) {
  52243. if (this._paused) {
  52244. this.animationStarted = false;
  52245. if (this._pausedDelay === null) {
  52246. this._pausedDelay = delay;
  52247. }
  52248. return true;
  52249. }
  52250. if (this._localDelayOffset === null) {
  52251. this._localDelayOffset = delay;
  52252. this._pausedDelay = null;
  52253. }
  52254. else if (this._pausedDelay !== null) {
  52255. this._localDelayOffset += delay - this._pausedDelay;
  52256. this._pausedDelay = null;
  52257. }
  52258. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52259. return true;
  52260. }
  52261. // Animating
  52262. var running = false;
  52263. var runtimeAnimations = this._runtimeAnimations;
  52264. var index;
  52265. for (index = 0; index < runtimeAnimations.length; index++) {
  52266. var animation = runtimeAnimations[index];
  52267. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52268. running = running || isRunning;
  52269. }
  52270. this.animationStarted = running;
  52271. if (!running) {
  52272. // Remove from active animatables
  52273. index = this._scene._activeAnimatables.indexOf(this);
  52274. this._scene._activeAnimatables.splice(index, 1);
  52275. // Dispose all runtime animations
  52276. for (index = 0; index < runtimeAnimations.length; index++) {
  52277. runtimeAnimations[index].dispose();
  52278. }
  52279. }
  52280. if (!running && this.onAnimationEnd) {
  52281. this.onAnimationEnd();
  52282. this.onAnimationEnd = null;
  52283. }
  52284. return running;
  52285. };
  52286. return Animatable;
  52287. }());
  52288. BABYLON.Animatable = Animatable;
  52289. })(BABYLON || (BABYLON = {}));
  52290. //# sourceMappingURL=babylon.animatable.js.map
  52291. var BABYLON;
  52292. (function (BABYLON) {
  52293. var EasingFunction = /** @class */ (function () {
  52294. function EasingFunction() {
  52295. // Properties
  52296. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52297. }
  52298. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52299. get: function () {
  52300. return EasingFunction._EASINGMODE_EASEIN;
  52301. },
  52302. enumerable: true,
  52303. configurable: true
  52304. });
  52305. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52306. get: function () {
  52307. return EasingFunction._EASINGMODE_EASEOUT;
  52308. },
  52309. enumerable: true,
  52310. configurable: true
  52311. });
  52312. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52313. get: function () {
  52314. return EasingFunction._EASINGMODE_EASEINOUT;
  52315. },
  52316. enumerable: true,
  52317. configurable: true
  52318. });
  52319. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52320. var n = Math.min(Math.max(easingMode, 0), 2);
  52321. this._easingMode = n;
  52322. };
  52323. EasingFunction.prototype.getEasingMode = function () {
  52324. return this._easingMode;
  52325. };
  52326. EasingFunction.prototype.easeInCore = function (gradient) {
  52327. throw new Error('You must implement this method');
  52328. };
  52329. EasingFunction.prototype.ease = function (gradient) {
  52330. switch (this._easingMode) {
  52331. case EasingFunction.EASINGMODE_EASEIN:
  52332. return this.easeInCore(gradient);
  52333. case EasingFunction.EASINGMODE_EASEOUT:
  52334. return (1 - this.easeInCore(1 - gradient));
  52335. }
  52336. if (gradient >= 0.5) {
  52337. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52338. }
  52339. return (this.easeInCore(gradient * 2) * 0.5);
  52340. };
  52341. //Statics
  52342. EasingFunction._EASINGMODE_EASEIN = 0;
  52343. EasingFunction._EASINGMODE_EASEOUT = 1;
  52344. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52345. return EasingFunction;
  52346. }());
  52347. BABYLON.EasingFunction = EasingFunction;
  52348. var CircleEase = /** @class */ (function (_super) {
  52349. __extends(CircleEase, _super);
  52350. function CircleEase() {
  52351. return _super !== null && _super.apply(this, arguments) || this;
  52352. }
  52353. CircleEase.prototype.easeInCore = function (gradient) {
  52354. gradient = Math.max(0, Math.min(1, gradient));
  52355. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52356. };
  52357. return CircleEase;
  52358. }(EasingFunction));
  52359. BABYLON.CircleEase = CircleEase;
  52360. var BackEase = /** @class */ (function (_super) {
  52361. __extends(BackEase, _super);
  52362. function BackEase(amplitude) {
  52363. if (amplitude === void 0) { amplitude = 1; }
  52364. var _this = _super.call(this) || this;
  52365. _this.amplitude = amplitude;
  52366. return _this;
  52367. }
  52368. BackEase.prototype.easeInCore = function (gradient) {
  52369. var num = Math.max(0, this.amplitude);
  52370. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52371. };
  52372. return BackEase;
  52373. }(EasingFunction));
  52374. BABYLON.BackEase = BackEase;
  52375. var BounceEase = /** @class */ (function (_super) {
  52376. __extends(BounceEase, _super);
  52377. function BounceEase(bounces, bounciness) {
  52378. if (bounces === void 0) { bounces = 3; }
  52379. if (bounciness === void 0) { bounciness = 2; }
  52380. var _this = _super.call(this) || this;
  52381. _this.bounces = bounces;
  52382. _this.bounciness = bounciness;
  52383. return _this;
  52384. }
  52385. BounceEase.prototype.easeInCore = function (gradient) {
  52386. var y = Math.max(0.0, this.bounces);
  52387. var bounciness = this.bounciness;
  52388. if (bounciness <= 1.0) {
  52389. bounciness = 1.001;
  52390. }
  52391. var num9 = Math.pow(bounciness, y);
  52392. var num5 = 1.0 - bounciness;
  52393. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52394. var num15 = gradient * num4;
  52395. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52396. var num3 = Math.floor(num65);
  52397. var num13 = num3 + 1.0;
  52398. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52399. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52400. var num7 = (num8 + num12) * 0.5;
  52401. var num6 = gradient - num7;
  52402. var num2 = num7 - num8;
  52403. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52404. };
  52405. return BounceEase;
  52406. }(EasingFunction));
  52407. BABYLON.BounceEase = BounceEase;
  52408. var CubicEase = /** @class */ (function (_super) {
  52409. __extends(CubicEase, _super);
  52410. function CubicEase() {
  52411. return _super !== null && _super.apply(this, arguments) || this;
  52412. }
  52413. CubicEase.prototype.easeInCore = function (gradient) {
  52414. return (gradient * gradient * gradient);
  52415. };
  52416. return CubicEase;
  52417. }(EasingFunction));
  52418. BABYLON.CubicEase = CubicEase;
  52419. var ElasticEase = /** @class */ (function (_super) {
  52420. __extends(ElasticEase, _super);
  52421. function ElasticEase(oscillations, springiness) {
  52422. if (oscillations === void 0) { oscillations = 3; }
  52423. if (springiness === void 0) { springiness = 3; }
  52424. var _this = _super.call(this) || this;
  52425. _this.oscillations = oscillations;
  52426. _this.springiness = springiness;
  52427. return _this;
  52428. }
  52429. ElasticEase.prototype.easeInCore = function (gradient) {
  52430. var num2;
  52431. var num3 = Math.max(0.0, this.oscillations);
  52432. var num = Math.max(0.0, this.springiness);
  52433. if (num == 0) {
  52434. num2 = gradient;
  52435. }
  52436. else {
  52437. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52438. }
  52439. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52440. };
  52441. return ElasticEase;
  52442. }(EasingFunction));
  52443. BABYLON.ElasticEase = ElasticEase;
  52444. var ExponentialEase = /** @class */ (function (_super) {
  52445. __extends(ExponentialEase, _super);
  52446. function ExponentialEase(exponent) {
  52447. if (exponent === void 0) { exponent = 2; }
  52448. var _this = _super.call(this) || this;
  52449. _this.exponent = exponent;
  52450. return _this;
  52451. }
  52452. ExponentialEase.prototype.easeInCore = function (gradient) {
  52453. if (this.exponent <= 0) {
  52454. return gradient;
  52455. }
  52456. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52457. };
  52458. return ExponentialEase;
  52459. }(EasingFunction));
  52460. BABYLON.ExponentialEase = ExponentialEase;
  52461. var PowerEase = /** @class */ (function (_super) {
  52462. __extends(PowerEase, _super);
  52463. function PowerEase(power) {
  52464. if (power === void 0) { power = 2; }
  52465. var _this = _super.call(this) || this;
  52466. _this.power = power;
  52467. return _this;
  52468. }
  52469. PowerEase.prototype.easeInCore = function (gradient) {
  52470. var y = Math.max(0.0, this.power);
  52471. return Math.pow(gradient, y);
  52472. };
  52473. return PowerEase;
  52474. }(EasingFunction));
  52475. BABYLON.PowerEase = PowerEase;
  52476. var QuadraticEase = /** @class */ (function (_super) {
  52477. __extends(QuadraticEase, _super);
  52478. function QuadraticEase() {
  52479. return _super !== null && _super.apply(this, arguments) || this;
  52480. }
  52481. QuadraticEase.prototype.easeInCore = function (gradient) {
  52482. return (gradient * gradient);
  52483. };
  52484. return QuadraticEase;
  52485. }(EasingFunction));
  52486. BABYLON.QuadraticEase = QuadraticEase;
  52487. var QuarticEase = /** @class */ (function (_super) {
  52488. __extends(QuarticEase, _super);
  52489. function QuarticEase() {
  52490. return _super !== null && _super.apply(this, arguments) || this;
  52491. }
  52492. QuarticEase.prototype.easeInCore = function (gradient) {
  52493. return (gradient * gradient * gradient * gradient);
  52494. };
  52495. return QuarticEase;
  52496. }(EasingFunction));
  52497. BABYLON.QuarticEase = QuarticEase;
  52498. var QuinticEase = /** @class */ (function (_super) {
  52499. __extends(QuinticEase, _super);
  52500. function QuinticEase() {
  52501. return _super !== null && _super.apply(this, arguments) || this;
  52502. }
  52503. QuinticEase.prototype.easeInCore = function (gradient) {
  52504. return (gradient * gradient * gradient * gradient * gradient);
  52505. };
  52506. return QuinticEase;
  52507. }(EasingFunction));
  52508. BABYLON.QuinticEase = QuinticEase;
  52509. var SineEase = /** @class */ (function (_super) {
  52510. __extends(SineEase, _super);
  52511. function SineEase() {
  52512. return _super !== null && _super.apply(this, arguments) || this;
  52513. }
  52514. SineEase.prototype.easeInCore = function (gradient) {
  52515. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52516. };
  52517. return SineEase;
  52518. }(EasingFunction));
  52519. BABYLON.SineEase = SineEase;
  52520. var BezierCurveEase = /** @class */ (function (_super) {
  52521. __extends(BezierCurveEase, _super);
  52522. function BezierCurveEase(x1, y1, x2, y2) {
  52523. if (x1 === void 0) { x1 = 0; }
  52524. if (y1 === void 0) { y1 = 0; }
  52525. if (x2 === void 0) { x2 = 1; }
  52526. if (y2 === void 0) { y2 = 1; }
  52527. var _this = _super.call(this) || this;
  52528. _this.x1 = x1;
  52529. _this.y1 = y1;
  52530. _this.x2 = x2;
  52531. _this.y2 = y2;
  52532. return _this;
  52533. }
  52534. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52535. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52536. };
  52537. return BezierCurveEase;
  52538. }(EasingFunction));
  52539. BABYLON.BezierCurveEase = BezierCurveEase;
  52540. })(BABYLON || (BABYLON = {}));
  52541. //# sourceMappingURL=babylon.easing.js.map
  52542. var BABYLON;
  52543. (function (BABYLON) {
  52544. /**
  52545. * A Condition applied to an Action
  52546. */
  52547. var Condition = /** @class */ (function () {
  52548. /**
  52549. * Creates a new Condition
  52550. * @param actionManager the manager of the action the condition is applied to
  52551. */
  52552. function Condition(actionManager) {
  52553. this._actionManager = actionManager;
  52554. }
  52555. /**
  52556. * Check if the current condition is valid
  52557. * @returns a boolean
  52558. */
  52559. Condition.prototype.isValid = function () {
  52560. return true;
  52561. };
  52562. /**
  52563. * Internal only
  52564. * @hidden
  52565. */
  52566. Condition.prototype._getProperty = function (propertyPath) {
  52567. return this._actionManager._getProperty(propertyPath);
  52568. };
  52569. /**
  52570. * Internal only
  52571. * @hidden
  52572. */
  52573. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52574. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52575. };
  52576. /**
  52577. * Serialize placeholder for child classes
  52578. * @returns the serialized object
  52579. */
  52580. Condition.prototype.serialize = function () {
  52581. };
  52582. /**
  52583. * Internal only
  52584. * @hidden
  52585. */
  52586. Condition.prototype._serialize = function (serializedCondition) {
  52587. return {
  52588. type: 2,
  52589. children: [],
  52590. name: serializedCondition.name,
  52591. properties: serializedCondition.properties
  52592. };
  52593. };
  52594. return Condition;
  52595. }());
  52596. BABYLON.Condition = Condition;
  52597. /**
  52598. * Defines specific conditional operators as extensions of Condition
  52599. */
  52600. var ValueCondition = /** @class */ (function (_super) {
  52601. __extends(ValueCondition, _super);
  52602. /**
  52603. * Creates a new ValueCondition
  52604. * @param actionManager manager for the action the condition applies to
  52605. * @param target for the action
  52606. * @param propertyPath path to specify the property of the target the conditional operator uses
  52607. * @param value the value compared by the conditional operator against the current value of the property
  52608. * @param operator the conditional operator, default ValueCondition.IsEqual
  52609. */
  52610. function ValueCondition(actionManager, target,
  52611. /** path to specify the property of the target the conditional operator uses */
  52612. propertyPath,
  52613. /** the value compared by the conditional operator against the current value of the property */
  52614. value,
  52615. /** the conditional operator, default ValueCondition.IsEqual */
  52616. operator) {
  52617. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52618. var _this = _super.call(this, actionManager) || this;
  52619. _this.propertyPath = propertyPath;
  52620. _this.value = value;
  52621. _this.operator = operator;
  52622. _this._target = target;
  52623. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52624. _this._property = _this._getProperty(_this.propertyPath);
  52625. return _this;
  52626. }
  52627. Object.defineProperty(ValueCondition, "IsEqual", {
  52628. /**
  52629. * returns the number for IsEqual
  52630. */
  52631. get: function () {
  52632. return ValueCondition._IsEqual;
  52633. },
  52634. enumerable: true,
  52635. configurable: true
  52636. });
  52637. Object.defineProperty(ValueCondition, "IsDifferent", {
  52638. /**
  52639. * Returns the number for IsDifferent
  52640. */
  52641. get: function () {
  52642. return ValueCondition._IsDifferent;
  52643. },
  52644. enumerable: true,
  52645. configurable: true
  52646. });
  52647. Object.defineProperty(ValueCondition, "IsGreater", {
  52648. /**
  52649. * Returns the number for IsGreater
  52650. */
  52651. get: function () {
  52652. return ValueCondition._IsGreater;
  52653. },
  52654. enumerable: true,
  52655. configurable: true
  52656. });
  52657. Object.defineProperty(ValueCondition, "IsLesser", {
  52658. /**
  52659. * Returns the number for IsLesser
  52660. */
  52661. get: function () {
  52662. return ValueCondition._IsLesser;
  52663. },
  52664. enumerable: true,
  52665. configurable: true
  52666. });
  52667. /**
  52668. * Compares the given value with the property value for the specified conditional operator
  52669. * @returns the result of the comparison
  52670. */
  52671. ValueCondition.prototype.isValid = function () {
  52672. switch (this.operator) {
  52673. case ValueCondition.IsGreater:
  52674. return this._effectiveTarget[this._property] > this.value;
  52675. case ValueCondition.IsLesser:
  52676. return this._effectiveTarget[this._property] < this.value;
  52677. case ValueCondition.IsEqual:
  52678. case ValueCondition.IsDifferent:
  52679. var check;
  52680. if (this.value.equals) {
  52681. check = this.value.equals(this._effectiveTarget[this._property]);
  52682. }
  52683. else {
  52684. check = this.value === this._effectiveTarget[this._property];
  52685. }
  52686. return this.operator === ValueCondition.IsEqual ? check : !check;
  52687. }
  52688. return false;
  52689. };
  52690. /**
  52691. * Serialize the ValueCondition into a JSON compatible object
  52692. * @returns serialization object
  52693. */
  52694. ValueCondition.prototype.serialize = function () {
  52695. return this._serialize({
  52696. name: "ValueCondition",
  52697. properties: [
  52698. BABYLON.Action._GetTargetProperty(this._target),
  52699. { name: "propertyPath", value: this.propertyPath },
  52700. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52701. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52702. ]
  52703. });
  52704. };
  52705. /**
  52706. * Gets the name of the conditional operator for the ValueCondition
  52707. * @param operator the conditional operator
  52708. * @returns the name
  52709. */
  52710. ValueCondition.GetOperatorName = function (operator) {
  52711. switch (operator) {
  52712. case ValueCondition._IsEqual: return "IsEqual";
  52713. case ValueCondition._IsDifferent: return "IsDifferent";
  52714. case ValueCondition._IsGreater: return "IsGreater";
  52715. case ValueCondition._IsLesser: return "IsLesser";
  52716. default: return "";
  52717. }
  52718. };
  52719. /**
  52720. * Internal only
  52721. * @hidden
  52722. */
  52723. ValueCondition._IsEqual = 0;
  52724. /**
  52725. * Internal only
  52726. * @hidden
  52727. */
  52728. ValueCondition._IsDifferent = 1;
  52729. /**
  52730. * Internal only
  52731. * @hidden
  52732. */
  52733. ValueCondition._IsGreater = 2;
  52734. /**
  52735. * Internal only
  52736. * @hidden
  52737. */
  52738. ValueCondition._IsLesser = 3;
  52739. return ValueCondition;
  52740. }(Condition));
  52741. BABYLON.ValueCondition = ValueCondition;
  52742. /**
  52743. * Defines a predicate condition as an extension of Condition
  52744. */
  52745. var PredicateCondition = /** @class */ (function (_super) {
  52746. __extends(PredicateCondition, _super);
  52747. /**
  52748. * Creates a new PredicateCondition
  52749. * @param actionManager manager for the action the condition applies to
  52750. * @param predicate defines the predicate function used to validate the condition
  52751. */
  52752. function PredicateCondition(actionManager,
  52753. /** defines the predicate function used to validate the condition */
  52754. predicate) {
  52755. var _this = _super.call(this, actionManager) || this;
  52756. _this.predicate = predicate;
  52757. return _this;
  52758. }
  52759. /**
  52760. * @returns the validity of the predicate condition
  52761. */
  52762. PredicateCondition.prototype.isValid = function () {
  52763. return this.predicate();
  52764. };
  52765. return PredicateCondition;
  52766. }(Condition));
  52767. BABYLON.PredicateCondition = PredicateCondition;
  52768. /**
  52769. * Defines a state condition as an extension of Condition
  52770. */
  52771. var StateCondition = /** @class */ (function (_super) {
  52772. __extends(StateCondition, _super);
  52773. /**
  52774. * Creates a new StateCondition
  52775. * @param actionManager manager for the action the condition applies to
  52776. * @param target of the condition
  52777. * @param value to compare with target state
  52778. */
  52779. function StateCondition(actionManager, target, value) {
  52780. var _this = _super.call(this, actionManager) || this;
  52781. _this.value = value;
  52782. _this._target = target;
  52783. return _this;
  52784. }
  52785. /**
  52786. * @returns the validity of the state
  52787. */
  52788. StateCondition.prototype.isValid = function () {
  52789. return this._target.state === this.value;
  52790. };
  52791. /**
  52792. * Serialize the StateCondition into a JSON compatible object
  52793. * @returns serialization object
  52794. */
  52795. StateCondition.prototype.serialize = function () {
  52796. return this._serialize({
  52797. name: "StateCondition",
  52798. properties: [
  52799. BABYLON.Action._GetTargetProperty(this._target),
  52800. { name: "value", value: this.value }
  52801. ]
  52802. });
  52803. };
  52804. return StateCondition;
  52805. }(Condition));
  52806. BABYLON.StateCondition = StateCondition;
  52807. })(BABYLON || (BABYLON = {}));
  52808. //# sourceMappingURL=babylon.condition.js.map
  52809. var BABYLON;
  52810. (function (BABYLON) {
  52811. /**
  52812. * The action to be carried out following a trigger
  52813. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52814. */
  52815. var Action = /** @class */ (function () {
  52816. /**
  52817. * Creates a new Action
  52818. * @param triggerOptions the trigger, with or without parameters, for the action
  52819. * @param condition an optional determinant of action
  52820. */
  52821. function Action(
  52822. /** the trigger, with or without parameters, for the action */
  52823. triggerOptions, condition) {
  52824. this.triggerOptions = triggerOptions;
  52825. /**
  52826. * An event triggered prior to action being executed.
  52827. */
  52828. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52829. if (triggerOptions.parameter) {
  52830. this.trigger = triggerOptions.trigger;
  52831. this._triggerParameter = triggerOptions.parameter;
  52832. }
  52833. else {
  52834. this.trigger = triggerOptions;
  52835. }
  52836. this._nextActiveAction = this;
  52837. this._condition = condition;
  52838. }
  52839. /**
  52840. * Internal only
  52841. * @hidden
  52842. */
  52843. Action.prototype._prepare = function () {
  52844. };
  52845. /**
  52846. * Gets the trigger parameters
  52847. * @returns the trigger parameters
  52848. */
  52849. Action.prototype.getTriggerParameter = function () {
  52850. return this._triggerParameter;
  52851. };
  52852. /**
  52853. * Internal only - executes current action event
  52854. * @hidden
  52855. */
  52856. Action.prototype._executeCurrent = function (evt) {
  52857. if (this._nextActiveAction._condition) {
  52858. var condition = this._nextActiveAction._condition;
  52859. var currentRenderId = this._actionManager.getScene().getRenderId();
  52860. // We cache the current evaluation for the current frame
  52861. if (condition._evaluationId === currentRenderId) {
  52862. if (!condition._currentResult) {
  52863. return;
  52864. }
  52865. }
  52866. else {
  52867. condition._evaluationId = currentRenderId;
  52868. if (!condition.isValid()) {
  52869. condition._currentResult = false;
  52870. return;
  52871. }
  52872. condition._currentResult = true;
  52873. }
  52874. }
  52875. this.onBeforeExecuteObservable.notifyObservers(this);
  52876. this._nextActiveAction.execute(evt);
  52877. this.skipToNextActiveAction();
  52878. };
  52879. /**
  52880. * Execute placeholder for child classes
  52881. * @param evt optional action event
  52882. */
  52883. Action.prototype.execute = function (evt) {
  52884. };
  52885. /**
  52886. * Skips to next active action
  52887. */
  52888. Action.prototype.skipToNextActiveAction = function () {
  52889. if (this._nextActiveAction._child) {
  52890. if (!this._nextActiveAction._child._actionManager) {
  52891. this._nextActiveAction._child._actionManager = this._actionManager;
  52892. }
  52893. this._nextActiveAction = this._nextActiveAction._child;
  52894. }
  52895. else {
  52896. this._nextActiveAction = this;
  52897. }
  52898. };
  52899. /**
  52900. * Adds action to chain of actions, may be a DoNothingAction
  52901. * @param action defines the next action to execute
  52902. * @returns The action passed in
  52903. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52904. */
  52905. Action.prototype.then = function (action) {
  52906. this._child = action;
  52907. action._actionManager = this._actionManager;
  52908. action._prepare();
  52909. return action;
  52910. };
  52911. /**
  52912. * Internal only
  52913. * @hidden
  52914. */
  52915. Action.prototype._getProperty = function (propertyPath) {
  52916. return this._actionManager._getProperty(propertyPath);
  52917. };
  52918. /**
  52919. * Internal only
  52920. * @hidden
  52921. */
  52922. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52923. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52924. };
  52925. /**
  52926. * Serialize placeholder for child classes
  52927. * @param parent of child
  52928. * @returns the serialized object
  52929. */
  52930. Action.prototype.serialize = function (parent) {
  52931. };
  52932. /**
  52933. * Internal only called by serialize
  52934. * @hidden
  52935. */
  52936. Action.prototype._serialize = function (serializedAction, parent) {
  52937. var serializationObject = {
  52938. type: 1,
  52939. children: [],
  52940. name: serializedAction.name,
  52941. properties: serializedAction.properties || []
  52942. };
  52943. // Serialize child
  52944. if (this._child) {
  52945. this._child.serialize(serializationObject);
  52946. }
  52947. // Check if "this" has a condition
  52948. if (this._condition) {
  52949. var serializedCondition = this._condition.serialize();
  52950. serializedCondition.children.push(serializationObject);
  52951. if (parent) {
  52952. parent.children.push(serializedCondition);
  52953. }
  52954. return serializedCondition;
  52955. }
  52956. if (parent) {
  52957. parent.children.push(serializationObject);
  52958. }
  52959. return serializationObject;
  52960. };
  52961. /**
  52962. * Internal only
  52963. * @hidden
  52964. */
  52965. Action._SerializeValueAsString = function (value) {
  52966. if (typeof value === "number") {
  52967. return value.toString();
  52968. }
  52969. if (typeof value === "boolean") {
  52970. return value ? "true" : "false";
  52971. }
  52972. if (value instanceof BABYLON.Vector2) {
  52973. return value.x + ", " + value.y;
  52974. }
  52975. if (value instanceof BABYLON.Vector3) {
  52976. return value.x + ", " + value.y + ", " + value.z;
  52977. }
  52978. if (value instanceof BABYLON.Color3) {
  52979. return value.r + ", " + value.g + ", " + value.b;
  52980. }
  52981. if (value instanceof BABYLON.Color4) {
  52982. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52983. }
  52984. return value; // string
  52985. };
  52986. /**
  52987. * Internal only
  52988. * @hidden
  52989. */
  52990. Action._GetTargetProperty = function (target) {
  52991. return {
  52992. name: "target",
  52993. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52994. : target instanceof BABYLON.Light ? "LightProperties"
  52995. : target instanceof BABYLON.Camera ? "CameraProperties"
  52996. : "SceneProperties",
  52997. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52998. };
  52999. };
  53000. return Action;
  53001. }());
  53002. BABYLON.Action = Action;
  53003. })(BABYLON || (BABYLON = {}));
  53004. //# sourceMappingURL=babylon.action.js.map
  53005. var BABYLON;
  53006. (function (BABYLON) {
  53007. /**
  53008. * ActionEvent is the event being sent when an action is triggered.
  53009. */
  53010. var ActionEvent = /** @class */ (function () {
  53011. /**
  53012. * Creates a new ActionEvent
  53013. * @param source The mesh or sprite that triggered the action
  53014. * @param pointerX The X mouse cursor position at the time of the event
  53015. * @param pointerY The Y mouse cursor position at the time of the event
  53016. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53017. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53018. * @param additionalData additional data for the event
  53019. */
  53020. function ActionEvent(
  53021. /** The mesh or sprite that triggered the action */
  53022. source,
  53023. /** The X mouse cursor position at the time of the event */
  53024. pointerX,
  53025. /** The Y mouse cursor position at the time of the event */
  53026. pointerY,
  53027. /** The mesh that is currently pointed at (can be null) */
  53028. meshUnderPointer,
  53029. /** the original (browser) event that triggered the ActionEvent */
  53030. sourceEvent,
  53031. /** additional data for the event */
  53032. additionalData) {
  53033. this.source = source;
  53034. this.pointerX = pointerX;
  53035. this.pointerY = pointerY;
  53036. this.meshUnderPointer = meshUnderPointer;
  53037. this.sourceEvent = sourceEvent;
  53038. this.additionalData = additionalData;
  53039. }
  53040. /**
  53041. * Helper function to auto-create an ActionEvent from a source mesh.
  53042. * @param source The source mesh that triggered the event
  53043. * @param evt The original (browser) event
  53044. * @param additionalData additional data for the event
  53045. * @returns the new ActionEvent
  53046. */
  53047. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53048. var scene = source.getScene();
  53049. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53050. };
  53051. /**
  53052. * Helper function to auto-create an ActionEvent from a source sprite
  53053. * @param source The source sprite that triggered the event
  53054. * @param scene Scene associated with the sprite
  53055. * @param evt The original (browser) event
  53056. * @param additionalData additional data for the event
  53057. * @returns the new ActionEvent
  53058. */
  53059. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53060. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53061. };
  53062. /**
  53063. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53064. * @param scene the scene where the event occurred
  53065. * @param evt The original (browser) event
  53066. * @returns the new ActionEvent
  53067. */
  53068. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53069. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53070. };
  53071. /**
  53072. * Helper function to auto-create an ActionEvent from a primitive
  53073. * @param prim defines the target primitive
  53074. * @param pointerPos defines the pointer position
  53075. * @param evt The original (browser) event
  53076. * @param additionalData additional data for the event
  53077. * @returns the new ActionEvent
  53078. */
  53079. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53080. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53081. };
  53082. return ActionEvent;
  53083. }());
  53084. BABYLON.ActionEvent = ActionEvent;
  53085. /**
  53086. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53087. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53088. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53089. */
  53090. var ActionManager = /** @class */ (function () {
  53091. /**
  53092. * Creates a new action manager
  53093. * @param scene defines the hosting scene
  53094. */
  53095. function ActionManager(scene) {
  53096. // Members
  53097. /** Gets the list of actions */
  53098. this.actions = new Array();
  53099. /** Gets the cursor to use when hovering items */
  53100. this.hoverCursor = '';
  53101. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53102. scene._actionManagers.push(this);
  53103. }
  53104. Object.defineProperty(ActionManager, "NothingTrigger", {
  53105. /**
  53106. * Nothing
  53107. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53108. */
  53109. get: function () {
  53110. return ActionManager._NothingTrigger;
  53111. },
  53112. enumerable: true,
  53113. configurable: true
  53114. });
  53115. Object.defineProperty(ActionManager, "OnPickTrigger", {
  53116. /**
  53117. * On pick
  53118. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53119. */
  53120. get: function () {
  53121. return ActionManager._OnPickTrigger;
  53122. },
  53123. enumerable: true,
  53124. configurable: true
  53125. });
  53126. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53127. /**
  53128. * On left pick
  53129. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53130. */
  53131. get: function () {
  53132. return ActionManager._OnLeftPickTrigger;
  53133. },
  53134. enumerable: true,
  53135. configurable: true
  53136. });
  53137. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53138. /**
  53139. * On right pick
  53140. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53141. */
  53142. get: function () {
  53143. return ActionManager._OnRightPickTrigger;
  53144. },
  53145. enumerable: true,
  53146. configurable: true
  53147. });
  53148. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53149. /**
  53150. * On center pick
  53151. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53152. */
  53153. get: function () {
  53154. return ActionManager._OnCenterPickTrigger;
  53155. },
  53156. enumerable: true,
  53157. configurable: true
  53158. });
  53159. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53160. /**
  53161. * On pick down
  53162. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53163. */
  53164. get: function () {
  53165. return ActionManager._OnPickDownTrigger;
  53166. },
  53167. enumerable: true,
  53168. configurable: true
  53169. });
  53170. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53171. /**
  53172. * On double pick
  53173. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53174. */
  53175. get: function () {
  53176. return ActionManager._OnDoublePickTrigger;
  53177. },
  53178. enumerable: true,
  53179. configurable: true
  53180. });
  53181. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53182. /**
  53183. * On pick up
  53184. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53185. */
  53186. get: function () {
  53187. return ActionManager._OnPickUpTrigger;
  53188. },
  53189. enumerable: true,
  53190. configurable: true
  53191. });
  53192. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53193. /**
  53194. * On pick out.
  53195. * This trigger will only be raised if you also declared a OnPickDown
  53196. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53197. */
  53198. get: function () {
  53199. return ActionManager._OnPickOutTrigger;
  53200. },
  53201. enumerable: true,
  53202. configurable: true
  53203. });
  53204. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53205. /**
  53206. * On long press
  53207. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53208. */
  53209. get: function () {
  53210. return ActionManager._OnLongPressTrigger;
  53211. },
  53212. enumerable: true,
  53213. configurable: true
  53214. });
  53215. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53216. /**
  53217. * On pointer over
  53218. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53219. */
  53220. get: function () {
  53221. return ActionManager._OnPointerOverTrigger;
  53222. },
  53223. enumerable: true,
  53224. configurable: true
  53225. });
  53226. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53227. /**
  53228. * On pointer out
  53229. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53230. */
  53231. get: function () {
  53232. return ActionManager._OnPointerOutTrigger;
  53233. },
  53234. enumerable: true,
  53235. configurable: true
  53236. });
  53237. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53238. /**
  53239. * On every frame
  53240. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53241. */
  53242. get: function () {
  53243. return ActionManager._OnEveryFrameTrigger;
  53244. },
  53245. enumerable: true,
  53246. configurable: true
  53247. });
  53248. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53249. /**
  53250. * On intersection enter
  53251. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53252. */
  53253. get: function () {
  53254. return ActionManager._OnIntersectionEnterTrigger;
  53255. },
  53256. enumerable: true,
  53257. configurable: true
  53258. });
  53259. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53260. /**
  53261. * On intersection exit
  53262. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53263. */
  53264. get: function () {
  53265. return ActionManager._OnIntersectionExitTrigger;
  53266. },
  53267. enumerable: true,
  53268. configurable: true
  53269. });
  53270. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53271. /**
  53272. * On key down
  53273. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53274. */
  53275. get: function () {
  53276. return ActionManager._OnKeyDownTrigger;
  53277. },
  53278. enumerable: true,
  53279. configurable: true
  53280. });
  53281. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53282. /**
  53283. * On key up
  53284. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53285. */
  53286. get: function () {
  53287. return ActionManager._OnKeyUpTrigger;
  53288. },
  53289. enumerable: true,
  53290. configurable: true
  53291. });
  53292. // Methods
  53293. /**
  53294. * Releases all associated resources
  53295. */
  53296. ActionManager.prototype.dispose = function () {
  53297. var index = this._scene._actionManagers.indexOf(this);
  53298. for (var i = 0; i < this.actions.length; i++) {
  53299. var action = this.actions[i];
  53300. ActionManager.Triggers[action.trigger]--;
  53301. if (ActionManager.Triggers[action.trigger] === 0) {
  53302. delete ActionManager.Triggers[action.trigger];
  53303. }
  53304. }
  53305. if (index > -1) {
  53306. this._scene._actionManagers.splice(index, 1);
  53307. }
  53308. };
  53309. /**
  53310. * Gets hosting scene
  53311. * @returns the hosting scene
  53312. */
  53313. ActionManager.prototype.getScene = function () {
  53314. return this._scene;
  53315. };
  53316. /**
  53317. * Does this action manager handles actions of any of the given triggers
  53318. * @param triggers defines the triggers to be tested
  53319. * @return a boolean indicating whether one (or more) of the triggers is handled
  53320. */
  53321. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53322. for (var index = 0; index < this.actions.length; index++) {
  53323. var action = this.actions[index];
  53324. if (triggers.indexOf(action.trigger) > -1) {
  53325. return true;
  53326. }
  53327. }
  53328. return false;
  53329. };
  53330. /**
  53331. * Does this action manager handles actions of a given trigger
  53332. * @param trigger defines the trigger to be tested
  53333. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53334. * @return whether the trigger is handled
  53335. */
  53336. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53337. for (var index = 0; index < this.actions.length; index++) {
  53338. var action = this.actions[index];
  53339. if (action.trigger === trigger) {
  53340. if (parameterPredicate) {
  53341. if (parameterPredicate(action.getTriggerParameter())) {
  53342. return true;
  53343. }
  53344. }
  53345. else {
  53346. return true;
  53347. }
  53348. }
  53349. }
  53350. return false;
  53351. };
  53352. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53353. /**
  53354. * Does this action manager has pointer triggers
  53355. */
  53356. get: function () {
  53357. for (var index = 0; index < this.actions.length; index++) {
  53358. var action = this.actions[index];
  53359. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53360. return true;
  53361. }
  53362. }
  53363. return false;
  53364. },
  53365. enumerable: true,
  53366. configurable: true
  53367. });
  53368. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53369. /**
  53370. * Does this action manager has pick triggers
  53371. */
  53372. get: function () {
  53373. for (var index = 0; index < this.actions.length; index++) {
  53374. var action = this.actions[index];
  53375. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53376. return true;
  53377. }
  53378. }
  53379. return false;
  53380. },
  53381. enumerable: true,
  53382. configurable: true
  53383. });
  53384. Object.defineProperty(ActionManager, "HasTriggers", {
  53385. /**
  53386. * Does exist one action manager with at least one trigger
  53387. **/
  53388. get: function () {
  53389. for (var t in ActionManager.Triggers) {
  53390. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53391. return true;
  53392. }
  53393. }
  53394. return false;
  53395. },
  53396. enumerable: true,
  53397. configurable: true
  53398. });
  53399. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53400. /**
  53401. * Does exist one action manager with at least one pick trigger
  53402. **/
  53403. get: function () {
  53404. for (var t in ActionManager.Triggers) {
  53405. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53406. var t_int = parseInt(t);
  53407. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53408. return true;
  53409. }
  53410. }
  53411. }
  53412. return false;
  53413. },
  53414. enumerable: true,
  53415. configurable: true
  53416. });
  53417. /**
  53418. * Does exist one action manager that handles actions of a given trigger
  53419. * @param trigger defines the trigger to be tested
  53420. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53421. **/
  53422. ActionManager.HasSpecificTrigger = function (trigger) {
  53423. for (var t in ActionManager.Triggers) {
  53424. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53425. var t_int = parseInt(t);
  53426. if (t_int === trigger) {
  53427. return true;
  53428. }
  53429. }
  53430. }
  53431. return false;
  53432. };
  53433. /**
  53434. * Registers an action to this action manager
  53435. * @param action defines the action to be registered
  53436. * @return the action amended (prepared) after registration
  53437. */
  53438. ActionManager.prototype.registerAction = function (action) {
  53439. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53440. if (this.getScene().actionManager !== this) {
  53441. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53442. return null;
  53443. }
  53444. }
  53445. this.actions.push(action);
  53446. if (ActionManager.Triggers[action.trigger]) {
  53447. ActionManager.Triggers[action.trigger]++;
  53448. }
  53449. else {
  53450. ActionManager.Triggers[action.trigger] = 1;
  53451. }
  53452. action._actionManager = this;
  53453. action._prepare();
  53454. return action;
  53455. };
  53456. /**
  53457. * Unregisters an action to this action manager
  53458. * @param action defines the action to be unregistered
  53459. * @return a boolean indicating whether the action has been unregistered
  53460. */
  53461. ActionManager.prototype.unregisterAction = function (action) {
  53462. var index = this.actions.indexOf(action);
  53463. if (index !== -1) {
  53464. this.actions.splice(index, 1);
  53465. ActionManager.Triggers[action.trigger] -= 1;
  53466. if (ActionManager.Triggers[action.trigger] === 0) {
  53467. delete ActionManager.Triggers[action.trigger];
  53468. }
  53469. delete action._actionManager;
  53470. return true;
  53471. }
  53472. return false;
  53473. };
  53474. /**
  53475. * Process a specific trigger
  53476. * @param trigger defines the trigger to process
  53477. * @param evt defines the event details to be processed
  53478. */
  53479. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53480. for (var index = 0; index < this.actions.length; index++) {
  53481. var action = this.actions[index];
  53482. if (action.trigger === trigger) {
  53483. if (evt) {
  53484. if (trigger === ActionManager.OnKeyUpTrigger
  53485. || trigger === ActionManager.OnKeyDownTrigger) {
  53486. var parameter = action.getTriggerParameter();
  53487. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53488. if (!parameter.toLowerCase) {
  53489. continue;
  53490. }
  53491. var lowerCase = parameter.toLowerCase();
  53492. if (lowerCase !== evt.sourceEvent.key) {
  53493. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53494. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53495. if (actualkey !== lowerCase) {
  53496. continue;
  53497. }
  53498. }
  53499. }
  53500. }
  53501. }
  53502. action._executeCurrent(evt);
  53503. }
  53504. }
  53505. };
  53506. /** @hidden */
  53507. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53508. var properties = propertyPath.split(".");
  53509. for (var index = 0; index < properties.length - 1; index++) {
  53510. target = target[properties[index]];
  53511. }
  53512. return target;
  53513. };
  53514. /** @hidden */
  53515. ActionManager.prototype._getProperty = function (propertyPath) {
  53516. var properties = propertyPath.split(".");
  53517. return properties[properties.length - 1];
  53518. };
  53519. /**
  53520. * Serialize this manager to a JSON object
  53521. * @param name defines the property name to store this manager
  53522. * @returns a JSON representation of this manager
  53523. */
  53524. ActionManager.prototype.serialize = function (name) {
  53525. var root = {
  53526. children: new Array(),
  53527. name: name,
  53528. type: 3,
  53529. properties: new Array() // Empty for root but required
  53530. };
  53531. for (var i = 0; i < this.actions.length; i++) {
  53532. var triggerObject = {
  53533. type: 0,
  53534. children: new Array(),
  53535. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53536. properties: new Array()
  53537. };
  53538. var triggerOptions = this.actions[i].triggerOptions;
  53539. if (triggerOptions && typeof triggerOptions !== "number") {
  53540. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53541. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53542. }
  53543. else {
  53544. var parameter = {};
  53545. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53546. if (triggerOptions.parameter.mesh) {
  53547. parameter._meshId = triggerOptions.parameter.mesh.id;
  53548. }
  53549. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53550. }
  53551. }
  53552. // Serialize child action, recursively
  53553. this.actions[i].serialize(triggerObject);
  53554. // Add serialized trigger
  53555. root.children.push(triggerObject);
  53556. }
  53557. return root;
  53558. };
  53559. /**
  53560. * Creates a new ActionManager from a JSON data
  53561. * @param parsedActions defines the JSON data to read from
  53562. * @param object defines the hosting mesh
  53563. * @param scene defines the hosting scene
  53564. */
  53565. ActionManager.Parse = function (parsedActions, object, scene) {
  53566. var actionManager = new ActionManager(scene);
  53567. if (object === null)
  53568. scene.actionManager = actionManager;
  53569. else
  53570. object.actionManager = actionManager;
  53571. // instanciate a new object
  53572. var instanciate = function (name, params) {
  53573. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53574. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53575. newInstance.constructor.apply(newInstance, params);
  53576. return newInstance;
  53577. };
  53578. var parseParameter = function (name, value, target, propertyPath) {
  53579. if (propertyPath === null) {
  53580. // String, boolean or float
  53581. var floatValue = parseFloat(value);
  53582. if (value === "true" || value === "false")
  53583. return value === "true";
  53584. else
  53585. return isNaN(floatValue) ? value : floatValue;
  53586. }
  53587. var effectiveTarget = propertyPath.split(".");
  53588. var values = value.split(",");
  53589. // Get effective Target
  53590. for (var i = 0; i < effectiveTarget.length; i++) {
  53591. target = target[effectiveTarget[i]];
  53592. }
  53593. // Return appropriate value with its type
  53594. if (typeof (target) === "boolean")
  53595. return values[0] === "true";
  53596. if (typeof (target) === "string")
  53597. return values[0];
  53598. // Parameters with multiple values such as Vector3 etc.
  53599. var split = new Array();
  53600. for (var i = 0; i < values.length; i++)
  53601. split.push(parseFloat(values[i]));
  53602. if (target instanceof BABYLON.Vector3)
  53603. return BABYLON.Vector3.FromArray(split);
  53604. if (target instanceof BABYLON.Vector4)
  53605. return BABYLON.Vector4.FromArray(split);
  53606. if (target instanceof BABYLON.Color3)
  53607. return BABYLON.Color3.FromArray(split);
  53608. if (target instanceof BABYLON.Color4)
  53609. return BABYLON.Color4.FromArray(split);
  53610. return parseFloat(values[0]);
  53611. };
  53612. // traverse graph per trigger
  53613. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53614. if (combineArray === void 0) { combineArray = null; }
  53615. if (parsedAction.detached)
  53616. return;
  53617. var parameters = new Array();
  53618. var target = null;
  53619. var propertyPath = null;
  53620. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53621. // Parameters
  53622. if (parsedAction.type === 2)
  53623. parameters.push(actionManager);
  53624. else
  53625. parameters.push(trigger);
  53626. if (combine) {
  53627. var actions = new Array();
  53628. for (var j = 0; j < parsedAction.combine.length; j++) {
  53629. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53630. }
  53631. parameters.push(actions);
  53632. }
  53633. else {
  53634. for (var i = 0; i < parsedAction.properties.length; i++) {
  53635. var value = parsedAction.properties[i].value;
  53636. var name = parsedAction.properties[i].name;
  53637. var targetType = parsedAction.properties[i].targetType;
  53638. if (name === "target")
  53639. if (targetType !== null && targetType === "SceneProperties")
  53640. value = target = scene;
  53641. else
  53642. value = target = scene.getNodeByName(value);
  53643. else if (name === "parent")
  53644. value = scene.getNodeByName(value);
  53645. else if (name === "sound")
  53646. value = scene.getSoundByName(value);
  53647. else if (name !== "propertyPath") {
  53648. if (parsedAction.type === 2 && name === "operator")
  53649. value = BABYLON.ValueCondition[value];
  53650. else
  53651. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53652. }
  53653. else {
  53654. propertyPath = value;
  53655. }
  53656. parameters.push(value);
  53657. }
  53658. }
  53659. if (combineArray === null) {
  53660. parameters.push(condition);
  53661. }
  53662. else {
  53663. parameters.push(null);
  53664. }
  53665. // If interpolate value action
  53666. if (parsedAction.name === "InterpolateValueAction") {
  53667. var param = parameters[parameters.length - 2];
  53668. parameters[parameters.length - 1] = param;
  53669. parameters[parameters.length - 2] = condition;
  53670. }
  53671. // Action or condition(s) and not CombineAction
  53672. var newAction = instanciate(parsedAction.name, parameters);
  53673. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53674. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53675. if (action)
  53676. action.then(nothing);
  53677. else
  53678. actionManager.registerAction(nothing);
  53679. action = nothing;
  53680. }
  53681. if (combineArray === null) {
  53682. if (newAction instanceof BABYLON.Condition) {
  53683. condition = newAction;
  53684. newAction = action;
  53685. }
  53686. else {
  53687. condition = null;
  53688. if (action)
  53689. action.then(newAction);
  53690. else
  53691. actionManager.registerAction(newAction);
  53692. }
  53693. }
  53694. else {
  53695. combineArray.push(newAction);
  53696. }
  53697. for (var i = 0; i < parsedAction.children.length; i++)
  53698. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53699. };
  53700. // triggers
  53701. for (var i = 0; i < parsedActions.children.length; i++) {
  53702. var triggerParams;
  53703. var trigger = parsedActions.children[i];
  53704. if (trigger.properties.length > 0) {
  53705. var param = trigger.properties[0].value;
  53706. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53707. if (value._meshId) {
  53708. value.mesh = scene.getMeshByID(value._meshId);
  53709. }
  53710. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53711. }
  53712. else
  53713. triggerParams = ActionManager[trigger.name];
  53714. for (var j = 0; j < trigger.children.length; j++) {
  53715. if (!trigger.detached)
  53716. traverse(trigger.children[j], triggerParams, null, null);
  53717. }
  53718. }
  53719. };
  53720. /**
  53721. * Get a trigger name by index
  53722. * @param trigger defines the trigger index
  53723. * @returns a trigger name
  53724. */
  53725. ActionManager.GetTriggerName = function (trigger) {
  53726. switch (trigger) {
  53727. case 0: return "NothingTrigger";
  53728. case 1: return "OnPickTrigger";
  53729. case 2: return "OnLeftPickTrigger";
  53730. case 3: return "OnRightPickTrigger";
  53731. case 4: return "OnCenterPickTrigger";
  53732. case 5: return "OnPickDownTrigger";
  53733. case 6: return "OnPickUpTrigger";
  53734. case 7: return "OnLongPressTrigger";
  53735. case 8: return "OnPointerOverTrigger";
  53736. case 9: return "OnPointerOutTrigger";
  53737. case 10: return "OnEveryFrameTrigger";
  53738. case 11: return "OnIntersectionEnterTrigger";
  53739. case 12: return "OnIntersectionExitTrigger";
  53740. case 13: return "OnKeyDownTrigger";
  53741. case 14: return "OnKeyUpTrigger";
  53742. case 15: return "OnPickOutTrigger";
  53743. default: return "";
  53744. }
  53745. };
  53746. // Statics
  53747. ActionManager._NothingTrigger = 0;
  53748. ActionManager._OnPickTrigger = 1;
  53749. ActionManager._OnLeftPickTrigger = 2;
  53750. ActionManager._OnRightPickTrigger = 3;
  53751. ActionManager._OnCenterPickTrigger = 4;
  53752. ActionManager._OnPickDownTrigger = 5;
  53753. ActionManager._OnDoublePickTrigger = 6;
  53754. ActionManager._OnPickUpTrigger = 7;
  53755. ActionManager._OnLongPressTrigger = 8;
  53756. ActionManager._OnPointerOverTrigger = 9;
  53757. ActionManager._OnPointerOutTrigger = 10;
  53758. ActionManager._OnEveryFrameTrigger = 11;
  53759. ActionManager._OnIntersectionEnterTrigger = 12;
  53760. ActionManager._OnIntersectionExitTrigger = 13;
  53761. ActionManager._OnKeyDownTrigger = 14;
  53762. ActionManager._OnKeyUpTrigger = 15;
  53763. ActionManager._OnPickOutTrigger = 16;
  53764. /** Gets the list of active triggers */
  53765. ActionManager.Triggers = {};
  53766. return ActionManager;
  53767. }());
  53768. BABYLON.ActionManager = ActionManager;
  53769. })(BABYLON || (BABYLON = {}));
  53770. //# sourceMappingURL=babylon.actionManager.js.map
  53771. var BABYLON;
  53772. (function (BABYLON) {
  53773. var InterpolateValueAction = /** @class */ (function (_super) {
  53774. __extends(InterpolateValueAction, _super);
  53775. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53776. if (duration === void 0) { duration = 1000; }
  53777. var _this = _super.call(this, triggerOptions, condition) || this;
  53778. _this.propertyPath = propertyPath;
  53779. _this.value = value;
  53780. _this.duration = duration;
  53781. _this.stopOtherAnimations = stopOtherAnimations;
  53782. _this.onInterpolationDone = onInterpolationDone;
  53783. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53784. _this._target = _this._effectiveTarget = target;
  53785. return _this;
  53786. }
  53787. InterpolateValueAction.prototype._prepare = function () {
  53788. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53789. this._property = this._getProperty(this.propertyPath);
  53790. };
  53791. InterpolateValueAction.prototype.execute = function () {
  53792. var _this = this;
  53793. var scene = this._actionManager.getScene();
  53794. var keys = [
  53795. {
  53796. frame: 0,
  53797. value: this._effectiveTarget[this._property]
  53798. }, {
  53799. frame: 100,
  53800. value: this.value
  53801. }
  53802. ];
  53803. var dataType;
  53804. if (typeof this.value === "number") {
  53805. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53806. }
  53807. else if (this.value instanceof BABYLON.Color3) {
  53808. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53809. }
  53810. else if (this.value instanceof BABYLON.Vector3) {
  53811. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53812. }
  53813. else if (this.value instanceof BABYLON.Matrix) {
  53814. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53815. }
  53816. else if (this.value instanceof BABYLON.Quaternion) {
  53817. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53818. }
  53819. else {
  53820. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53821. return;
  53822. }
  53823. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53824. animation.setKeys(keys);
  53825. if (this.stopOtherAnimations) {
  53826. scene.stopAnimation(this._effectiveTarget);
  53827. }
  53828. var wrapper = function () {
  53829. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53830. if (_this.onInterpolationDone) {
  53831. _this.onInterpolationDone();
  53832. }
  53833. };
  53834. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53835. };
  53836. InterpolateValueAction.prototype.serialize = function (parent) {
  53837. return _super.prototype._serialize.call(this, {
  53838. name: "InterpolateValueAction",
  53839. properties: [
  53840. BABYLON.Action._GetTargetProperty(this._target),
  53841. { name: "propertyPath", value: this.propertyPath },
  53842. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53843. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53844. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53845. ]
  53846. }, parent);
  53847. };
  53848. return InterpolateValueAction;
  53849. }(BABYLON.Action));
  53850. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53851. })(BABYLON || (BABYLON = {}));
  53852. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53853. var BABYLON;
  53854. (function (BABYLON) {
  53855. var SwitchBooleanAction = /** @class */ (function (_super) {
  53856. __extends(SwitchBooleanAction, _super);
  53857. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53858. var _this = _super.call(this, triggerOptions, condition) || this;
  53859. _this.propertyPath = propertyPath;
  53860. _this._target = _this._effectiveTarget = target;
  53861. return _this;
  53862. }
  53863. SwitchBooleanAction.prototype._prepare = function () {
  53864. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53865. this._property = this._getProperty(this.propertyPath);
  53866. };
  53867. SwitchBooleanAction.prototype.execute = function () {
  53868. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53869. };
  53870. SwitchBooleanAction.prototype.serialize = function (parent) {
  53871. return _super.prototype._serialize.call(this, {
  53872. name: "SwitchBooleanAction",
  53873. properties: [
  53874. BABYLON.Action._GetTargetProperty(this._target),
  53875. { name: "propertyPath", value: this.propertyPath }
  53876. ]
  53877. }, parent);
  53878. };
  53879. return SwitchBooleanAction;
  53880. }(BABYLON.Action));
  53881. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53882. var SetStateAction = /** @class */ (function (_super) {
  53883. __extends(SetStateAction, _super);
  53884. function SetStateAction(triggerOptions, target, value, condition) {
  53885. var _this = _super.call(this, triggerOptions, condition) || this;
  53886. _this.value = value;
  53887. _this._target = target;
  53888. return _this;
  53889. }
  53890. SetStateAction.prototype.execute = function () {
  53891. this._target.state = this.value;
  53892. };
  53893. SetStateAction.prototype.serialize = function (parent) {
  53894. return _super.prototype._serialize.call(this, {
  53895. name: "SetStateAction",
  53896. properties: [
  53897. BABYLON.Action._GetTargetProperty(this._target),
  53898. { name: "value", value: this.value }
  53899. ]
  53900. }, parent);
  53901. };
  53902. return SetStateAction;
  53903. }(BABYLON.Action));
  53904. BABYLON.SetStateAction = SetStateAction;
  53905. var SetValueAction = /** @class */ (function (_super) {
  53906. __extends(SetValueAction, _super);
  53907. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53908. var _this = _super.call(this, triggerOptions, condition) || this;
  53909. _this.propertyPath = propertyPath;
  53910. _this.value = value;
  53911. _this._target = _this._effectiveTarget = target;
  53912. return _this;
  53913. }
  53914. SetValueAction.prototype._prepare = function () {
  53915. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53916. this._property = this._getProperty(this.propertyPath);
  53917. };
  53918. SetValueAction.prototype.execute = function () {
  53919. this._effectiveTarget[this._property] = this.value;
  53920. if (this._target.markAsDirty) {
  53921. this._target.markAsDirty(this._property);
  53922. }
  53923. };
  53924. SetValueAction.prototype.serialize = function (parent) {
  53925. return _super.prototype._serialize.call(this, {
  53926. name: "SetValueAction",
  53927. properties: [
  53928. BABYLON.Action._GetTargetProperty(this._target),
  53929. { name: "propertyPath", value: this.propertyPath },
  53930. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53931. ]
  53932. }, parent);
  53933. };
  53934. return SetValueAction;
  53935. }(BABYLON.Action));
  53936. BABYLON.SetValueAction = SetValueAction;
  53937. var IncrementValueAction = /** @class */ (function (_super) {
  53938. __extends(IncrementValueAction, _super);
  53939. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53940. var _this = _super.call(this, triggerOptions, condition) || this;
  53941. _this.propertyPath = propertyPath;
  53942. _this.value = value;
  53943. _this._target = _this._effectiveTarget = target;
  53944. return _this;
  53945. }
  53946. IncrementValueAction.prototype._prepare = function () {
  53947. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53948. this._property = this._getProperty(this.propertyPath);
  53949. if (typeof this._effectiveTarget[this._property] !== "number") {
  53950. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53951. }
  53952. };
  53953. IncrementValueAction.prototype.execute = function () {
  53954. this._effectiveTarget[this._property] += this.value;
  53955. if (this._target.markAsDirty) {
  53956. this._target.markAsDirty(this._property);
  53957. }
  53958. };
  53959. IncrementValueAction.prototype.serialize = function (parent) {
  53960. return _super.prototype._serialize.call(this, {
  53961. name: "IncrementValueAction",
  53962. properties: [
  53963. BABYLON.Action._GetTargetProperty(this._target),
  53964. { name: "propertyPath", value: this.propertyPath },
  53965. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53966. ]
  53967. }, parent);
  53968. };
  53969. return IncrementValueAction;
  53970. }(BABYLON.Action));
  53971. BABYLON.IncrementValueAction = IncrementValueAction;
  53972. var PlayAnimationAction = /** @class */ (function (_super) {
  53973. __extends(PlayAnimationAction, _super);
  53974. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53975. var _this = _super.call(this, triggerOptions, condition) || this;
  53976. _this.from = from;
  53977. _this.to = to;
  53978. _this.loop = loop;
  53979. _this._target = target;
  53980. return _this;
  53981. }
  53982. PlayAnimationAction.prototype._prepare = function () {
  53983. };
  53984. PlayAnimationAction.prototype.execute = function () {
  53985. var scene = this._actionManager.getScene();
  53986. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53987. };
  53988. PlayAnimationAction.prototype.serialize = function (parent) {
  53989. return _super.prototype._serialize.call(this, {
  53990. name: "PlayAnimationAction",
  53991. properties: [
  53992. BABYLON.Action._GetTargetProperty(this._target),
  53993. { name: "from", value: String(this.from) },
  53994. { name: "to", value: String(this.to) },
  53995. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53996. ]
  53997. }, parent);
  53998. };
  53999. return PlayAnimationAction;
  54000. }(BABYLON.Action));
  54001. BABYLON.PlayAnimationAction = PlayAnimationAction;
  54002. var StopAnimationAction = /** @class */ (function (_super) {
  54003. __extends(StopAnimationAction, _super);
  54004. function StopAnimationAction(triggerOptions, target, condition) {
  54005. var _this = _super.call(this, triggerOptions, condition) || this;
  54006. _this._target = target;
  54007. return _this;
  54008. }
  54009. StopAnimationAction.prototype._prepare = function () {
  54010. };
  54011. StopAnimationAction.prototype.execute = function () {
  54012. var scene = this._actionManager.getScene();
  54013. scene.stopAnimation(this._target);
  54014. };
  54015. StopAnimationAction.prototype.serialize = function (parent) {
  54016. return _super.prototype._serialize.call(this, {
  54017. name: "StopAnimationAction",
  54018. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54019. }, parent);
  54020. };
  54021. return StopAnimationAction;
  54022. }(BABYLON.Action));
  54023. BABYLON.StopAnimationAction = StopAnimationAction;
  54024. var DoNothingAction = /** @class */ (function (_super) {
  54025. __extends(DoNothingAction, _super);
  54026. function DoNothingAction(triggerOptions, condition) {
  54027. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54028. return _super.call(this, triggerOptions, condition) || this;
  54029. }
  54030. DoNothingAction.prototype.execute = function () {
  54031. };
  54032. DoNothingAction.prototype.serialize = function (parent) {
  54033. return _super.prototype._serialize.call(this, {
  54034. name: "DoNothingAction",
  54035. properties: []
  54036. }, parent);
  54037. };
  54038. return DoNothingAction;
  54039. }(BABYLON.Action));
  54040. BABYLON.DoNothingAction = DoNothingAction;
  54041. var CombineAction = /** @class */ (function (_super) {
  54042. __extends(CombineAction, _super);
  54043. function CombineAction(triggerOptions, children, condition) {
  54044. var _this = _super.call(this, triggerOptions, condition) || this;
  54045. _this.children = children;
  54046. return _this;
  54047. }
  54048. CombineAction.prototype._prepare = function () {
  54049. for (var index = 0; index < this.children.length; index++) {
  54050. this.children[index]._actionManager = this._actionManager;
  54051. this.children[index]._prepare();
  54052. }
  54053. };
  54054. CombineAction.prototype.execute = function (evt) {
  54055. for (var index = 0; index < this.children.length; index++) {
  54056. this.children[index].execute(evt);
  54057. }
  54058. };
  54059. CombineAction.prototype.serialize = function (parent) {
  54060. var serializationObject = _super.prototype._serialize.call(this, {
  54061. name: "CombineAction",
  54062. properties: [],
  54063. combine: []
  54064. }, parent);
  54065. for (var i = 0; i < this.children.length; i++) {
  54066. serializationObject.combine.push(this.children[i].serialize(null));
  54067. }
  54068. return serializationObject;
  54069. };
  54070. return CombineAction;
  54071. }(BABYLON.Action));
  54072. BABYLON.CombineAction = CombineAction;
  54073. var ExecuteCodeAction = /** @class */ (function (_super) {
  54074. __extends(ExecuteCodeAction, _super);
  54075. function ExecuteCodeAction(triggerOptions, func, condition) {
  54076. var _this = _super.call(this, triggerOptions, condition) || this;
  54077. _this.func = func;
  54078. return _this;
  54079. }
  54080. ExecuteCodeAction.prototype.execute = function (evt) {
  54081. this.func(evt);
  54082. };
  54083. return ExecuteCodeAction;
  54084. }(BABYLON.Action));
  54085. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54086. var SetParentAction = /** @class */ (function (_super) {
  54087. __extends(SetParentAction, _super);
  54088. function SetParentAction(triggerOptions, target, parent, condition) {
  54089. var _this = _super.call(this, triggerOptions, condition) || this;
  54090. _this._target = target;
  54091. _this._parent = parent;
  54092. return _this;
  54093. }
  54094. SetParentAction.prototype._prepare = function () {
  54095. };
  54096. SetParentAction.prototype.execute = function () {
  54097. if (this._target.parent === this._parent) {
  54098. return;
  54099. }
  54100. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54101. invertParentWorldMatrix.invert();
  54102. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54103. this._target.parent = this._parent;
  54104. };
  54105. SetParentAction.prototype.serialize = function (parent) {
  54106. return _super.prototype._serialize.call(this, {
  54107. name: "SetParentAction",
  54108. properties: [
  54109. BABYLON.Action._GetTargetProperty(this._target),
  54110. BABYLON.Action._GetTargetProperty(this._parent),
  54111. ]
  54112. }, parent);
  54113. };
  54114. return SetParentAction;
  54115. }(BABYLON.Action));
  54116. BABYLON.SetParentAction = SetParentAction;
  54117. var PlaySoundAction = /** @class */ (function (_super) {
  54118. __extends(PlaySoundAction, _super);
  54119. function PlaySoundAction(triggerOptions, sound, condition) {
  54120. var _this = _super.call(this, triggerOptions, condition) || this;
  54121. _this._sound = sound;
  54122. return _this;
  54123. }
  54124. PlaySoundAction.prototype._prepare = function () {
  54125. };
  54126. PlaySoundAction.prototype.execute = function () {
  54127. if (this._sound !== undefined)
  54128. this._sound.play();
  54129. };
  54130. PlaySoundAction.prototype.serialize = function (parent) {
  54131. return _super.prototype._serialize.call(this, {
  54132. name: "PlaySoundAction",
  54133. properties: [{ name: "sound", value: this._sound.name }]
  54134. }, parent);
  54135. };
  54136. return PlaySoundAction;
  54137. }(BABYLON.Action));
  54138. BABYLON.PlaySoundAction = PlaySoundAction;
  54139. var StopSoundAction = /** @class */ (function (_super) {
  54140. __extends(StopSoundAction, _super);
  54141. function StopSoundAction(triggerOptions, sound, condition) {
  54142. var _this = _super.call(this, triggerOptions, condition) || this;
  54143. _this._sound = sound;
  54144. return _this;
  54145. }
  54146. StopSoundAction.prototype._prepare = function () {
  54147. };
  54148. StopSoundAction.prototype.execute = function () {
  54149. if (this._sound !== undefined)
  54150. this._sound.stop();
  54151. };
  54152. StopSoundAction.prototype.serialize = function (parent) {
  54153. return _super.prototype._serialize.call(this, {
  54154. name: "StopSoundAction",
  54155. properties: [{ name: "sound", value: this._sound.name }]
  54156. }, parent);
  54157. };
  54158. return StopSoundAction;
  54159. }(BABYLON.Action));
  54160. BABYLON.StopSoundAction = StopSoundAction;
  54161. })(BABYLON || (BABYLON = {}));
  54162. //# sourceMappingURL=babylon.directActions.js.map
  54163. var BABYLON;
  54164. (function (BABYLON) {
  54165. var SpriteManager = /** @class */ (function () {
  54166. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54167. if (epsilon === void 0) { epsilon = 0.01; }
  54168. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54169. this.name = name;
  54170. this.sprites = new Array();
  54171. this.renderingGroupId = 0;
  54172. this.layerMask = 0x0FFFFFFF;
  54173. this.fogEnabled = true;
  54174. this.isPickable = false;
  54175. /**
  54176. * An event triggered when the manager is disposed.
  54177. */
  54178. this.onDisposeObservable = new BABYLON.Observable();
  54179. this._vertexBuffers = {};
  54180. this._capacity = capacity;
  54181. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54182. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54183. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54184. if (cellSize.width && cellSize.height) {
  54185. this.cellWidth = cellSize.width;
  54186. this.cellHeight = cellSize.height;
  54187. }
  54188. else if (cellSize !== undefined) {
  54189. this.cellWidth = cellSize;
  54190. this.cellHeight = cellSize;
  54191. }
  54192. else {
  54193. return;
  54194. }
  54195. this._epsilon = epsilon;
  54196. this._scene = scene;
  54197. this._scene.spriteManagers.push(this);
  54198. var indices = [];
  54199. var index = 0;
  54200. for (var count = 0; count < capacity; count++) {
  54201. indices.push(index);
  54202. indices.push(index + 1);
  54203. indices.push(index + 2);
  54204. indices.push(index);
  54205. indices.push(index + 2);
  54206. indices.push(index + 3);
  54207. index += 4;
  54208. }
  54209. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54210. // VBO
  54211. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54212. this._vertexData = new Float32Array(capacity * 16 * 4);
  54213. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54214. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54215. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54216. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54217. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54218. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54219. this._vertexBuffers["options"] = options;
  54220. this._vertexBuffers["cellInfo"] = cellInfo;
  54221. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54222. // Effects
  54223. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54224. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54225. }
  54226. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54227. set: function (callback) {
  54228. if (this._onDisposeObserver) {
  54229. this.onDisposeObservable.remove(this._onDisposeObserver);
  54230. }
  54231. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54232. },
  54233. enumerable: true,
  54234. configurable: true
  54235. });
  54236. Object.defineProperty(SpriteManager.prototype, "texture", {
  54237. get: function () {
  54238. return this._spriteTexture;
  54239. },
  54240. set: function (value) {
  54241. this._spriteTexture = value;
  54242. },
  54243. enumerable: true,
  54244. configurable: true
  54245. });
  54246. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54247. var arrayOffset = index * 16;
  54248. if (offsetX === 0)
  54249. offsetX = this._epsilon;
  54250. else if (offsetX === 1)
  54251. offsetX = 1 - this._epsilon;
  54252. if (offsetY === 0)
  54253. offsetY = this._epsilon;
  54254. else if (offsetY === 1)
  54255. offsetY = 1 - this._epsilon;
  54256. this._vertexData[arrayOffset] = sprite.position.x;
  54257. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54258. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54259. this._vertexData[arrayOffset + 3] = sprite.angle;
  54260. this._vertexData[arrayOffset + 4] = sprite.width;
  54261. this._vertexData[arrayOffset + 5] = sprite.height;
  54262. this._vertexData[arrayOffset + 6] = offsetX;
  54263. this._vertexData[arrayOffset + 7] = offsetY;
  54264. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54265. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54266. var offset = (sprite.cellIndex / rowSize) >> 0;
  54267. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54268. this._vertexData[arrayOffset + 11] = offset;
  54269. // Color
  54270. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54271. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54272. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54273. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54274. };
  54275. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54276. var count = Math.min(this._capacity, this.sprites.length);
  54277. var min = BABYLON.Vector3.Zero();
  54278. var max = BABYLON.Vector3.Zero();
  54279. var distance = Number.MAX_VALUE;
  54280. var currentSprite = null;
  54281. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54282. var cameraView = camera.getViewMatrix();
  54283. for (var index = 0; index < count; index++) {
  54284. var sprite = this.sprites[index];
  54285. if (!sprite) {
  54286. continue;
  54287. }
  54288. if (predicate) {
  54289. if (!predicate(sprite)) {
  54290. continue;
  54291. }
  54292. }
  54293. else if (!sprite.isPickable) {
  54294. continue;
  54295. }
  54296. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54297. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54298. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54299. if (ray.intersectsBoxMinMax(min, max)) {
  54300. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54301. if (distance > currentDistance) {
  54302. distance = currentDistance;
  54303. currentSprite = sprite;
  54304. if (fastCheck) {
  54305. break;
  54306. }
  54307. }
  54308. }
  54309. }
  54310. if (currentSprite) {
  54311. var result = new BABYLON.PickingInfo();
  54312. result.hit = true;
  54313. result.pickedSprite = currentSprite;
  54314. result.distance = distance;
  54315. return result;
  54316. }
  54317. return null;
  54318. };
  54319. SpriteManager.prototype.render = function () {
  54320. // Check
  54321. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54322. return;
  54323. var engine = this._scene.getEngine();
  54324. var baseSize = this._spriteTexture.getBaseSize();
  54325. // Sprites
  54326. var deltaTime = engine.getDeltaTime();
  54327. var max = Math.min(this._capacity, this.sprites.length);
  54328. var rowSize = baseSize.width / this.cellWidth;
  54329. var offset = 0;
  54330. for (var index = 0; index < max; index++) {
  54331. var sprite = this.sprites[index];
  54332. if (!sprite) {
  54333. continue;
  54334. }
  54335. sprite._animate(deltaTime);
  54336. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54337. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54338. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54339. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54340. }
  54341. this._buffer.update(this._vertexData);
  54342. // Render
  54343. var effect = this._effectBase;
  54344. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54345. effect = this._effectFog;
  54346. }
  54347. engine.enableEffect(effect);
  54348. var viewMatrix = this._scene.getViewMatrix();
  54349. effect.setTexture("diffuseSampler", this._spriteTexture);
  54350. effect.setMatrix("view", viewMatrix);
  54351. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54352. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54353. // Fog
  54354. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54355. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54356. effect.setColor3("vFogColor", this._scene.fogColor);
  54357. }
  54358. // VBOs
  54359. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54360. // Draw order
  54361. engine.setDepthFunctionToLessOrEqual();
  54362. effect.setBool("alphaTest", true);
  54363. engine.setColorWrite(false);
  54364. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54365. engine.setColorWrite(true);
  54366. effect.setBool("alphaTest", false);
  54367. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54368. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54369. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54370. };
  54371. SpriteManager.prototype.dispose = function () {
  54372. if (this._buffer) {
  54373. this._buffer.dispose();
  54374. this._buffer = null;
  54375. }
  54376. if (this._indexBuffer) {
  54377. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54378. this._indexBuffer = null;
  54379. }
  54380. if (this._spriteTexture) {
  54381. this._spriteTexture.dispose();
  54382. this._spriteTexture = null;
  54383. }
  54384. // Remove from scene
  54385. var index = this._scene.spriteManagers.indexOf(this);
  54386. this._scene.spriteManagers.splice(index, 1);
  54387. // Callback
  54388. this.onDisposeObservable.notifyObservers(this);
  54389. this.onDisposeObservable.clear();
  54390. };
  54391. return SpriteManager;
  54392. }());
  54393. BABYLON.SpriteManager = SpriteManager;
  54394. })(BABYLON || (BABYLON = {}));
  54395. //# sourceMappingURL=babylon.spriteManager.js.map
  54396. var BABYLON;
  54397. (function (BABYLON) {
  54398. var Sprite = /** @class */ (function () {
  54399. function Sprite(name, manager) {
  54400. this.name = name;
  54401. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54402. this.width = 1.0;
  54403. this.height = 1.0;
  54404. this.angle = 0;
  54405. this.cellIndex = 0;
  54406. this.invertU = 0;
  54407. this.invertV = 0;
  54408. this.animations = new Array();
  54409. this.isPickable = false;
  54410. this._animationStarted = false;
  54411. this._loopAnimation = false;
  54412. this._fromIndex = 0;
  54413. this._toIndex = 0;
  54414. this._delay = 0;
  54415. this._direction = 1;
  54416. this._time = 0;
  54417. this._manager = manager;
  54418. this._manager.sprites.push(this);
  54419. this.position = BABYLON.Vector3.Zero();
  54420. }
  54421. Object.defineProperty(Sprite.prototype, "size", {
  54422. get: function () {
  54423. return this.width;
  54424. },
  54425. set: function (value) {
  54426. this.width = value;
  54427. this.height = value;
  54428. },
  54429. enumerable: true,
  54430. configurable: true
  54431. });
  54432. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54433. this._fromIndex = from;
  54434. this._toIndex = to;
  54435. this._loopAnimation = loop;
  54436. this._delay = delay;
  54437. this._animationStarted = true;
  54438. this._direction = from < to ? 1 : -1;
  54439. this.cellIndex = from;
  54440. this._time = 0;
  54441. this._onAnimationEnd = onAnimationEnd;
  54442. };
  54443. Sprite.prototype.stopAnimation = function () {
  54444. this._animationStarted = false;
  54445. };
  54446. Sprite.prototype._animate = function (deltaTime) {
  54447. if (!this._animationStarted)
  54448. return;
  54449. this._time += deltaTime;
  54450. if (this._time > this._delay) {
  54451. this._time = this._time % this._delay;
  54452. this.cellIndex += this._direction;
  54453. if (this.cellIndex > this._toIndex) {
  54454. if (this._loopAnimation) {
  54455. this.cellIndex = this._fromIndex;
  54456. }
  54457. else {
  54458. this.cellIndex = this._toIndex;
  54459. this._animationStarted = false;
  54460. if (this._onAnimationEnd) {
  54461. this._onAnimationEnd();
  54462. }
  54463. if (this.disposeWhenFinishedAnimating) {
  54464. this.dispose();
  54465. }
  54466. }
  54467. }
  54468. }
  54469. };
  54470. Sprite.prototype.dispose = function () {
  54471. for (var i = 0; i < this._manager.sprites.length; i++) {
  54472. if (this._manager.sprites[i] == this) {
  54473. this._manager.sprites.splice(i, 1);
  54474. }
  54475. }
  54476. };
  54477. return Sprite;
  54478. }());
  54479. BABYLON.Sprite = Sprite;
  54480. })(BABYLON || (BABYLON = {}));
  54481. //# sourceMappingURL=babylon.sprite.js.map
  54482. var BABYLON;
  54483. (function (BABYLON) {
  54484. var IntersectionInfo = /** @class */ (function () {
  54485. function IntersectionInfo(bu, bv, distance) {
  54486. this.bu = bu;
  54487. this.bv = bv;
  54488. this.distance = distance;
  54489. this.faceId = 0;
  54490. this.subMeshId = 0;
  54491. }
  54492. return IntersectionInfo;
  54493. }());
  54494. BABYLON.IntersectionInfo = IntersectionInfo;
  54495. var PickingInfo = /** @class */ (function () {
  54496. function PickingInfo() {
  54497. this.hit = false;
  54498. this.distance = 0;
  54499. this.pickedPoint = null;
  54500. this.pickedMesh = null;
  54501. this.bu = 0;
  54502. this.bv = 0;
  54503. this.faceId = -1;
  54504. this.subMeshId = 0;
  54505. this.pickedSprite = null;
  54506. }
  54507. // Methods
  54508. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54509. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54510. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54511. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54512. return null;
  54513. }
  54514. var indices = this.pickedMesh.getIndices();
  54515. if (!indices) {
  54516. return null;
  54517. }
  54518. var result;
  54519. if (useVerticesNormals) {
  54520. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54521. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54522. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54523. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54524. normal0 = normal0.scale(this.bu);
  54525. normal1 = normal1.scale(this.bv);
  54526. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54527. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54528. }
  54529. else {
  54530. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54531. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54532. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54533. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54534. var p1p2 = vertex1.subtract(vertex2);
  54535. var p3p2 = vertex3.subtract(vertex2);
  54536. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54537. }
  54538. if (useWorldCoordinates) {
  54539. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  54540. }
  54541. return BABYLON.Vector3.Normalize(result);
  54542. };
  54543. PickingInfo.prototype.getTextureCoordinates = function () {
  54544. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54545. return null;
  54546. }
  54547. var indices = this.pickedMesh.getIndices();
  54548. if (!indices) {
  54549. return null;
  54550. }
  54551. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54552. if (!uvs) {
  54553. return null;
  54554. }
  54555. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54556. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54557. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54558. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54559. uv1 = uv1.scale(this.bu);
  54560. uv2 = uv2.scale(this.bv);
  54561. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54562. };
  54563. return PickingInfo;
  54564. }());
  54565. BABYLON.PickingInfo = PickingInfo;
  54566. })(BABYLON || (BABYLON = {}));
  54567. //# sourceMappingURL=babylon.pickingInfo.js.map
  54568. var BABYLON;
  54569. (function (BABYLON) {
  54570. var Ray = /** @class */ (function () {
  54571. function Ray(origin, direction, length) {
  54572. if (length === void 0) { length = Number.MAX_VALUE; }
  54573. this.origin = origin;
  54574. this.direction = direction;
  54575. this.length = length;
  54576. }
  54577. // Methods
  54578. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54579. var d = 0.0;
  54580. var maxValue = Number.MAX_VALUE;
  54581. var inv;
  54582. var min;
  54583. var max;
  54584. var temp;
  54585. if (Math.abs(this.direction.x) < 0.0000001) {
  54586. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54587. return false;
  54588. }
  54589. }
  54590. else {
  54591. inv = 1.0 / this.direction.x;
  54592. min = (minimum.x - this.origin.x) * inv;
  54593. max = (maximum.x - this.origin.x) * inv;
  54594. if (max === -Infinity) {
  54595. max = Infinity;
  54596. }
  54597. if (min > max) {
  54598. temp = min;
  54599. min = max;
  54600. max = temp;
  54601. }
  54602. d = Math.max(min, d);
  54603. maxValue = Math.min(max, maxValue);
  54604. if (d > maxValue) {
  54605. return false;
  54606. }
  54607. }
  54608. if (Math.abs(this.direction.y) < 0.0000001) {
  54609. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54610. return false;
  54611. }
  54612. }
  54613. else {
  54614. inv = 1.0 / this.direction.y;
  54615. min = (minimum.y - this.origin.y) * inv;
  54616. max = (maximum.y - this.origin.y) * inv;
  54617. if (max === -Infinity) {
  54618. max = Infinity;
  54619. }
  54620. if (min > max) {
  54621. temp = min;
  54622. min = max;
  54623. max = temp;
  54624. }
  54625. d = Math.max(min, d);
  54626. maxValue = Math.min(max, maxValue);
  54627. if (d > maxValue) {
  54628. return false;
  54629. }
  54630. }
  54631. if (Math.abs(this.direction.z) < 0.0000001) {
  54632. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54633. return false;
  54634. }
  54635. }
  54636. else {
  54637. inv = 1.0 / this.direction.z;
  54638. min = (minimum.z - this.origin.z) * inv;
  54639. max = (maximum.z - this.origin.z) * inv;
  54640. if (max === -Infinity) {
  54641. max = Infinity;
  54642. }
  54643. if (min > max) {
  54644. temp = min;
  54645. min = max;
  54646. max = temp;
  54647. }
  54648. d = Math.max(min, d);
  54649. maxValue = Math.min(max, maxValue);
  54650. if (d > maxValue) {
  54651. return false;
  54652. }
  54653. }
  54654. return true;
  54655. };
  54656. Ray.prototype.intersectsBox = function (box) {
  54657. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54658. };
  54659. Ray.prototype.intersectsSphere = function (sphere) {
  54660. var x = sphere.center.x - this.origin.x;
  54661. var y = sphere.center.y - this.origin.y;
  54662. var z = sphere.center.z - this.origin.z;
  54663. var pyth = (x * x) + (y * y) + (z * z);
  54664. var rr = sphere.radius * sphere.radius;
  54665. if (pyth <= rr) {
  54666. return true;
  54667. }
  54668. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54669. if (dot < 0.0) {
  54670. return false;
  54671. }
  54672. var temp = pyth - (dot * dot);
  54673. return temp <= rr;
  54674. };
  54675. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54676. if (!this._edge1) {
  54677. this._edge1 = BABYLON.Vector3.Zero();
  54678. this._edge2 = BABYLON.Vector3.Zero();
  54679. this._pvec = BABYLON.Vector3.Zero();
  54680. this._tvec = BABYLON.Vector3.Zero();
  54681. this._qvec = BABYLON.Vector3.Zero();
  54682. }
  54683. vertex1.subtractToRef(vertex0, this._edge1);
  54684. vertex2.subtractToRef(vertex0, this._edge2);
  54685. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54686. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54687. if (det === 0) {
  54688. return null;
  54689. }
  54690. var invdet = 1 / det;
  54691. this.origin.subtractToRef(vertex0, this._tvec);
  54692. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54693. if (bu < 0 || bu > 1.0) {
  54694. return null;
  54695. }
  54696. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54697. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54698. if (bv < 0 || bu + bv > 1.0) {
  54699. return null;
  54700. }
  54701. //check if the distance is longer than the predefined length.
  54702. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54703. if (distance > this.length) {
  54704. return null;
  54705. }
  54706. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54707. };
  54708. Ray.prototype.intersectsPlane = function (plane) {
  54709. var distance;
  54710. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54711. if (Math.abs(result1) < 9.99999997475243E-07) {
  54712. return null;
  54713. }
  54714. else {
  54715. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54716. distance = (-plane.d - result2) / result1;
  54717. if (distance < 0.0) {
  54718. if (distance < -9.99999997475243E-07) {
  54719. return null;
  54720. }
  54721. else {
  54722. return 0;
  54723. }
  54724. }
  54725. return distance;
  54726. }
  54727. };
  54728. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54729. var tm = BABYLON.Tmp.Matrix[0];
  54730. mesh.getWorldMatrix().invertToRef(tm);
  54731. if (this._tmpRay) {
  54732. Ray.TransformToRef(this, tm, this._tmpRay);
  54733. }
  54734. else {
  54735. this._tmpRay = Ray.Transform(this, tm);
  54736. }
  54737. return mesh.intersects(this._tmpRay, fastCheck);
  54738. };
  54739. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54740. if (results) {
  54741. results.length = 0;
  54742. }
  54743. else {
  54744. results = [];
  54745. }
  54746. for (var i = 0; i < meshes.length; i++) {
  54747. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54748. if (pickInfo.hit) {
  54749. results.push(pickInfo);
  54750. }
  54751. }
  54752. results.sort(this._comparePickingInfo);
  54753. return results;
  54754. };
  54755. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54756. if (pickingInfoA.distance < pickingInfoB.distance) {
  54757. return -1;
  54758. }
  54759. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54760. return 1;
  54761. }
  54762. else {
  54763. return 0;
  54764. }
  54765. };
  54766. /**
  54767. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54768. * @param sega the first point of the segment to test the intersection against
  54769. * @param segb the second point of the segment to test the intersection against
  54770. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54771. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54772. */
  54773. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54774. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54775. var u = segb.subtract(sega);
  54776. var v = rsegb.subtract(this.origin);
  54777. var w = sega.subtract(this.origin);
  54778. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54779. var b = BABYLON.Vector3.Dot(u, v);
  54780. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54781. var d = BABYLON.Vector3.Dot(u, w);
  54782. var e = BABYLON.Vector3.Dot(v, w);
  54783. var D = a * c - b * b; // always >= 0
  54784. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54785. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54786. // compute the line parameters of the two closest points
  54787. if (D < Ray.smallnum) { // the lines are almost parallel
  54788. sN = 0.0; // force using point P0 on segment S1
  54789. sD = 1.0; // to prevent possible division by 0.0 later
  54790. tN = e;
  54791. tD = c;
  54792. }
  54793. else { // get the closest points on the infinite lines
  54794. sN = (b * e - c * d);
  54795. tN = (a * e - b * d);
  54796. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54797. sN = 0.0;
  54798. tN = e;
  54799. tD = c;
  54800. }
  54801. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54802. sN = sD;
  54803. tN = e + b;
  54804. tD = c;
  54805. }
  54806. }
  54807. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54808. tN = 0.0;
  54809. // recompute sc for this edge
  54810. if (-d < 0.0) {
  54811. sN = 0.0;
  54812. }
  54813. else if (-d > a)
  54814. sN = sD;
  54815. else {
  54816. sN = -d;
  54817. sD = a;
  54818. }
  54819. }
  54820. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54821. tN = tD;
  54822. // recompute sc for this edge
  54823. if ((-d + b) < 0.0) {
  54824. sN = 0;
  54825. }
  54826. else if ((-d + b) > a) {
  54827. sN = sD;
  54828. }
  54829. else {
  54830. sN = (-d + b);
  54831. sD = a;
  54832. }
  54833. }
  54834. // finally do the division to get sc and tc
  54835. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54836. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54837. // get the difference of the two closest points
  54838. var qtc = v.multiplyByFloats(tc, tc, tc);
  54839. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54840. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54841. if (isIntersected) {
  54842. return qtc.length();
  54843. }
  54844. return -1;
  54845. };
  54846. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54847. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54848. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54849. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54850. this.direction.normalize();
  54851. return this;
  54852. };
  54853. // Statics
  54854. Ray.Zero = function () {
  54855. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54856. };
  54857. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54858. var result = Ray.Zero();
  54859. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54860. };
  54861. /**
  54862. * 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
  54863. * transformed to the given world matrix.
  54864. * @param origin The origin point
  54865. * @param end The end point
  54866. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54867. */
  54868. Ray.CreateNewFromTo = function (origin, end, world) {
  54869. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54870. var direction = end.subtract(origin);
  54871. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54872. direction.normalize();
  54873. return Ray.Transform(new Ray(origin, direction, length), world);
  54874. };
  54875. Ray.Transform = function (ray, matrix) {
  54876. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54877. Ray.TransformToRef(ray, matrix, result);
  54878. return result;
  54879. };
  54880. Ray.TransformToRef = function (ray, matrix, result) {
  54881. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54882. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54883. result.length = ray.length;
  54884. var dir = result.direction;
  54885. var len = dir.length();
  54886. if (!(len === 0 || len === 1)) {
  54887. var num = 1.0 / len;
  54888. dir.x *= num;
  54889. dir.y *= num;
  54890. dir.z *= num;
  54891. result.length *= len;
  54892. }
  54893. };
  54894. Ray.smallnum = 0.00000001;
  54895. Ray.rayl = 10e8;
  54896. return Ray;
  54897. }());
  54898. BABYLON.Ray = Ray;
  54899. })(BABYLON || (BABYLON = {}));
  54900. //# sourceMappingURL=babylon.ray.js.map
  54901. var BABYLON;
  54902. (function (BABYLON) {
  54903. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54904. if (boxMin.x > sphereCenter.x + sphereRadius)
  54905. return false;
  54906. if (sphereCenter.x - sphereRadius > boxMax.x)
  54907. return false;
  54908. if (boxMin.y > sphereCenter.y + sphereRadius)
  54909. return false;
  54910. if (sphereCenter.y - sphereRadius > boxMax.y)
  54911. return false;
  54912. if (boxMin.z > sphereCenter.z + sphereRadius)
  54913. return false;
  54914. if (sphereCenter.z - sphereRadius > boxMax.z)
  54915. return false;
  54916. return true;
  54917. };
  54918. var getLowestRoot = (function () {
  54919. var result = { root: 0, found: false };
  54920. return function (a, b, c, maxR) {
  54921. result.root = 0;
  54922. result.found = false;
  54923. var determinant = b * b - 4.0 * a * c;
  54924. if (determinant < 0)
  54925. return result;
  54926. var sqrtD = Math.sqrt(determinant);
  54927. var r1 = (-b - sqrtD) / (2.0 * a);
  54928. var r2 = (-b + sqrtD) / (2.0 * a);
  54929. if (r1 > r2) {
  54930. var temp = r2;
  54931. r2 = r1;
  54932. r1 = temp;
  54933. }
  54934. if (r1 > 0 && r1 < maxR) {
  54935. result.root = r1;
  54936. result.found = true;
  54937. return result;
  54938. }
  54939. if (r2 > 0 && r2 < maxR) {
  54940. result.root = r2;
  54941. result.found = true;
  54942. return result;
  54943. }
  54944. return result;
  54945. };
  54946. })();
  54947. var Collider = /** @class */ (function () {
  54948. function Collider() {
  54949. this._collisionPoint = BABYLON.Vector3.Zero();
  54950. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54951. this._tempVector = BABYLON.Vector3.Zero();
  54952. this._tempVector2 = BABYLON.Vector3.Zero();
  54953. this._tempVector3 = BABYLON.Vector3.Zero();
  54954. this._tempVector4 = BABYLON.Vector3.Zero();
  54955. this._edge = BABYLON.Vector3.Zero();
  54956. this._baseToVertex = BABYLON.Vector3.Zero();
  54957. this._destinationPoint = BABYLON.Vector3.Zero();
  54958. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54959. this._displacementVector = BABYLON.Vector3.Zero();
  54960. this._radius = BABYLON.Vector3.One();
  54961. this._retry = 0;
  54962. this._basePointWorld = BABYLON.Vector3.Zero();
  54963. this._velocityWorld = BABYLON.Vector3.Zero();
  54964. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54965. this._collisionMask = -1;
  54966. }
  54967. Object.defineProperty(Collider.prototype, "collisionMask", {
  54968. get: function () {
  54969. return this._collisionMask;
  54970. },
  54971. set: function (mask) {
  54972. this._collisionMask = !isNaN(mask) ? mask : -1;
  54973. },
  54974. enumerable: true,
  54975. configurable: true
  54976. });
  54977. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54978. /**
  54979. * Gets the plane normal used to compute the sliding response (in local space)
  54980. */
  54981. get: function () {
  54982. return this._slidePlaneNormal;
  54983. },
  54984. enumerable: true,
  54985. configurable: true
  54986. });
  54987. // Methods
  54988. Collider.prototype._initialize = function (source, dir, e) {
  54989. this._velocity = dir;
  54990. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54991. this._basePoint = source;
  54992. source.multiplyToRef(this._radius, this._basePointWorld);
  54993. dir.multiplyToRef(this._radius, this._velocityWorld);
  54994. this._velocityWorldLength = this._velocityWorld.length();
  54995. this._epsilon = e;
  54996. this.collisionFound = false;
  54997. };
  54998. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54999. pa.subtractToRef(point, this._tempVector);
  55000. pb.subtractToRef(point, this._tempVector2);
  55001. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  55002. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55003. if (d < 0)
  55004. return false;
  55005. pc.subtractToRef(point, this._tempVector3);
  55006. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  55007. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55008. if (d < 0)
  55009. return false;
  55010. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  55011. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55012. return d >= 0;
  55013. };
  55014. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55015. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55016. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55017. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55018. return false;
  55019. }
  55020. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55021. return false;
  55022. return true;
  55023. };
  55024. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  55025. var t0;
  55026. var embeddedInPlane = false;
  55027. //defensive programming, actually not needed.
  55028. if (!trianglePlaneArray) {
  55029. trianglePlaneArray = [];
  55030. }
  55031. if (!trianglePlaneArray[faceIndex]) {
  55032. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  55033. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  55034. }
  55035. var trianglePlane = trianglePlaneArray[faceIndex];
  55036. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  55037. return;
  55038. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55039. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55040. if (normalDotVelocity == 0) {
  55041. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55042. return;
  55043. embeddedInPlane = true;
  55044. t0 = 0;
  55045. }
  55046. else {
  55047. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55048. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55049. if (t0 > t1) {
  55050. var temp = t1;
  55051. t1 = t0;
  55052. t0 = temp;
  55053. }
  55054. if (t0 > 1.0 || t1 < 0.0)
  55055. return;
  55056. if (t0 < 0)
  55057. t0 = 0;
  55058. if (t0 > 1.0)
  55059. t0 = 1.0;
  55060. }
  55061. this._collisionPoint.copyFromFloats(0, 0, 0);
  55062. var found = false;
  55063. var t = 1.0;
  55064. if (!embeddedInPlane) {
  55065. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55066. this._velocity.scaleToRef(t0, this._tempVector);
  55067. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55068. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55069. found = true;
  55070. t = t0;
  55071. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55072. }
  55073. }
  55074. if (!found) {
  55075. var velocitySquaredLength = this._velocity.lengthSquared();
  55076. var a = velocitySquaredLength;
  55077. this._basePoint.subtractToRef(p1, this._tempVector);
  55078. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55079. var c = this._tempVector.lengthSquared() - 1.0;
  55080. var lowestRoot = getLowestRoot(a, b, c, t);
  55081. if (lowestRoot.found) {
  55082. t = lowestRoot.root;
  55083. found = true;
  55084. this._collisionPoint.copyFrom(p1);
  55085. }
  55086. this._basePoint.subtractToRef(p2, this._tempVector);
  55087. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55088. c = this._tempVector.lengthSquared() - 1.0;
  55089. lowestRoot = getLowestRoot(a, b, c, t);
  55090. if (lowestRoot.found) {
  55091. t = lowestRoot.root;
  55092. found = true;
  55093. this._collisionPoint.copyFrom(p2);
  55094. }
  55095. this._basePoint.subtractToRef(p3, this._tempVector);
  55096. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55097. c = this._tempVector.lengthSquared() - 1.0;
  55098. lowestRoot = getLowestRoot(a, b, c, t);
  55099. if (lowestRoot.found) {
  55100. t = lowestRoot.root;
  55101. found = true;
  55102. this._collisionPoint.copyFrom(p3);
  55103. }
  55104. p2.subtractToRef(p1, this._edge);
  55105. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55106. var edgeSquaredLength = this._edge.lengthSquared();
  55107. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55108. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55109. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55110. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55111. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55112. lowestRoot = getLowestRoot(a, b, c, t);
  55113. if (lowestRoot.found) {
  55114. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55115. if (f >= 0.0 && f <= 1.0) {
  55116. t = lowestRoot.root;
  55117. found = true;
  55118. this._edge.scaleInPlace(f);
  55119. p1.addToRef(this._edge, this._collisionPoint);
  55120. }
  55121. }
  55122. p3.subtractToRef(p2, this._edge);
  55123. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55124. edgeSquaredLength = this._edge.lengthSquared();
  55125. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55126. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55127. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55128. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55129. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55130. lowestRoot = getLowestRoot(a, b, c, t);
  55131. if (lowestRoot.found) {
  55132. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55133. if (f >= 0.0 && f <= 1.0) {
  55134. t = lowestRoot.root;
  55135. found = true;
  55136. this._edge.scaleInPlace(f);
  55137. p2.addToRef(this._edge, this._collisionPoint);
  55138. }
  55139. }
  55140. p1.subtractToRef(p3, this._edge);
  55141. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55142. edgeSquaredLength = this._edge.lengthSquared();
  55143. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55144. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55145. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55146. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55147. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55148. lowestRoot = getLowestRoot(a, b, c, t);
  55149. if (lowestRoot.found) {
  55150. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55151. if (f >= 0.0 && f <= 1.0) {
  55152. t = lowestRoot.root;
  55153. found = true;
  55154. this._edge.scaleInPlace(f);
  55155. p3.addToRef(this._edge, this._collisionPoint);
  55156. }
  55157. }
  55158. }
  55159. if (found) {
  55160. var distToCollision = t * this._velocity.length();
  55161. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55162. if (!this.intersectionPoint) {
  55163. this.intersectionPoint = this._collisionPoint.clone();
  55164. }
  55165. else {
  55166. this.intersectionPoint.copyFrom(this._collisionPoint);
  55167. }
  55168. this._nearestDistance = distToCollision;
  55169. this.collisionFound = true;
  55170. }
  55171. }
  55172. };
  55173. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55174. for (var i = indexStart; i < indexEnd; i += 3) {
  55175. var p1 = pts[indices[i] - decal];
  55176. var p2 = pts[indices[i + 1] - decal];
  55177. var p3 = pts[indices[i + 2] - decal];
  55178. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55179. }
  55180. };
  55181. Collider.prototype._getResponse = function (pos, vel) {
  55182. pos.addToRef(vel, this._destinationPoint);
  55183. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55184. this._basePoint.addToRef(vel, pos);
  55185. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55186. this._slidePlaneNormal.normalize();
  55187. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55188. pos.addInPlace(this._displacementVector);
  55189. this.intersectionPoint.addInPlace(this._displacementVector);
  55190. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55191. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55192. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55193. };
  55194. return Collider;
  55195. }());
  55196. BABYLON.Collider = Collider;
  55197. })(BABYLON || (BABYLON = {}));
  55198. //# sourceMappingURL=babylon.collider.js.map
  55199. var BABYLON;
  55200. (function (BABYLON) {
  55201. //WebWorker code will be inserted to this variable.
  55202. BABYLON.CollisionWorker = "";
  55203. /** Defines supported task for worker process */
  55204. var WorkerTaskType;
  55205. (function (WorkerTaskType) {
  55206. /** Initialization */
  55207. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55208. /** Update of geometry */
  55209. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55210. /** Evaluate collision */
  55211. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55212. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55213. /** Defines kind of replies returned by worker */
  55214. var WorkerReplyType;
  55215. (function (WorkerReplyType) {
  55216. /** Success */
  55217. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55218. /** Unkown error */
  55219. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55220. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55221. var CollisionCoordinatorWorker = /** @class */ (function () {
  55222. function CollisionCoordinatorWorker() {
  55223. var _this = this;
  55224. this._scaledPosition = BABYLON.Vector3.Zero();
  55225. this._scaledVelocity = BABYLON.Vector3.Zero();
  55226. this.onMeshUpdated = function (transformNode) {
  55227. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55228. };
  55229. this.onGeometryUpdated = function (geometry) {
  55230. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55231. };
  55232. this._afterRender = function () {
  55233. if (!_this._init)
  55234. return;
  55235. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55236. return;
  55237. }
  55238. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55239. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55240. if (_this._runningUpdated > 4) {
  55241. return;
  55242. }
  55243. ++_this._runningUpdated;
  55244. var payload = {
  55245. updatedMeshes: _this._addUpdateMeshesList,
  55246. updatedGeometries: _this._addUpdateGeometriesList,
  55247. removedGeometries: _this._toRemoveGeometryArray,
  55248. removedMeshes: _this._toRemoveMeshesArray
  55249. };
  55250. var message = {
  55251. payload: payload,
  55252. taskType: WorkerTaskType.UPDATE
  55253. };
  55254. var serializable = [];
  55255. for (var id in payload.updatedGeometries) {
  55256. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55257. //prepare transferables
  55258. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55259. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55260. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55261. }
  55262. }
  55263. _this._worker.postMessage(message, serializable);
  55264. _this._addUpdateMeshesList = {};
  55265. _this._addUpdateGeometriesList = {};
  55266. _this._toRemoveGeometryArray = [];
  55267. _this._toRemoveMeshesArray = [];
  55268. };
  55269. this._onMessageFromWorker = function (e) {
  55270. var returnData = e.data;
  55271. if (returnData.error != WorkerReplyType.SUCCESS) {
  55272. //TODO what errors can be returned from the worker?
  55273. BABYLON.Tools.Warn("error returned from worker!");
  55274. return;
  55275. }
  55276. switch (returnData.taskType) {
  55277. case WorkerTaskType.INIT:
  55278. _this._init = true;
  55279. //Update the worked with ALL of the scene's current state
  55280. _this._scene.meshes.forEach(function (mesh) {
  55281. _this.onMeshAdded(mesh);
  55282. });
  55283. _this._scene.getGeometries().forEach(function (geometry) {
  55284. _this.onGeometryAdded(geometry);
  55285. });
  55286. break;
  55287. case WorkerTaskType.UPDATE:
  55288. _this._runningUpdated--;
  55289. break;
  55290. case WorkerTaskType.COLLIDE:
  55291. var returnPayload = returnData.payload;
  55292. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55293. return;
  55294. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55295. if (callback) {
  55296. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55297. if (mesh) {
  55298. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55299. }
  55300. }
  55301. //cleanup
  55302. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55303. break;
  55304. }
  55305. };
  55306. this._collisionsCallbackArray = [];
  55307. this._init = false;
  55308. this._runningUpdated = 0;
  55309. this._addUpdateMeshesList = {};
  55310. this._addUpdateGeometriesList = {};
  55311. this._toRemoveGeometryArray = [];
  55312. this._toRemoveMeshesArray = [];
  55313. }
  55314. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55315. if (!this._init)
  55316. return;
  55317. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55318. return;
  55319. position.divideToRef(collider._radius, this._scaledPosition);
  55320. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55321. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55322. var payload = {
  55323. collider: {
  55324. position: this._scaledPosition.asArray(),
  55325. velocity: this._scaledVelocity.asArray(),
  55326. radius: collider._radius.asArray()
  55327. },
  55328. collisionId: collisionIndex,
  55329. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55330. maximumRetry: maximumRetry
  55331. };
  55332. var message = {
  55333. payload: payload,
  55334. taskType: WorkerTaskType.COLLIDE
  55335. };
  55336. this._worker.postMessage(message);
  55337. };
  55338. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55339. this._scene = scene;
  55340. this._scene.registerAfterRender(this._afterRender);
  55341. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55342. this._worker = new Worker(workerUrl);
  55343. this._worker.onmessage = this._onMessageFromWorker;
  55344. var message = {
  55345. payload: {},
  55346. taskType: WorkerTaskType.INIT
  55347. };
  55348. this._worker.postMessage(message);
  55349. };
  55350. CollisionCoordinatorWorker.prototype.destroy = function () {
  55351. this._scene.unregisterAfterRender(this._afterRender);
  55352. this._worker.terminate();
  55353. };
  55354. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55355. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55356. this.onMeshUpdated(mesh);
  55357. };
  55358. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55359. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55360. };
  55361. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55362. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55363. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55364. this.onGeometryUpdated(geometry);
  55365. };
  55366. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55367. this._toRemoveGeometryArray.push(geometry.id);
  55368. };
  55369. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55370. var submeshes = [];
  55371. if (mesh.subMeshes) {
  55372. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55373. var boundingInfo = sm.getBoundingInfo();
  55374. return {
  55375. position: idx,
  55376. verticesStart: sm.verticesStart,
  55377. verticesCount: sm.verticesCount,
  55378. indexStart: sm.indexStart,
  55379. indexCount: sm.indexCount,
  55380. hasMaterial: !!sm.getMaterial(),
  55381. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55382. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55383. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55384. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55385. };
  55386. });
  55387. }
  55388. var geometryId = null;
  55389. if (mesh instanceof BABYLON.Mesh) {
  55390. var geometry = mesh.geometry;
  55391. geometryId = geometry ? geometry.id : null;
  55392. }
  55393. else if (mesh instanceof BABYLON.InstancedMesh) {
  55394. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55395. geometryId = geometry ? geometry.id : null;
  55396. }
  55397. var boundingInfo = mesh.getBoundingInfo();
  55398. return {
  55399. uniqueId: mesh.uniqueId,
  55400. id: mesh.id,
  55401. name: mesh.name,
  55402. geometryId: geometryId,
  55403. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55404. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55405. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55406. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55407. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55408. subMeshes: submeshes,
  55409. checkCollisions: mesh.checkCollisions
  55410. };
  55411. };
  55412. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55413. return {
  55414. id: geometry.id,
  55415. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55416. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55417. indices: new Uint32Array(geometry.getIndices() || []),
  55418. };
  55419. };
  55420. return CollisionCoordinatorWorker;
  55421. }());
  55422. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55423. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55424. function CollisionCoordinatorLegacy() {
  55425. this._scaledPosition = BABYLON.Vector3.Zero();
  55426. this._scaledVelocity = BABYLON.Vector3.Zero();
  55427. this._finalPosition = BABYLON.Vector3.Zero();
  55428. }
  55429. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55430. position.divideToRef(collider._radius, this._scaledPosition);
  55431. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55432. collider.collidedMesh = null;
  55433. collider._retry = 0;
  55434. collider._initialVelocity = this._scaledVelocity;
  55435. collider._initialPosition = this._scaledPosition;
  55436. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55437. this._finalPosition.multiplyInPlace(collider._radius);
  55438. //run the callback
  55439. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55440. };
  55441. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55442. this._scene = scene;
  55443. };
  55444. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55445. //Legacy need no destruction method.
  55446. };
  55447. //No update in legacy mode
  55448. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55449. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55450. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55451. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55452. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55453. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55454. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55455. if (excludedMesh === void 0) { excludedMesh = null; }
  55456. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55457. if (collider._retry >= maximumRetry) {
  55458. finalPosition.copyFrom(position);
  55459. return;
  55460. }
  55461. // Check if this is a mesh else camera or -1
  55462. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55463. collider._initialize(position, velocity, closeDistance);
  55464. // Check all meshes
  55465. for (var index = 0; index < this._scene.meshes.length; index++) {
  55466. var mesh = this._scene.meshes[index];
  55467. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55468. mesh._checkCollision(collider);
  55469. }
  55470. }
  55471. if (!collider.collisionFound) {
  55472. position.addToRef(velocity, finalPosition);
  55473. return;
  55474. }
  55475. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55476. collider._getResponse(position, velocity);
  55477. }
  55478. if (velocity.length() <= closeDistance) {
  55479. finalPosition.copyFrom(position);
  55480. return;
  55481. }
  55482. collider._retry++;
  55483. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55484. };
  55485. return CollisionCoordinatorLegacy;
  55486. }());
  55487. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55488. })(BABYLON || (BABYLON = {}));
  55489. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55490. var BABYLON;
  55491. (function (BABYLON) {
  55492. /**
  55493. * A particle represents one of the element emitted by a particle system.
  55494. * This is mainly define by its coordinates, direction, velocity and age.
  55495. */
  55496. var Particle = /** @class */ (function () {
  55497. /**
  55498. * Creates a new instance Particle
  55499. * @param particleSystem the particle system the particle belongs to
  55500. */
  55501. function Particle(
  55502. /**
  55503. * particleSystem the particle system the particle belongs to.
  55504. */
  55505. particleSystem) {
  55506. this.particleSystem = particleSystem;
  55507. /**
  55508. * The world position of the particle in the scene.
  55509. */
  55510. this.position = BABYLON.Vector3.Zero();
  55511. /**
  55512. * The world direction of the particle in the scene.
  55513. */
  55514. this.direction = BABYLON.Vector3.Zero();
  55515. /**
  55516. * The color of the particle.
  55517. */
  55518. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55519. /**
  55520. * The color change of the particle per step.
  55521. */
  55522. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55523. /**
  55524. * Defines how long will the life of the particle be.
  55525. */
  55526. this.lifeTime = 1.0;
  55527. /**
  55528. * The current age of the particle.
  55529. */
  55530. this.age = 0;
  55531. /**
  55532. * The current size of the particle.
  55533. */
  55534. this.size = 0;
  55535. /**
  55536. * The current angle of the particle.
  55537. */
  55538. this.angle = 0;
  55539. /**
  55540. * Defines how fast is the angle changing.
  55541. */
  55542. this.angularSpeed = 0;
  55543. /**
  55544. * Defines the cell index used by the particle to be rendered from a sprite.
  55545. */
  55546. this.cellIndex = 0;
  55547. this._currentFrameCounter = 0;
  55548. if (!this.particleSystem.isAnimationSheetEnabled) {
  55549. return;
  55550. }
  55551. this.updateCellInfoFromSystem();
  55552. }
  55553. Particle.prototype.updateCellInfoFromSystem = function () {
  55554. this.cellIndex = this.particleSystem.startSpriteCellID;
  55555. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  55556. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  55557. }
  55558. else {
  55559. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  55560. }
  55561. };
  55562. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  55563. // (ageOffset / scaledUpdateSpeed) / available cells
  55564. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  55565. this._currentFrameCounter += scaledUpdateSpeed;
  55566. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  55567. this._currentFrameCounter = 0;
  55568. this.cellIndex++;
  55569. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55570. this.cellIndex = this.particleSystem.endSpriteCellID;
  55571. }
  55572. }
  55573. };
  55574. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  55575. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  55576. this.cellIndex++;
  55577. this._currentFrameCounter = 0;
  55578. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55579. if (this.particleSystem.spriteCellLoop) {
  55580. this.cellIndex = this.particleSystem.startSpriteCellID;
  55581. }
  55582. else {
  55583. this.cellIndex = this.particleSystem.endSpriteCellID;
  55584. }
  55585. }
  55586. }
  55587. else {
  55588. this._currentFrameCounter++;
  55589. }
  55590. };
  55591. /**
  55592. * Copy the properties of particle to another one.
  55593. * @param other the particle to copy the information to.
  55594. */
  55595. Particle.prototype.copyTo = function (other) {
  55596. other.position.copyFrom(this.position);
  55597. other.direction.copyFrom(this.direction);
  55598. other.color.copyFrom(this.color);
  55599. other.colorStep.copyFrom(this.colorStep);
  55600. other.lifeTime = this.lifeTime;
  55601. other.age = this.age;
  55602. other.size = this.size;
  55603. other.angle = this.angle;
  55604. other.angularSpeed = this.angularSpeed;
  55605. other.particleSystem = this.particleSystem;
  55606. other.cellIndex = this.cellIndex;
  55607. };
  55608. return Particle;
  55609. }());
  55610. BABYLON.Particle = Particle;
  55611. })(BABYLON || (BABYLON = {}));
  55612. //# sourceMappingURL=babylon.particle.js.map
  55613. var BABYLON;
  55614. (function (BABYLON) {
  55615. /**
  55616. * This represents a particle system in Babylon.
  55617. * 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.
  55618. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55619. * @example https://doc.babylonjs.com/babylon101/particles
  55620. */
  55621. var ParticleSystem = /** @class */ (function () {
  55622. /**
  55623. * Instantiates a particle system.
  55624. * 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.
  55625. * @param name The name of the particle system
  55626. * @param capacity The max number of particles alive at the same time
  55627. * @param scene The scene the particle system belongs to
  55628. * @param customEffect a custom effect used to change the way particles are rendered by default
  55629. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55630. * @param epsilon Offset used to render the particles
  55631. */
  55632. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55633. if (customEffect === void 0) { customEffect = null; }
  55634. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55635. if (epsilon === void 0) { epsilon = 0.01; }
  55636. var _this = this;
  55637. /**
  55638. * List of animations used by the particle system.
  55639. */
  55640. this.animations = [];
  55641. /**
  55642. * The rendering group used by the Particle system to chose when to render.
  55643. */
  55644. this.renderingGroupId = 0;
  55645. /**
  55646. * The emitter represents the Mesh or position we are attaching the particle system to.
  55647. */
  55648. this.emitter = null;
  55649. /**
  55650. * The maximum number of particles to emit per frame
  55651. */
  55652. this.emitRate = 10;
  55653. /**
  55654. * If you want to launch only a few particles at once, that can be done, as well.
  55655. */
  55656. this.manualEmitCount = -1;
  55657. /**
  55658. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55659. */
  55660. this.updateSpeed = 0.01;
  55661. /**
  55662. * The amount of time the particle system is running (depends of the overall update speed).
  55663. */
  55664. this.targetStopDuration = 0;
  55665. /**
  55666. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55667. */
  55668. this.disposeOnStop = false;
  55669. /**
  55670. * Minimum power of emitting particles.
  55671. */
  55672. this.minEmitPower = 1;
  55673. /**
  55674. * Maximum power of emitting particles.
  55675. */
  55676. this.maxEmitPower = 1;
  55677. /**
  55678. * Minimum life time of emitting particles.
  55679. */
  55680. this.minLifeTime = 1;
  55681. /**
  55682. * Maximum life time of emitting particles.
  55683. */
  55684. this.maxLifeTime = 1;
  55685. /**
  55686. * Minimum Size of emitting particles.
  55687. */
  55688. this.minSize = 1;
  55689. /**
  55690. * Maximum Size of emitting particles.
  55691. */
  55692. this.maxSize = 1;
  55693. /**
  55694. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55695. */
  55696. this.minAngularSpeed = 0;
  55697. /**
  55698. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55699. */
  55700. this.maxAngularSpeed = 0;
  55701. /**
  55702. * The layer mask we are rendering the particles through.
  55703. */
  55704. this.layerMask = 0x0FFFFFFF;
  55705. /**
  55706. * This can help using your own shader to render the particle system.
  55707. * The according effect will be created
  55708. */
  55709. this.customShader = null;
  55710. /**
  55711. * By default particle system starts as soon as they are created. This prevents the
  55712. * automatic start to happen and let you decide when to start emitting particles.
  55713. */
  55714. this.preventAutoStart = false;
  55715. /**
  55716. * Callback triggered when the particle animation is ending.
  55717. */
  55718. this.onAnimationEnd = null;
  55719. /**
  55720. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55721. */
  55722. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55723. /**
  55724. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55725. * to override the particles.
  55726. */
  55727. this.forceDepthWrite = false;
  55728. /**
  55729. * You can use gravity if you want to give an orientation to your particles.
  55730. */
  55731. this.gravity = BABYLON.Vector3.Zero();
  55732. /**
  55733. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55734. */
  55735. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55736. /**
  55737. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55738. */
  55739. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55740. /**
  55741. * Color the particle will have at the end of its lifetime.
  55742. */
  55743. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55744. /**
  55745. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  55746. */
  55747. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55748. /**
  55749. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  55750. */
  55751. this.spriteCellLoop = true;
  55752. /**
  55753. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  55754. */
  55755. this.spriteCellChangeSpeed = 0;
  55756. /**
  55757. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  55758. */
  55759. this.startSpriteCellID = 0;
  55760. /**
  55761. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  55762. */
  55763. this.endSpriteCellID = 0;
  55764. /**
  55765. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  55766. */
  55767. this.spriteCellWidth = 0;
  55768. /**
  55769. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  55770. */
  55771. this.spriteCellHeight = 0;
  55772. /**
  55773. * An event triggered when the system is disposed.
  55774. */
  55775. this.onDisposeObservable = new BABYLON.Observable();
  55776. this._particles = new Array();
  55777. this._stockParticles = new Array();
  55778. this._newPartsExcess = 0;
  55779. this._vertexBuffers = {};
  55780. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55781. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55782. this._scaledDirection = BABYLON.Vector3.Zero();
  55783. this._scaledGravity = BABYLON.Vector3.Zero();
  55784. this._currentRenderId = -1;
  55785. this._started = false;
  55786. this._stopped = false;
  55787. this._actualFrame = 0;
  55788. this._vertexBufferSize = 11;
  55789. // start of sub system methods
  55790. /**
  55791. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55792. * Its lifetime will start back at 0.
  55793. */
  55794. this.recycleParticle = function (particle) {
  55795. var lastParticle = _this._particles.pop();
  55796. if (lastParticle !== particle) {
  55797. lastParticle.copyTo(particle);
  55798. }
  55799. _this._stockParticles.push(lastParticle);
  55800. };
  55801. this._createParticle = function () {
  55802. var particle;
  55803. if (_this._stockParticles.length !== 0) {
  55804. particle = _this._stockParticles.pop();
  55805. particle.age = 0;
  55806. particle.cellIndex = _this.startSpriteCellID;
  55807. }
  55808. else {
  55809. particle = new BABYLON.Particle(_this);
  55810. }
  55811. return particle;
  55812. };
  55813. this._emitFromParticle = function (particle) {
  55814. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55815. return;
  55816. }
  55817. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55818. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55819. subSystem._rootParticleSystem = _this;
  55820. _this.activeSubSystems.push(subSystem);
  55821. subSystem.start();
  55822. };
  55823. this._appendParticleVertexes = null;
  55824. this.id = name;
  55825. this.name = name;
  55826. this._capacity = capacity;
  55827. this._epsilon = epsilon;
  55828. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55829. if (isAnimationSheetEnabled) {
  55830. this._vertexBufferSize = 12;
  55831. }
  55832. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55833. this._customEffect = customEffect;
  55834. scene.particleSystems.push(this);
  55835. this._createIndexBuffer();
  55836. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  55837. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  55838. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  55839. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  55840. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  55841. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  55842. if (this._isAnimationSheetEnabled) {
  55843. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  55844. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55845. }
  55846. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55847. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55848. this._vertexBuffers["options"] = options;
  55849. // Default emitter type
  55850. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55851. this.updateFunction = function (particles) {
  55852. for (var index = 0; index < particles.length; index++) {
  55853. var particle = particles[index];
  55854. particle.age += _this._scaledUpdateSpeed;
  55855. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55856. _this._emitFromParticle(particle);
  55857. _this.recycleParticle(particle);
  55858. index--;
  55859. continue;
  55860. }
  55861. else {
  55862. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55863. particle.color.addInPlace(_this._scaledColorStep);
  55864. if (particle.color.a < 0)
  55865. particle.color.a = 0;
  55866. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55867. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55868. particle.position.addInPlace(_this._scaledDirection);
  55869. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55870. particle.direction.addInPlace(_this._scaledGravity);
  55871. if (_this._isAnimationSheetEnabled) {
  55872. particle.updateCellIndex(_this._scaledUpdateSpeed);
  55873. }
  55874. }
  55875. }
  55876. };
  55877. }
  55878. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55879. /**
  55880. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55881. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55882. */
  55883. get: function () {
  55884. if (this.particleEmitterType.direction1) {
  55885. return this.particleEmitterType.direction1;
  55886. }
  55887. return BABYLON.Vector3.Zero();
  55888. },
  55889. set: function (value) {
  55890. if (this.particleEmitterType.direction1) {
  55891. this.particleEmitterType.direction1 = value;
  55892. }
  55893. },
  55894. enumerable: true,
  55895. configurable: true
  55896. });
  55897. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55898. /**
  55899. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55900. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55901. */
  55902. get: function () {
  55903. if (this.particleEmitterType.direction2) {
  55904. return this.particleEmitterType.direction2;
  55905. }
  55906. return BABYLON.Vector3.Zero();
  55907. },
  55908. set: function (value) {
  55909. if (this.particleEmitterType.direction2) {
  55910. this.particleEmitterType.direction2 = value;
  55911. }
  55912. },
  55913. enumerable: true,
  55914. configurable: true
  55915. });
  55916. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55917. /**
  55918. * 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.
  55919. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55920. */
  55921. get: function () {
  55922. if (this.particleEmitterType.minEmitBox) {
  55923. return this.particleEmitterType.minEmitBox;
  55924. }
  55925. return BABYLON.Vector3.Zero();
  55926. },
  55927. set: function (value) {
  55928. if (this.particleEmitterType.minEmitBox) {
  55929. this.particleEmitterType.minEmitBox = value;
  55930. }
  55931. },
  55932. enumerable: true,
  55933. configurable: true
  55934. });
  55935. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55936. /**
  55937. * 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.
  55938. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55939. */
  55940. get: function () {
  55941. if (this.particleEmitterType.maxEmitBox) {
  55942. return this.particleEmitterType.maxEmitBox;
  55943. }
  55944. return BABYLON.Vector3.Zero();
  55945. },
  55946. set: function (value) {
  55947. if (this.particleEmitterType.maxEmitBox) {
  55948. this.particleEmitterType.maxEmitBox = value;
  55949. }
  55950. },
  55951. enumerable: true,
  55952. configurable: true
  55953. });
  55954. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55955. /**
  55956. * Sets a callback that will be triggered when the system is disposed.
  55957. */
  55958. set: function (callback) {
  55959. if (this._onDisposeObserver) {
  55960. this.onDisposeObservable.remove(this._onDisposeObserver);
  55961. }
  55962. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55963. },
  55964. enumerable: true,
  55965. configurable: true
  55966. });
  55967. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55968. /**
  55969. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  55970. */
  55971. get: function () {
  55972. return this._isAnimationSheetEnabled;
  55973. },
  55974. enumerable: true,
  55975. configurable: true
  55976. });
  55977. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55978. //end of Sub-emitter
  55979. /**
  55980. * Gets the current list of active particles
  55981. */
  55982. get: function () {
  55983. return this._particles;
  55984. },
  55985. enumerable: true,
  55986. configurable: true
  55987. });
  55988. /**
  55989. * Returns the string "ParticleSystem"
  55990. * @returns a string containing the class name
  55991. */
  55992. ParticleSystem.prototype.getClassName = function () {
  55993. return "ParticleSystem";
  55994. };
  55995. ParticleSystem.prototype._createIndexBuffer = function () {
  55996. var indices = [];
  55997. var index = 0;
  55998. for (var count = 0; count < this._capacity; count++) {
  55999. indices.push(index);
  56000. indices.push(index + 1);
  56001. indices.push(index + 2);
  56002. indices.push(index);
  56003. indices.push(index + 2);
  56004. indices.push(index + 3);
  56005. index += 4;
  56006. }
  56007. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56008. };
  56009. /**
  56010. * Gets the maximum number of particles active at the same time.
  56011. * @returns The max number of active particles.
  56012. */
  56013. ParticleSystem.prototype.getCapacity = function () {
  56014. return this._capacity;
  56015. };
  56016. /**
  56017. * Gets Wether there are still active particles in the system.
  56018. * @returns True if it is alive, otherwise false.
  56019. */
  56020. ParticleSystem.prototype.isAlive = function () {
  56021. return this._alive;
  56022. };
  56023. /**
  56024. * Gets Wether the system has been started.
  56025. * @returns True if it has been started, otherwise false.
  56026. */
  56027. ParticleSystem.prototype.isStarted = function () {
  56028. return this._started;
  56029. };
  56030. /**
  56031. * Starts the particle system and begins to emit.
  56032. */
  56033. ParticleSystem.prototype.start = function () {
  56034. this._started = true;
  56035. this._stopped = false;
  56036. this._actualFrame = 0;
  56037. if (this.subEmitters && this.subEmitters.length != 0) {
  56038. this.activeSubSystems = new Array();
  56039. }
  56040. };
  56041. /**
  56042. * Stops the particle system.
  56043. * @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.
  56044. */
  56045. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56046. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56047. this._stopped = true;
  56048. if (stopSubEmitters) {
  56049. this._stopSubEmitters();
  56050. }
  56051. };
  56052. // animation sheet
  56053. /**
  56054. * Remove all active particles
  56055. */
  56056. ParticleSystem.prototype.reset = function () {
  56057. this._stockParticles = [];
  56058. this._particles = [];
  56059. };
  56060. /**
  56061. * @hidden (for internal use only)
  56062. */
  56063. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56064. var offset = index * this._vertexBufferSize;
  56065. this._vertexData[offset] = particle.position.x;
  56066. this._vertexData[offset + 1] = particle.position.y;
  56067. this._vertexData[offset + 2] = particle.position.z;
  56068. this._vertexData[offset + 3] = particle.color.r;
  56069. this._vertexData[offset + 4] = particle.color.g;
  56070. this._vertexData[offset + 5] = particle.color.b;
  56071. this._vertexData[offset + 6] = particle.color.a;
  56072. this._vertexData[offset + 7] = particle.angle;
  56073. this._vertexData[offset + 8] = particle.size;
  56074. this._vertexData[offset + 9] = offsetX;
  56075. this._vertexData[offset + 10] = offsetY;
  56076. };
  56077. /**
  56078. * @hidden (for internal use only)
  56079. */
  56080. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  56081. if (offsetX === 0)
  56082. offsetX = this._epsilon;
  56083. else if (offsetX === 1)
  56084. offsetX = 1 - this._epsilon;
  56085. if (offsetY === 0)
  56086. offsetY = this._epsilon;
  56087. else if (offsetY === 1)
  56088. offsetY = 1 - this._epsilon;
  56089. var offset = index * this._vertexBufferSize;
  56090. this._vertexData[offset] = particle.position.x;
  56091. this._vertexData[offset + 1] = particle.position.y;
  56092. this._vertexData[offset + 2] = particle.position.z;
  56093. this._vertexData[offset + 3] = particle.color.r;
  56094. this._vertexData[offset + 4] = particle.color.g;
  56095. this._vertexData[offset + 5] = particle.color.b;
  56096. this._vertexData[offset + 6] = particle.color.a;
  56097. this._vertexData[offset + 7] = particle.angle;
  56098. this._vertexData[offset + 8] = particle.size;
  56099. this._vertexData[offset + 9] = offsetX;
  56100. this._vertexData[offset + 10] = offsetY;
  56101. this._vertexData[offset + 11] = particle.cellIndex;
  56102. };
  56103. ParticleSystem.prototype._stopSubEmitters = function () {
  56104. if (!this.activeSubSystems) {
  56105. return;
  56106. }
  56107. this.activeSubSystems.forEach(function (subSystem) {
  56108. subSystem.stop(true);
  56109. });
  56110. this.activeSubSystems = new Array();
  56111. };
  56112. ParticleSystem.prototype._removeFromRoot = function () {
  56113. if (!this._rootParticleSystem) {
  56114. return;
  56115. }
  56116. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56117. if (index !== -1) {
  56118. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56119. }
  56120. };
  56121. // end of sub system methods
  56122. ParticleSystem.prototype._update = function (newParticles) {
  56123. // Update current
  56124. this._alive = this._particles.length > 0;
  56125. this.updateFunction(this._particles);
  56126. // Add new ones
  56127. var worldMatrix;
  56128. if (this.emitter.position) {
  56129. var emitterMesh = this.emitter;
  56130. worldMatrix = emitterMesh.getWorldMatrix();
  56131. }
  56132. else {
  56133. var emitterPosition = this.emitter;
  56134. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56135. }
  56136. var particle;
  56137. for (var index = 0; index < newParticles; index++) {
  56138. if (this._particles.length === this._capacity) {
  56139. break;
  56140. }
  56141. particle = this._createParticle();
  56142. this._particles.push(particle);
  56143. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  56144. if (this.startPositionFunction) {
  56145. this.startPositionFunction(worldMatrix, particle.position, particle);
  56146. }
  56147. else {
  56148. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  56149. }
  56150. if (this.startDirectionFunction) {
  56151. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56152. }
  56153. else {
  56154. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56155. }
  56156. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  56157. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  56158. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  56159. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  56160. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  56161. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  56162. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56163. }
  56164. };
  56165. ParticleSystem.prototype._getEffect = function () {
  56166. if (this._customEffect) {
  56167. return this._customEffect;
  56168. }
  56169. ;
  56170. var defines = [];
  56171. if (this._scene.clipPlane) {
  56172. defines.push("#define CLIPPLANE");
  56173. }
  56174. if (this._isAnimationSheetEnabled) {
  56175. defines.push("#define ANIMATESHEET");
  56176. }
  56177. // Effect
  56178. var join = defines.join("\n");
  56179. if (this._cachedDefines !== join) {
  56180. this._cachedDefines = join;
  56181. var attributesNamesOrOptions;
  56182. var effectCreationOption;
  56183. if (this._isAnimationSheetEnabled) {
  56184. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  56185. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  56186. }
  56187. else {
  56188. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  56189. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  56190. }
  56191. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56192. }
  56193. return this._effect;
  56194. };
  56195. /**
  56196. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56197. */
  56198. ParticleSystem.prototype.animate = function () {
  56199. if (!this._started)
  56200. return;
  56201. var effect = this._getEffect();
  56202. // Check
  56203. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56204. return;
  56205. if (this._currentRenderId === this._scene.getRenderId()) {
  56206. return;
  56207. }
  56208. this._currentRenderId = this._scene.getRenderId();
  56209. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  56210. // determine the number of particles we need to create
  56211. var newParticles;
  56212. if (this.manualEmitCount > -1) {
  56213. newParticles = this.manualEmitCount;
  56214. this._newPartsExcess = 0;
  56215. this.manualEmitCount = 0;
  56216. }
  56217. else {
  56218. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56219. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56220. }
  56221. if (this._newPartsExcess > 1.0) {
  56222. newParticles += this._newPartsExcess >> 0;
  56223. this._newPartsExcess -= this._newPartsExcess >> 0;
  56224. }
  56225. this._alive = false;
  56226. if (!this._stopped) {
  56227. this._actualFrame += this._scaledUpdateSpeed;
  56228. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56229. this.stop();
  56230. }
  56231. else {
  56232. newParticles = 0;
  56233. }
  56234. this._update(newParticles);
  56235. // Stopped?
  56236. if (this._stopped) {
  56237. if (!this._alive) {
  56238. this._started = false;
  56239. if (this.onAnimationEnd) {
  56240. this.onAnimationEnd();
  56241. }
  56242. if (this.disposeOnStop) {
  56243. this._scene._toBeDisposed.push(this);
  56244. }
  56245. }
  56246. }
  56247. // Animation sheet
  56248. if (this._isAnimationSheetEnabled) {
  56249. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  56250. }
  56251. else {
  56252. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  56253. }
  56254. // Update VBO
  56255. var offset = 0;
  56256. for (var index = 0; index < this._particles.length; index++) {
  56257. var particle = this._particles[index];
  56258. this._appendParticleVertexes(offset, particle);
  56259. offset += 4;
  56260. }
  56261. if (this._vertexBuffer) {
  56262. this._vertexBuffer.update(this._vertexData);
  56263. }
  56264. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56265. this.stop();
  56266. }
  56267. };
  56268. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  56269. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  56270. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  56271. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  56272. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  56273. };
  56274. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  56275. this._appendParticleVertex(offset++, particle, 0, 0);
  56276. this._appendParticleVertex(offset++, particle, 1, 0);
  56277. this._appendParticleVertex(offset++, particle, 1, 1);
  56278. this._appendParticleVertex(offset++, particle, 0, 1);
  56279. };
  56280. /**
  56281. * Rebuilds the particle system.
  56282. */
  56283. ParticleSystem.prototype.rebuild = function () {
  56284. this._createIndexBuffer();
  56285. if (this._vertexBuffer) {
  56286. this._vertexBuffer._rebuild();
  56287. }
  56288. };
  56289. /**
  56290. * Is this system ready to be used/rendered
  56291. * @return true if the system is ready
  56292. */
  56293. ParticleSystem.prototype.isReady = function () {
  56294. var effect = this._getEffect();
  56295. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56296. return false;
  56297. }
  56298. return true;
  56299. };
  56300. /**
  56301. * Renders the particle system in its current state.
  56302. * @returns the current number of particles
  56303. */
  56304. ParticleSystem.prototype.render = function () {
  56305. var effect = this._getEffect();
  56306. // Check
  56307. if (!this.isReady() || !this._particles.length) {
  56308. return 0;
  56309. }
  56310. var engine = this._scene.getEngine();
  56311. // Render
  56312. engine.enableEffect(effect);
  56313. engine.setState(false);
  56314. var viewMatrix = this._scene.getViewMatrix();
  56315. effect.setTexture("diffuseSampler", this.particleTexture);
  56316. effect.setMatrix("view", viewMatrix);
  56317. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56318. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56319. var baseSize = this.particleTexture.getBaseSize();
  56320. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56321. }
  56322. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56323. if (this._scene.clipPlane) {
  56324. var clipPlane = this._scene.clipPlane;
  56325. var invView = viewMatrix.clone();
  56326. invView.invert();
  56327. effect.setMatrix("invView", invView);
  56328. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56329. }
  56330. // VBOs
  56331. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56332. // Draw order
  56333. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  56334. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56335. }
  56336. else {
  56337. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56338. }
  56339. if (this.forceDepthWrite) {
  56340. engine.setDepthWrite(true);
  56341. }
  56342. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56343. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56344. return this._particles.length;
  56345. };
  56346. /**
  56347. * Disposes the particle system and free the associated resources
  56348. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56349. */
  56350. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56351. if (disposeTexture === void 0) { disposeTexture = true; }
  56352. if (this._vertexBuffer) {
  56353. this._vertexBuffer.dispose();
  56354. this._vertexBuffer = null;
  56355. }
  56356. if (this._indexBuffer) {
  56357. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56358. this._indexBuffer = null;
  56359. }
  56360. if (disposeTexture && this.particleTexture) {
  56361. this.particleTexture.dispose();
  56362. this.particleTexture = null;
  56363. }
  56364. this._removeFromRoot();
  56365. // Remove from scene
  56366. var index = this._scene.particleSystems.indexOf(this);
  56367. if (index > -1) {
  56368. this._scene.particleSystems.splice(index, 1);
  56369. }
  56370. // Callback
  56371. this.onDisposeObservable.notifyObservers(this);
  56372. this.onDisposeObservable.clear();
  56373. };
  56374. /**
  56375. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56376. * @param radius The radius of the sphere to emit from
  56377. * @returns the emitter
  56378. */
  56379. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56380. if (radius === void 0) { radius = 1; }
  56381. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56382. this.particleEmitterType = particleEmitter;
  56383. return particleEmitter;
  56384. };
  56385. /**
  56386. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56387. * @param radius The radius of the sphere to emit from
  56388. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56389. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56390. * @returns the emitter
  56391. */
  56392. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56393. if (radius === void 0) { radius = 1; }
  56394. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56395. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56396. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56397. this.particleEmitterType = particleEmitter;
  56398. return particleEmitter;
  56399. };
  56400. /**
  56401. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56402. * @param radius The radius of the cone to emit from
  56403. * @param angle The base angle of the cone
  56404. * @returns the emitter
  56405. */
  56406. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56407. if (radius === void 0) { radius = 1; }
  56408. if (angle === void 0) { angle = Math.PI / 4; }
  56409. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56410. this.particleEmitterType = particleEmitter;
  56411. return particleEmitter;
  56412. };
  56413. // 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.
  56414. /**
  56415. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56416. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56417. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56418. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56419. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56420. * @returns the emitter
  56421. */
  56422. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56423. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56424. this.particleEmitterType = particleEmitter;
  56425. this.direction1 = direction1;
  56426. this.direction2 = direction2;
  56427. this.minEmitBox = minEmitBox;
  56428. this.maxEmitBox = maxEmitBox;
  56429. return particleEmitter;
  56430. };
  56431. // Clone
  56432. /**
  56433. * Clones the particle system.
  56434. * @param name The name of the cloned object
  56435. * @param newEmitter The new emitter to use
  56436. * @returns the cloned particle system
  56437. */
  56438. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56439. var custom = null;
  56440. var program = null;
  56441. if (this.customShader != null) {
  56442. program = this.customShader;
  56443. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56444. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56445. }
  56446. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56447. result.customShader = program;
  56448. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56449. if (newEmitter === undefined) {
  56450. newEmitter = this.emitter;
  56451. }
  56452. result.emitter = newEmitter;
  56453. if (this.particleTexture) {
  56454. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56455. }
  56456. if (!this.preventAutoStart) {
  56457. result.start();
  56458. }
  56459. return result;
  56460. };
  56461. /**
  56462. * Serializes the particle system to a JSON object.
  56463. * @returns the JSON object
  56464. */
  56465. ParticleSystem.prototype.serialize = function () {
  56466. var serializationObject = {};
  56467. serializationObject.name = this.name;
  56468. serializationObject.id = this.id;
  56469. // Emitter
  56470. if (this.emitter.position) {
  56471. var emitterMesh = this.emitter;
  56472. serializationObject.emitterId = emitterMesh.id;
  56473. }
  56474. else {
  56475. var emitterPosition = this.emitter;
  56476. serializationObject.emitter = emitterPosition.asArray();
  56477. }
  56478. serializationObject.capacity = this.getCapacity();
  56479. if (this.particleTexture) {
  56480. serializationObject.textureName = this.particleTexture.name;
  56481. }
  56482. // Animations
  56483. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56484. // Particle system
  56485. serializationObject.minAngularSpeed = this.minAngularSpeed;
  56486. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  56487. serializationObject.minSize = this.minSize;
  56488. serializationObject.maxSize = this.maxSize;
  56489. serializationObject.minEmitPower = this.minEmitPower;
  56490. serializationObject.maxEmitPower = this.maxEmitPower;
  56491. serializationObject.minLifeTime = this.minLifeTime;
  56492. serializationObject.maxLifeTime = this.maxLifeTime;
  56493. serializationObject.emitRate = this.emitRate;
  56494. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56495. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56496. serializationObject.gravity = this.gravity.asArray();
  56497. serializationObject.direction1 = this.direction1.asArray();
  56498. serializationObject.direction2 = this.direction2.asArray();
  56499. serializationObject.color1 = this.color1.asArray();
  56500. serializationObject.color2 = this.color2.asArray();
  56501. serializationObject.colorDead = this.colorDead.asArray();
  56502. serializationObject.updateSpeed = this.updateSpeed;
  56503. serializationObject.targetStopDuration = this.targetStopDuration;
  56504. serializationObject.textureMask = this.textureMask.asArray();
  56505. serializationObject.blendMode = this.blendMode;
  56506. serializationObject.customShader = this.customShader;
  56507. serializationObject.preventAutoStart = this.preventAutoStart;
  56508. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56509. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56510. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56511. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56512. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56513. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56514. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56515. // Emitter
  56516. if (this.particleEmitterType) {
  56517. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56518. }
  56519. return serializationObject;
  56520. };
  56521. /**
  56522. * Parses a JSON object to create a particle system.
  56523. * @param parsedParticleSystem The JSON object to parse
  56524. * @param scene The scene to create the particle system in
  56525. * @param rootUrl The root url to use to load external dependencies like texture
  56526. * @returns the Parsed particle system
  56527. */
  56528. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56529. var name = parsedParticleSystem.name;
  56530. var custom = null;
  56531. var program = null;
  56532. if (parsedParticleSystem.customShader) {
  56533. program = parsedParticleSystem.customShader;
  56534. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56535. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56536. }
  56537. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56538. particleSystem.customShader = program;
  56539. if (parsedParticleSystem.id) {
  56540. particleSystem.id = parsedParticleSystem.id;
  56541. }
  56542. // Auto start
  56543. if (parsedParticleSystem.preventAutoStart) {
  56544. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56545. }
  56546. // Texture
  56547. if (parsedParticleSystem.textureName) {
  56548. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56549. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56550. }
  56551. // Emitter
  56552. if (parsedParticleSystem.emitterId) {
  56553. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56554. }
  56555. else {
  56556. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56557. }
  56558. // Animations
  56559. if (parsedParticleSystem.animations) {
  56560. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56561. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56562. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56563. }
  56564. }
  56565. if (parsedParticleSystem.autoAnimate) {
  56566. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56567. }
  56568. // Particle system
  56569. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56570. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56571. particleSystem.minSize = parsedParticleSystem.minSize;
  56572. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56573. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56574. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56575. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56576. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56577. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56578. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  56579. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  56580. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56581. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  56582. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  56583. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56584. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56585. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56586. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56587. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56588. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56589. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56590. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56591. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56592. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  56593. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56594. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56595. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56596. if (!particleSystem.preventAutoStart) {
  56597. particleSystem.start();
  56598. }
  56599. return particleSystem;
  56600. };
  56601. /**
  56602. * Source color is added to the destination color without alpha affecting the result.
  56603. */
  56604. ParticleSystem.BLENDMODE_ONEONE = 0;
  56605. /**
  56606. * Blend current color and particle color using particle’s alpha.
  56607. */
  56608. ParticleSystem.BLENDMODE_STANDARD = 1;
  56609. return ParticleSystem;
  56610. }());
  56611. BABYLON.ParticleSystem = ParticleSystem;
  56612. })(BABYLON || (BABYLON = {}));
  56613. //# sourceMappingURL=babylon.particleSystem.js.map
  56614. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56615. var BABYLON;
  56616. (function (BABYLON) {
  56617. /**
  56618. * Particle emitter emitting particles from the inside of a box.
  56619. * It emits the particles randomly between 2 given directions.
  56620. */
  56621. var BoxParticleEmitter = /** @class */ (function () {
  56622. /**
  56623. * Creates a new instance BoxParticleEmitter
  56624. */
  56625. function BoxParticleEmitter() {
  56626. /**
  56627. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56628. */
  56629. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56630. /**
  56631. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56632. */
  56633. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56634. /**
  56635. * 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.
  56636. */
  56637. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56638. /**
  56639. * 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.
  56640. */
  56641. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56642. }
  56643. /**
  56644. * Called by the particle System when the direction is computed for the created particle.
  56645. * @param emitPower is the power of the particle (speed)
  56646. * @param worldMatrix is the world matrix of the particle system
  56647. * @param directionToUpdate is the direction vector to update with the result
  56648. * @param particle is the particle we are computed the direction for
  56649. */
  56650. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56651. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56652. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56653. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56654. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56655. };
  56656. /**
  56657. * Called by the particle System when the position is computed for the created particle.
  56658. * @param worldMatrix is the world matrix of the particle system
  56659. * @param positionToUpdate is the position vector to update with the result
  56660. * @param particle is the particle we are computed the position for
  56661. */
  56662. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56663. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56664. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56665. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56666. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56667. };
  56668. /**
  56669. * Clones the current emitter and returns a copy of it
  56670. * @returns the new emitter
  56671. */
  56672. BoxParticleEmitter.prototype.clone = function () {
  56673. var newOne = new BoxParticleEmitter();
  56674. BABYLON.Tools.DeepCopy(this, newOne);
  56675. return newOne;
  56676. };
  56677. /**
  56678. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56679. * @param effect defines the update shader
  56680. */
  56681. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56682. effect.setVector3("direction1", this.direction1);
  56683. effect.setVector3("direction2", this.direction2);
  56684. effect.setVector3("minEmitBox", this.minEmitBox);
  56685. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56686. };
  56687. /**
  56688. * Returns a string to use to update the GPU particles update shader
  56689. * @returns a string containng the defines string
  56690. */
  56691. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56692. return "#define BOXEMITTER";
  56693. };
  56694. /**
  56695. * Returns the string "BoxEmitter"
  56696. * @returns a string containing the class name
  56697. */
  56698. BoxParticleEmitter.prototype.getClassName = function () {
  56699. return "BoxEmitter";
  56700. };
  56701. /**
  56702. * Serializes the particle system to a JSON object.
  56703. * @returns the JSON object
  56704. */
  56705. BoxParticleEmitter.prototype.serialize = function () {
  56706. var serializationObject = {};
  56707. serializationObject.type = this.getClassName();
  56708. serializationObject.direction1 = this.direction1.asArray();
  56709. ;
  56710. serializationObject.direction2 = this.direction2.asArray();
  56711. ;
  56712. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56713. ;
  56714. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56715. ;
  56716. return serializationObject;
  56717. };
  56718. /**
  56719. * Parse properties from a JSON object
  56720. * @param serializationObject defines the JSON object
  56721. */
  56722. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56723. this.direction1.copyFrom(serializationObject.direction1);
  56724. this.direction2.copyFrom(serializationObject.direction2);
  56725. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  56726. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  56727. };
  56728. return BoxParticleEmitter;
  56729. }());
  56730. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56731. })(BABYLON || (BABYLON = {}));
  56732. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56733. var BABYLON;
  56734. (function (BABYLON) {
  56735. /**
  56736. * Particle emitter emitting particles from the inside of a cone.
  56737. * It emits the particles alongside the cone volume from the base to the particle.
  56738. * The emission direction might be randomized.
  56739. */
  56740. var ConeParticleEmitter = /** @class */ (function () {
  56741. /**
  56742. * Creates a new instance ConeParticleEmitter
  56743. * @param radius the radius of the emission cone (1 by default)
  56744. * @param angles the cone base angle (PI by default)
  56745. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56746. */
  56747. function ConeParticleEmitter(radius,
  56748. /**
  56749. * The radius of the emission cone.
  56750. */
  56751. angle,
  56752. /**
  56753. * The cone base angle.
  56754. */
  56755. directionRandomizer) {
  56756. if (radius === void 0) { radius = 1; }
  56757. if (angle === void 0) { angle = Math.PI; }
  56758. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56759. this.angle = angle;
  56760. this.directionRandomizer = directionRandomizer;
  56761. this.radius = radius;
  56762. }
  56763. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56764. /**
  56765. * Gets the radius of the emission cone.
  56766. */
  56767. get: function () {
  56768. return this._radius;
  56769. },
  56770. /**
  56771. * Sets the radius of the emission cone.
  56772. */
  56773. set: function (value) {
  56774. this._radius = value;
  56775. if (this.angle !== 0) {
  56776. this._height = value / Math.tan(this.angle / 2);
  56777. }
  56778. else {
  56779. this._height = 1;
  56780. }
  56781. },
  56782. enumerable: true,
  56783. configurable: true
  56784. });
  56785. /**
  56786. * Called by the particle System when the direction is computed for the created particle.
  56787. * @param emitPower is the power of the particle (speed)
  56788. * @param worldMatrix is the world matrix of the particle system
  56789. * @param directionToUpdate is the direction vector to update with the result
  56790. * @param particle is the particle we are computed the direction for
  56791. */
  56792. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56793. if (this.angle === 0) {
  56794. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  56795. }
  56796. else {
  56797. // measure the direction Vector from the emitter to the particle.
  56798. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56799. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56800. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56801. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56802. direction.x += randX;
  56803. direction.y += randY;
  56804. direction.z += randZ;
  56805. direction.normalize();
  56806. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56807. }
  56808. };
  56809. /**
  56810. * Called by the particle System when the position is computed for the created particle.
  56811. * @param worldMatrix is the world matrix of the particle system
  56812. * @param positionToUpdate is the position vector to update with the result
  56813. * @param particle is the particle we are computed the position for
  56814. */
  56815. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56816. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56817. var h = BABYLON.Scalar.RandomRange(0, 1);
  56818. // Better distribution in a cone at normal angles.
  56819. h = 1 - h * h;
  56820. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  56821. radius = radius * h;
  56822. var randX = radius * Math.sin(s);
  56823. var randZ = radius * Math.cos(s);
  56824. var randY = h * this._height;
  56825. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56826. };
  56827. /**
  56828. * Clones the current emitter and returns a copy of it
  56829. * @returns the new emitter
  56830. */
  56831. ConeParticleEmitter.prototype.clone = function () {
  56832. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  56833. BABYLON.Tools.DeepCopy(this, newOne);
  56834. return newOne;
  56835. };
  56836. /**
  56837. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56838. * @param effect defines the update shader
  56839. */
  56840. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56841. effect.setFloat("radius", this.radius);
  56842. effect.setFloat("angle", this.angle);
  56843. effect.setFloat("height", this._height);
  56844. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56845. };
  56846. /**
  56847. * Returns a string to use to update the GPU particles update shader
  56848. * @returns a string containng the defines string
  56849. */
  56850. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56851. return "#define CONEEMITTER";
  56852. };
  56853. /**
  56854. * Returns the string "BoxEmitter"
  56855. * @returns a string containing the class name
  56856. */
  56857. ConeParticleEmitter.prototype.getClassName = function () {
  56858. return "ConeEmitter";
  56859. };
  56860. /**
  56861. * Serializes the particle system to a JSON object.
  56862. * @returns the JSON object
  56863. */
  56864. ConeParticleEmitter.prototype.serialize = function () {
  56865. var serializationObject = {};
  56866. serializationObject.type = this.getClassName();
  56867. serializationObject.radius = this.radius;
  56868. serializationObject.angle = this.angle;
  56869. serializationObject.directionRandomizer = this.directionRandomizer;
  56870. return serializationObject;
  56871. };
  56872. /**
  56873. * Parse properties from a JSON object
  56874. * @param serializationObject defines the JSON object
  56875. */
  56876. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56877. this.radius = serializationObject.radius;
  56878. this.angle = serializationObject.angle;
  56879. this.directionRandomizer = serializationObject.directionRandomizer;
  56880. };
  56881. return ConeParticleEmitter;
  56882. }());
  56883. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56884. })(BABYLON || (BABYLON = {}));
  56885. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56886. var BABYLON;
  56887. (function (BABYLON) {
  56888. /**
  56889. * Particle emitter emitting particles from the inside of a sphere.
  56890. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56891. */
  56892. var SphereParticleEmitter = /** @class */ (function () {
  56893. /**
  56894. * Creates a new instance SphereParticleEmitter
  56895. * @param radius the radius of the emission sphere (1 by default)
  56896. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56897. */
  56898. function SphereParticleEmitter(
  56899. /**
  56900. * The radius of the emission sphere.
  56901. */
  56902. radius,
  56903. /**
  56904. * How much to randomize the particle direction [0-1].
  56905. */
  56906. directionRandomizer) {
  56907. if (radius === void 0) { radius = 1; }
  56908. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56909. this.radius = radius;
  56910. this.directionRandomizer = directionRandomizer;
  56911. }
  56912. /**
  56913. * Called by the particle System when the direction is computed for the created particle.
  56914. * @param emitPower is the power of the particle (speed)
  56915. * @param worldMatrix is the world matrix of the particle system
  56916. * @param directionToUpdate is the direction vector to update with the result
  56917. * @param particle is the particle we are computed the direction for
  56918. */
  56919. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56920. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56921. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56922. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56923. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56924. direction.x += randX;
  56925. direction.y += randY;
  56926. direction.z += randZ;
  56927. direction.normalize();
  56928. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56929. };
  56930. /**
  56931. * Called by the particle System when the position is computed for the created particle.
  56932. * @param worldMatrix is the world matrix of the particle system
  56933. * @param positionToUpdate is the position vector to update with the result
  56934. * @param particle is the particle we are computed the position for
  56935. */
  56936. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56937. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56938. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  56939. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  56940. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56941. var randY = randRadius * Math.cos(theta);
  56942. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56943. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56944. };
  56945. /**
  56946. * Clones the current emitter and returns a copy of it
  56947. * @returns the new emitter
  56948. */
  56949. SphereParticleEmitter.prototype.clone = function () {
  56950. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56951. BABYLON.Tools.DeepCopy(this, newOne);
  56952. return newOne;
  56953. };
  56954. /**
  56955. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56956. * @param effect defines the update shader
  56957. */
  56958. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56959. effect.setFloat("radius", this.radius);
  56960. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56961. };
  56962. /**
  56963. * Returns a string to use to update the GPU particles update shader
  56964. * @returns a string containng the defines string
  56965. */
  56966. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56967. return "#define SPHEREEMITTER";
  56968. };
  56969. /**
  56970. * Returns the string "SphereParticleEmitter"
  56971. * @returns a string containing the class name
  56972. */
  56973. SphereParticleEmitter.prototype.getClassName = function () {
  56974. return "SphereParticleEmitter";
  56975. };
  56976. /**
  56977. * Serializes the particle system to a JSON object.
  56978. * @returns the JSON object
  56979. */
  56980. SphereParticleEmitter.prototype.serialize = function () {
  56981. var serializationObject = {};
  56982. serializationObject.type = this.getClassName();
  56983. serializationObject.radius = this.radius;
  56984. serializationObject.directionRandomizer = this.directionRandomizer;
  56985. return serializationObject;
  56986. };
  56987. /**
  56988. * Parse properties from a JSON object
  56989. * @param serializationObject defines the JSON object
  56990. */
  56991. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56992. this.radius = serializationObject.radius;
  56993. this.directionRandomizer = serializationObject.directionRandomizer;
  56994. };
  56995. return SphereParticleEmitter;
  56996. }());
  56997. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56998. /**
  56999. * Particle emitter emitting particles from the inside of a sphere.
  57000. * It emits the particles randomly between two vectors.
  57001. */
  57002. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  57003. __extends(SphereDirectedParticleEmitter, _super);
  57004. /**
  57005. * Creates a new instance SphereDirectedParticleEmitter
  57006. * @param radius the radius of the emission sphere (1 by default)
  57007. * @param direction1 the min limit of the emission direction (up vector by default)
  57008. * @param direction2 the max limit of the emission direction (up vector by default)
  57009. */
  57010. function SphereDirectedParticleEmitter(radius,
  57011. /**
  57012. * The min limit of the emission direction.
  57013. */
  57014. direction1,
  57015. /**
  57016. * The max limit of the emission direction.
  57017. */
  57018. direction2) {
  57019. if (radius === void 0) { radius = 1; }
  57020. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57021. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57022. var _this = _super.call(this, radius) || this;
  57023. _this.direction1 = direction1;
  57024. _this.direction2 = direction2;
  57025. return _this;
  57026. }
  57027. /**
  57028. * Called by the particle System when the direction is computed for the created particle.
  57029. * @param emitPower is the power of the particle (speed)
  57030. * @param worldMatrix is the world matrix of the particle system
  57031. * @param directionToUpdate is the direction vector to update with the result
  57032. * @param particle is the particle we are computed the direction for
  57033. */
  57034. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57035. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57036. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57037. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57038. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57039. };
  57040. /**
  57041. * Clones the current emitter and returns a copy of it
  57042. * @returns the new emitter
  57043. */
  57044. SphereDirectedParticleEmitter.prototype.clone = function () {
  57045. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57046. BABYLON.Tools.DeepCopy(this, newOne);
  57047. return newOne;
  57048. };
  57049. /**
  57050. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57051. * @param effect defines the update shader
  57052. */
  57053. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57054. effect.setFloat("radius", this.radius);
  57055. effect.setVector3("direction1", this.direction1);
  57056. effect.setVector3("direction2", this.direction2);
  57057. };
  57058. /**
  57059. * Returns a string to use to update the GPU particles update shader
  57060. * @returns a string containng the defines string
  57061. */
  57062. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57063. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57064. };
  57065. /**
  57066. * Returns the string "SphereDirectedParticleEmitter"
  57067. * @returns a string containing the class name
  57068. */
  57069. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57070. return "SphereDirectedParticleEmitter";
  57071. };
  57072. /**
  57073. * Serializes the particle system to a JSON object.
  57074. * @returns the JSON object
  57075. */
  57076. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57077. var serializationObject = _super.prototype.serialize.call(this);
  57078. ;
  57079. serializationObject.direction1 = this.direction1.asArray();
  57080. ;
  57081. serializationObject.direction2 = this.direction2.asArray();
  57082. ;
  57083. return serializationObject;
  57084. };
  57085. /**
  57086. * Parse properties from a JSON object
  57087. * @param serializationObject defines the JSON object
  57088. */
  57089. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57090. _super.prototype.parse.call(this, serializationObject);
  57091. this.direction1.copyFrom(serializationObject.direction1);
  57092. this.direction2.copyFrom(serializationObject.direction2);
  57093. };
  57094. return SphereDirectedParticleEmitter;
  57095. }(SphereParticleEmitter));
  57096. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57097. })(BABYLON || (BABYLON = {}));
  57098. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57099. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57100. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57101. s = arguments[i];
  57102. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57103. t[p] = s[p];
  57104. }
  57105. return t;
  57106. };
  57107. var BABYLON;
  57108. (function (BABYLON) {
  57109. /**
  57110. * This represents a GPU particle system in Babylon
  57111. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57112. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57113. */
  57114. var GPUParticleSystem = /** @class */ (function () {
  57115. /**
  57116. * Instantiates a GPU particle system.
  57117. * 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.
  57118. * @param name The name of the particle system
  57119. * @param capacity The max number of particles alive at the same time
  57120. * @param scene The scene the particle system belongs to
  57121. */
  57122. function GPUParticleSystem(name, options, scene) {
  57123. /**
  57124. * The emitter represents the Mesh or position we are attaching the particle system to.
  57125. */
  57126. this.emitter = null;
  57127. /**
  57128. * The rendering group used by the Particle system to chose when to render.
  57129. */
  57130. this.renderingGroupId = 0;
  57131. /**
  57132. * The layer mask we are rendering the particles through.
  57133. */
  57134. this.layerMask = 0x0FFFFFFF;
  57135. this._targetIndex = 0;
  57136. this._currentRenderId = -1;
  57137. this._started = false;
  57138. this._stopped = false;
  57139. this._timeDelta = 0;
  57140. this._attributesStrideSize = 14;
  57141. this._actualFrame = 0;
  57142. /**
  57143. * List of animations used by the particle system.
  57144. */
  57145. this.animations = [];
  57146. /**
  57147. * An event triggered when the system is disposed.
  57148. */
  57149. this.onDisposeObservable = new BABYLON.Observable();
  57150. /**
  57151. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57152. */
  57153. this.updateSpeed = 0.01;
  57154. /**
  57155. * The amount of time the particle system is running (depends of the overall update speed).
  57156. */
  57157. this.targetStopDuration = 0;
  57158. /**
  57159. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57160. */
  57161. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57162. /**
  57163. * Minimum life time of emitting particles.
  57164. */
  57165. this.minLifeTime = 1;
  57166. /**
  57167. * Maximum life time of emitting particles.
  57168. */
  57169. this.maxLifeTime = 1;
  57170. /**
  57171. * Minimum Size of emitting particles.
  57172. */
  57173. this.minSize = 1;
  57174. /**
  57175. * Maximum Size of emitting particles.
  57176. */
  57177. this.maxSize = 1;
  57178. /**
  57179. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57180. */
  57181. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57182. /**
  57183. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57184. */
  57185. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57186. /**
  57187. * Color the particle will have at the end of its lifetime.
  57188. */
  57189. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57190. /**
  57191. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57192. */
  57193. this.emitRate = 100;
  57194. /**
  57195. * You can use gravity if you want to give an orientation to your particles.
  57196. */
  57197. this.gravity = BABYLON.Vector3.Zero();
  57198. /**
  57199. * Minimum power of emitting particles.
  57200. */
  57201. this.minEmitPower = 1;
  57202. /**
  57203. * Maximum power of emitting particles.
  57204. */
  57205. this.maxEmitPower = 1;
  57206. /**
  57207. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57208. * to override the particles.
  57209. */
  57210. this.forceDepthWrite = false;
  57211. this.id = name;
  57212. this.name = name;
  57213. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57214. this._engine = this._scene.getEngine();
  57215. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57216. this._capacity = fullOptions.capacity;
  57217. this._activeCount = fullOptions.capacity;
  57218. this._currentActiveCount = 0;
  57219. this._scene.particleSystems.push(this);
  57220. this._updateEffectOptions = {
  57221. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  57222. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  57223. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  57224. uniformBuffersNames: [],
  57225. samplers: ["randomSampler"],
  57226. defines: "",
  57227. fallbacks: null,
  57228. onCompiled: null,
  57229. onError: null,
  57230. indexParameters: null,
  57231. maxSimultaneousLights: 0,
  57232. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  57233. };
  57234. // Random data
  57235. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57236. var d = [];
  57237. for (var i = 0; i < maxTextureSize; ++i) {
  57238. d.push(Math.random());
  57239. d.push(Math.random());
  57240. d.push(Math.random());
  57241. d.push(Math.random());
  57242. }
  57243. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA32F, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  57244. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57245. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57246. this._randomTextureSize = maxTextureSize;
  57247. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57248. }
  57249. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57250. /**
  57251. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57252. */
  57253. get: function () {
  57254. if (!BABYLON.Engine.LastCreatedEngine) {
  57255. return false;
  57256. }
  57257. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57258. },
  57259. enumerable: true,
  57260. configurable: true
  57261. });
  57262. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57263. /**
  57264. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57265. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57266. */
  57267. get: function () {
  57268. if (this.particleEmitterType.direction1) {
  57269. return this.particleEmitterType.direction1;
  57270. }
  57271. return BABYLON.Vector3.Zero();
  57272. },
  57273. set: function (value) {
  57274. if (this.particleEmitterType.direction1) {
  57275. this.particleEmitterType.direction1 = value;
  57276. }
  57277. },
  57278. enumerable: true,
  57279. configurable: true
  57280. });
  57281. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57282. /**
  57283. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57284. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57285. */
  57286. get: function () {
  57287. if (this.particleEmitterType.direction2) {
  57288. return this.particleEmitterType.direction2;
  57289. }
  57290. return BABYLON.Vector3.Zero();
  57291. },
  57292. set: function (value) {
  57293. if (this.particleEmitterType.direction2) {
  57294. this.particleEmitterType.direction2 = value;
  57295. }
  57296. },
  57297. enumerable: true,
  57298. configurable: true
  57299. });
  57300. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57301. /**
  57302. * 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.
  57303. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57304. */
  57305. get: function () {
  57306. if (this.particleEmitterType.minEmitBox) {
  57307. return this.particleEmitterType.minEmitBox;
  57308. }
  57309. return BABYLON.Vector3.Zero();
  57310. },
  57311. set: function (value) {
  57312. if (this.particleEmitterType.minEmitBox) {
  57313. this.particleEmitterType.minEmitBox = value;
  57314. }
  57315. },
  57316. enumerable: true,
  57317. configurable: true
  57318. });
  57319. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57320. /**
  57321. * 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.
  57322. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57323. */
  57324. get: function () {
  57325. if (this.particleEmitterType.maxEmitBox) {
  57326. return this.particleEmitterType.maxEmitBox;
  57327. }
  57328. return BABYLON.Vector3.Zero();
  57329. },
  57330. set: function (value) {
  57331. if (this.particleEmitterType.maxEmitBox) {
  57332. this.particleEmitterType.maxEmitBox = value;
  57333. }
  57334. },
  57335. enumerable: true,
  57336. configurable: true
  57337. });
  57338. /**
  57339. * Gets the maximum number of particles active at the same time.
  57340. * @returns The max number of active particles.
  57341. */
  57342. GPUParticleSystem.prototype.getCapacity = function () {
  57343. return this._capacity;
  57344. };
  57345. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57346. /**
  57347. * Gets or set the number of active particles
  57348. */
  57349. get: function () {
  57350. return this._activeCount;
  57351. },
  57352. set: function (value) {
  57353. this._activeCount = Math.min(value, this._capacity);
  57354. },
  57355. enumerable: true,
  57356. configurable: true
  57357. });
  57358. /**
  57359. * Is this system ready to be used/rendered
  57360. * @return true if the system is ready
  57361. */
  57362. GPUParticleSystem.prototype.isReady = function () {
  57363. if (!this._updateEffect) {
  57364. this._recreateUpdateEffect();
  57365. this._recreateRenderEffect();
  57366. return false;
  57367. }
  57368. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57369. return false;
  57370. }
  57371. return true;
  57372. };
  57373. /**
  57374. * Gets Wether the system has been started.
  57375. * @returns True if it has been started, otherwise false.
  57376. */
  57377. GPUParticleSystem.prototype.isStarted = function () {
  57378. return this._started;
  57379. };
  57380. /**
  57381. * Starts the particle system and begins to emit.
  57382. */
  57383. GPUParticleSystem.prototype.start = function () {
  57384. this._started = true;
  57385. this._stopped = false;
  57386. };
  57387. /**
  57388. * Stops the particle system.
  57389. */
  57390. GPUParticleSystem.prototype.stop = function () {
  57391. this._stopped = true;
  57392. };
  57393. /**
  57394. * Remove all active particles
  57395. */
  57396. GPUParticleSystem.prototype.reset = function () {
  57397. this._releaseBuffers();
  57398. this._releaseVAOs();
  57399. this._currentActiveCount = 0;
  57400. this._targetIndex = 0;
  57401. };
  57402. /**
  57403. * Returns the string "GPUParticleSystem"
  57404. * @returns a string containing the class name
  57405. */
  57406. GPUParticleSystem.prototype.getClassName = function () {
  57407. return "GPUParticleSystem";
  57408. };
  57409. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57410. var updateVertexBuffers = {};
  57411. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57412. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57413. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57414. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  57415. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  57416. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  57417. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  57418. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57419. this._engine.bindArrayBuffer(null);
  57420. return vao;
  57421. };
  57422. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57423. var renderVertexBuffers = {};
  57424. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57425. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57426. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57427. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  57428. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  57429. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57430. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57431. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57432. this._engine.bindArrayBuffer(null);
  57433. return vao;
  57434. };
  57435. GPUParticleSystem.prototype._initialize = function (force) {
  57436. if (force === void 0) { force = false; }
  57437. if (this._buffer0 && !force) {
  57438. return;
  57439. }
  57440. var engine = this._scene.getEngine();
  57441. var data = new Array();
  57442. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57443. // position
  57444. data.push(0.0);
  57445. data.push(0.0);
  57446. data.push(0.0);
  57447. // Age and life
  57448. data.push(0.0); // create the particle as a dead one to create a new one at start
  57449. data.push(0.0);
  57450. // Seed
  57451. data.push(Math.random());
  57452. // Size
  57453. data.push(0.0);
  57454. // color
  57455. data.push(0.0);
  57456. data.push(0.0);
  57457. data.push(0.0);
  57458. data.push(0.0);
  57459. // direction
  57460. data.push(0.0);
  57461. data.push(0.0);
  57462. data.push(0.0);
  57463. }
  57464. // Sprite data
  57465. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57466. -0.5, 0.5, 0, 1,
  57467. -0.5, -0.5, 0, 0,
  57468. 0.5, -0.5, 1, 0]);
  57469. // Buffers
  57470. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57471. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57472. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57473. // Update VAO
  57474. this._updateVAO = [];
  57475. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57476. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57477. // Render VAO
  57478. this._renderVAO = [];
  57479. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57480. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57481. // Links
  57482. this._sourceBuffer = this._buffer0;
  57483. this._targetBuffer = this._buffer1;
  57484. };
  57485. /** @hidden */
  57486. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57487. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57488. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57489. return;
  57490. }
  57491. this._updateEffectOptions.defines = defines;
  57492. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57493. };
  57494. /** @hidden */
  57495. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57496. var defines = "";
  57497. if (this._scene.clipPlane) {
  57498. defines = "\n#define CLIPPLANE";
  57499. }
  57500. if (this._renderEffect && this._renderEffect.defines === defines) {
  57501. return;
  57502. }
  57503. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  57504. };
  57505. /**
  57506. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57507. */
  57508. GPUParticleSystem.prototype.animate = function () {
  57509. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  57510. this._actualFrame += this._timeDelta;
  57511. if (!this._stopped) {
  57512. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57513. this.stop();
  57514. }
  57515. }
  57516. };
  57517. /**
  57518. * Renders the particle system in its current state.
  57519. * @returns the current number of particles
  57520. */
  57521. GPUParticleSystem.prototype.render = function () {
  57522. if (!this._started) {
  57523. return 0;
  57524. }
  57525. this._recreateUpdateEffect();
  57526. this._recreateRenderEffect();
  57527. if (!this.isReady()) {
  57528. return 0;
  57529. }
  57530. if (this._currentRenderId === this._scene.getRenderId()) {
  57531. return 0;
  57532. }
  57533. this._currentRenderId = this._scene.getRenderId();
  57534. // Get everything ready to render
  57535. this._initialize();
  57536. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  57537. // Enable update effect
  57538. this._engine.enableEffect(this._updateEffect);
  57539. this._engine.setState(false);
  57540. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57541. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57542. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57543. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  57544. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57545. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57546. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57547. this._updateEffect.setDirectColor4("color1", this.color1);
  57548. this._updateEffect.setDirectColor4("color2", this.color2);
  57549. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57550. this._updateEffect.setVector3("gravity", this.gravity);
  57551. if (this.particleEmitterType) {
  57552. this.particleEmitterType.applyToShader(this._updateEffect);
  57553. }
  57554. var emitterWM;
  57555. if (this.emitter.position) {
  57556. var emitterMesh = this.emitter;
  57557. emitterWM = emitterMesh.getWorldMatrix();
  57558. }
  57559. else {
  57560. var emitterPosition = this.emitter;
  57561. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57562. }
  57563. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57564. // Bind source VAO
  57565. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57566. // Update
  57567. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57568. this._engine.setRasterizerState(false);
  57569. this._engine.beginTransformFeedback();
  57570. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57571. this._engine.endTransformFeedback();
  57572. this._engine.setRasterizerState(true);
  57573. this._engine.bindTransformFeedbackBuffer(null);
  57574. // Enable render effect
  57575. this._engine.enableEffect(this._renderEffect);
  57576. var viewMatrix = this._scene.getViewMatrix();
  57577. this._renderEffect.setMatrix("view", viewMatrix);
  57578. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57579. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57580. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57581. if (this._scene.clipPlane) {
  57582. var clipPlane = this._scene.clipPlane;
  57583. var invView = viewMatrix.clone();
  57584. invView.invert();
  57585. this._renderEffect.setMatrix("invView", invView);
  57586. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57587. }
  57588. // Draw order
  57589. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  57590. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57591. }
  57592. else {
  57593. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57594. }
  57595. if (this.forceDepthWrite) {
  57596. this._engine.setDepthWrite(true);
  57597. }
  57598. // Bind source VAO
  57599. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57600. // Render
  57601. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57602. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57603. // Switch VAOs
  57604. this._targetIndex++;
  57605. if (this._targetIndex === 2) {
  57606. this._targetIndex = 0;
  57607. }
  57608. // Switch buffers
  57609. var tmpBuffer = this._sourceBuffer;
  57610. this._sourceBuffer = this._targetBuffer;
  57611. this._targetBuffer = tmpBuffer;
  57612. return this._currentActiveCount;
  57613. };
  57614. /**
  57615. * Rebuilds the particle system
  57616. */
  57617. GPUParticleSystem.prototype.rebuild = function () {
  57618. this._initialize(true);
  57619. };
  57620. GPUParticleSystem.prototype._releaseBuffers = function () {
  57621. if (this._buffer0) {
  57622. this._buffer0.dispose();
  57623. this._buffer0 = null;
  57624. }
  57625. if (this._buffer1) {
  57626. this._buffer1.dispose();
  57627. this._buffer1 = null;
  57628. }
  57629. if (this._spriteBuffer) {
  57630. this._spriteBuffer.dispose();
  57631. this._spriteBuffer = null;
  57632. }
  57633. };
  57634. GPUParticleSystem.prototype._releaseVAOs = function () {
  57635. if (!this._updateVAO) {
  57636. return;
  57637. }
  57638. for (var index = 0; index < this._updateVAO.length; index++) {
  57639. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57640. }
  57641. this._updateVAO = [];
  57642. for (var index = 0; index < this._renderVAO.length; index++) {
  57643. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57644. }
  57645. this._renderVAO = [];
  57646. };
  57647. /**
  57648. * Disposes the particle system and free the associated resources
  57649. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57650. */
  57651. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57652. if (disposeTexture === void 0) { disposeTexture = true; }
  57653. var index = this._scene.particleSystems.indexOf(this);
  57654. if (index > -1) {
  57655. this._scene.particleSystems.splice(index, 1);
  57656. }
  57657. this._releaseBuffers();
  57658. this._releaseVAOs();
  57659. if (this._randomTexture) {
  57660. this._randomTexture.dispose();
  57661. this._randomTexture = null;
  57662. }
  57663. if (disposeTexture && this.particleTexture) {
  57664. this.particleTexture.dispose();
  57665. this.particleTexture = null;
  57666. }
  57667. // Callback
  57668. this.onDisposeObservable.notifyObservers(this);
  57669. this.onDisposeObservable.clear();
  57670. };
  57671. /**
  57672. * Clones the particle system.
  57673. * @param name The name of the cloned object
  57674. * @param newEmitter The new emitter to use
  57675. * @returns the cloned particle system
  57676. */
  57677. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57678. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57679. BABYLON.Tools.DeepCopy(this, result);
  57680. if (newEmitter === undefined) {
  57681. newEmitter = this.emitter;
  57682. }
  57683. result.emitter = newEmitter;
  57684. if (this.particleTexture) {
  57685. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57686. }
  57687. return result;
  57688. };
  57689. /**
  57690. * Serializes the particle system to a JSON object.
  57691. * @returns the JSON object
  57692. */
  57693. GPUParticleSystem.prototype.serialize = function () {
  57694. var serializationObject = {};
  57695. serializationObject.name = this.name;
  57696. serializationObject.id = this.id;
  57697. // Emitter
  57698. if (this.emitter.position) {
  57699. var emitterMesh = this.emitter;
  57700. serializationObject.emitterId = emitterMesh.id;
  57701. }
  57702. else {
  57703. var emitterPosition = this.emitter;
  57704. serializationObject.emitter = emitterPosition.asArray();
  57705. }
  57706. serializationObject.capacity = this.getCapacity();
  57707. if (this.particleTexture) {
  57708. serializationObject.textureName = this.particleTexture.name;
  57709. }
  57710. // Animations
  57711. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57712. // Particle system
  57713. serializationObject.activeParticleCount = this.activeParticleCount;
  57714. serializationObject.randomTextureSize = this._randomTextureSize;
  57715. serializationObject.minSize = this.minSize;
  57716. serializationObject.maxSize = this.maxSize;
  57717. serializationObject.minEmitPower = this.minEmitPower;
  57718. serializationObject.maxEmitPower = this.maxEmitPower;
  57719. serializationObject.minLifeTime = this.minLifeTime;
  57720. serializationObject.maxLifeTime = this.maxLifeTime;
  57721. serializationObject.emitRate = this.emitRate;
  57722. serializationObject.gravity = this.gravity.asArray();
  57723. serializationObject.color1 = this.color1.asArray();
  57724. serializationObject.color2 = this.color2.asArray();
  57725. serializationObject.colorDead = this.colorDead.asArray();
  57726. serializationObject.updateSpeed = this.updateSpeed;
  57727. serializationObject.targetStopDuration = this.targetStopDuration;
  57728. serializationObject.blendMode = this.blendMode;
  57729. // Emitter
  57730. if (this.particleEmitterType) {
  57731. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57732. }
  57733. return serializationObject;
  57734. };
  57735. /**
  57736. * Parses a JSON object to create a GPU particle system.
  57737. * @param parsedParticleSystem The JSON object to parse
  57738. * @param scene The scene to create the particle system in
  57739. * @param rootUrl The root url to use to load external dependencies like texture
  57740. * @returns the parsed GPU particle system
  57741. */
  57742. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57743. var name = parsedParticleSystem.name;
  57744. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57745. if (parsedParticleSystem.id) {
  57746. particleSystem.id = parsedParticleSystem.id;
  57747. }
  57748. // Texture
  57749. if (parsedParticleSystem.textureName) {
  57750. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57751. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57752. }
  57753. // Emitter
  57754. if (parsedParticleSystem.emitterId) {
  57755. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57756. }
  57757. else {
  57758. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57759. }
  57760. // Animations
  57761. if (parsedParticleSystem.animations) {
  57762. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57763. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57764. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57765. }
  57766. }
  57767. // Particle system
  57768. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57769. particleSystem.minSize = parsedParticleSystem.minSize;
  57770. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57771. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57772. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57773. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57774. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57775. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57776. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57777. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57778. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57779. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57780. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57781. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57782. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57783. // Emitter
  57784. if (parsedParticleSystem.particleEmitterType) {
  57785. var emitterType = void 0;
  57786. switch (parsedParticleSystem.particleEmitterType.type) {
  57787. case "SphereEmitter":
  57788. emitterType = new BABYLON.SphereParticleEmitter();
  57789. break;
  57790. case "SphereDirectedParticleEmitter":
  57791. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57792. break;
  57793. case "ConeEmitter":
  57794. emitterType = new BABYLON.ConeParticleEmitter();
  57795. break;
  57796. case "BoxEmitter":
  57797. default:
  57798. emitterType = new BABYLON.BoxParticleEmitter();
  57799. break;
  57800. }
  57801. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57802. particleSystem.particleEmitterType = emitterType;
  57803. }
  57804. return particleSystem;
  57805. };
  57806. return GPUParticleSystem;
  57807. }());
  57808. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57809. })(BABYLON || (BABYLON = {}));
  57810. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57811. var BABYLON;
  57812. (function (BABYLON) {
  57813. /**
  57814. * Represents one particle of a solid particle system.
  57815. */
  57816. var SolidParticle = /** @class */ (function () {
  57817. /**
  57818. * Creates a Solid Particle object.
  57819. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57820. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57821. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57822. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57823. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57824. * @param shapeId (integer) is the model shape identifier in the SPS.
  57825. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57826. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57827. */
  57828. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57829. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57830. /**
  57831. * particle global index
  57832. */
  57833. this.idx = 0;
  57834. /**
  57835. * The color of the particle
  57836. */
  57837. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57838. /**
  57839. * The world space position of the particle.
  57840. */
  57841. this.position = BABYLON.Vector3.Zero();
  57842. /**
  57843. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57844. */
  57845. this.rotation = BABYLON.Vector3.Zero();
  57846. /**
  57847. * The scaling of the particle.
  57848. */
  57849. this.scaling = BABYLON.Vector3.One();
  57850. /**
  57851. * The uvs of the particle.
  57852. */
  57853. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  57854. /**
  57855. * The current speed of the particle.
  57856. */
  57857. this.velocity = BABYLON.Vector3.Zero();
  57858. /**
  57859. * The pivot point in the particle local space.
  57860. */
  57861. this.pivot = BABYLON.Vector3.Zero();
  57862. /**
  57863. * Must the particle be translated from its pivot point in its local space ?
  57864. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  57865. * Default : false
  57866. */
  57867. this.translateFromPivot = false;
  57868. /**
  57869. * Is the particle active or not ?
  57870. */
  57871. this.alive = true;
  57872. /**
  57873. * Is the particle visible or not ?
  57874. */
  57875. this.isVisible = true;
  57876. /**
  57877. * Index of this particle in the global "positions" array (Internal use)
  57878. */
  57879. this._pos = 0;
  57880. /**
  57881. * Index of this particle in the global "indices" array (Internal use)
  57882. */
  57883. this._ind = 0;
  57884. /**
  57885. * ModelShape id of this particle
  57886. */
  57887. this.shapeId = 0;
  57888. /**
  57889. * Index of the particle in its shape id (Internal use)
  57890. */
  57891. this.idxInShape = 0;
  57892. /**
  57893. * Still set as invisible in order to skip useless computations (Internal use)
  57894. */
  57895. this._stillInvisible = false;
  57896. /**
  57897. * Last computed particle rotation matrix
  57898. */
  57899. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  57900. /**
  57901. * Parent particle Id, if any.
  57902. * Default null.
  57903. */
  57904. this.parentId = null;
  57905. /**
  57906. * Internal global position in the SPS.
  57907. */
  57908. this._globalPosition = BABYLON.Vector3.Zero();
  57909. this.idx = particleIndex;
  57910. this._pos = positionIndex;
  57911. this._ind = indiceIndex;
  57912. this._model = model;
  57913. this.shapeId = shapeId;
  57914. this.idxInShape = idxInShape;
  57915. this._sps = sps;
  57916. if (modelBoundingInfo) {
  57917. this._modelBoundingInfo = modelBoundingInfo;
  57918. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  57919. }
  57920. }
  57921. Object.defineProperty(SolidParticle.prototype, "scale", {
  57922. /**
  57923. * Legacy support, changed scale to scaling
  57924. */
  57925. get: function () {
  57926. return this.scaling;
  57927. },
  57928. /**
  57929. * Legacy support, changed scale to scaling
  57930. */
  57931. set: function (scale) {
  57932. this.scaling = scale;
  57933. },
  57934. enumerable: true,
  57935. configurable: true
  57936. });
  57937. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  57938. /**
  57939. * Legacy support, changed quaternion to rotationQuaternion
  57940. */
  57941. get: function () {
  57942. return this.rotationQuaternion;
  57943. },
  57944. /**
  57945. * Legacy support, changed quaternion to rotationQuaternion
  57946. */
  57947. set: function (q) {
  57948. this.rotationQuaternion = q;
  57949. },
  57950. enumerable: true,
  57951. configurable: true
  57952. });
  57953. /**
  57954. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  57955. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  57956. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  57957. * @returns true if it intersects
  57958. */
  57959. SolidParticle.prototype.intersectsMesh = function (target) {
  57960. if (!this._boundingInfo || !target._boundingInfo) {
  57961. return false;
  57962. }
  57963. if (this._sps._bSphereOnly) {
  57964. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  57965. }
  57966. return this._boundingInfo.intersects(target._boundingInfo, false);
  57967. };
  57968. return SolidParticle;
  57969. }());
  57970. BABYLON.SolidParticle = SolidParticle;
  57971. /**
  57972. * Represents the shape of the model used by one particle of a solid particle system.
  57973. * SPS internal tool, don't use it manually.
  57974. */
  57975. var ModelShape = /** @class */ (function () {
  57976. /**
  57977. * 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.
  57978. * SPS internal tool, don't use it manually.
  57979. * @hidden
  57980. */
  57981. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  57982. /**
  57983. * length of the shape in the model indices array (internal use)
  57984. */
  57985. this._indicesLength = 0;
  57986. this.shapeID = id;
  57987. this._shape = shape;
  57988. this._indicesLength = indicesLength;
  57989. this._shapeUV = shapeUV;
  57990. this._positionFunction = posFunction;
  57991. this._vertexFunction = vtxFunction;
  57992. }
  57993. return ModelShape;
  57994. }());
  57995. BABYLON.ModelShape = ModelShape;
  57996. /**
  57997. * Represents a Depth Sorted Particle in the solid particle system.
  57998. */
  57999. var DepthSortedParticle = /** @class */ (function () {
  58000. function DepthSortedParticle() {
  58001. /**
  58002. * Index of the particle in the "indices" array
  58003. */
  58004. this.ind = 0;
  58005. /**
  58006. * Length of the particle shape in the "indices" array
  58007. */
  58008. this.indicesLength = 0;
  58009. /**
  58010. * Squared distance from the particle to the camera
  58011. */
  58012. this.sqDistance = 0.0;
  58013. }
  58014. return DepthSortedParticle;
  58015. }());
  58016. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58017. })(BABYLON || (BABYLON = {}));
  58018. //# sourceMappingURL=babylon.solidParticle.js.map
  58019. var BABYLON;
  58020. (function (BABYLON) {
  58021. /**
  58022. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58023. *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.
  58024. * The SPS is also a particle system. It provides some methods to manage the particles.
  58025. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58026. *
  58027. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58028. */
  58029. var SolidParticleSystem = /** @class */ (function () {
  58030. /**
  58031. * Creates a SPS (Solid Particle System) object.
  58032. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58033. * @param scene (Scene) is the scene in which the SPS is added.
  58034. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58035. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58036. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58037. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58038. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58039. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58040. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58041. */
  58042. function SolidParticleSystem(name, scene, options) {
  58043. /**
  58044. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58045. * Example : var p = SPS.particles[i];
  58046. */
  58047. this.particles = new Array();
  58048. /**
  58049. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58050. */
  58051. this.nbParticles = 0;
  58052. /**
  58053. * If the particles must ever face the camera (default false). Useful for planar particles.
  58054. */
  58055. this.billboard = false;
  58056. /**
  58057. * Recompute normals when adding a shape
  58058. */
  58059. this.recomputeNormals = true;
  58060. /**
  58061. * This a counter ofr your own usage. It's not set by any SPS functions.
  58062. */
  58063. this.counter = 0;
  58064. /**
  58065. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58066. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58067. */
  58068. this.vars = {};
  58069. /**
  58070. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58071. */
  58072. this._bSphereOnly = false;
  58073. /**
  58074. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58075. */
  58076. this._bSphereRadiusFactor = 1.0;
  58077. this._positions = new Array();
  58078. this._indices = new Array();
  58079. this._normals = new Array();
  58080. this._colors = new Array();
  58081. this._uvs = new Array();
  58082. this._index = 0; // indices index
  58083. this._updatable = true;
  58084. this._pickable = false;
  58085. this._isVisibilityBoxLocked = false;
  58086. this._alwaysVisible = false;
  58087. this._depthSort = false;
  58088. this._shapeCounter = 0;
  58089. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58090. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58091. this._computeParticleColor = true;
  58092. this._computeParticleTexture = true;
  58093. this._computeParticleRotation = true;
  58094. this._computeParticleVertex = false;
  58095. this._computeBoundingBox = false;
  58096. this._depthSortParticles = true;
  58097. this._cam_axisZ = BABYLON.Vector3.Zero();
  58098. this._cam_axisY = BABYLON.Vector3.Zero();
  58099. this._cam_axisX = BABYLON.Vector3.Zero();
  58100. this._axisZ = BABYLON.Axis.Z;
  58101. this._camDir = BABYLON.Vector3.Zero();
  58102. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58103. this._rotMatrix = new BABYLON.Matrix();
  58104. this._invertMatrix = new BABYLON.Matrix();
  58105. this._rotated = BABYLON.Vector3.Zero();
  58106. this._quaternion = new BABYLON.Quaternion();
  58107. this._vertex = BABYLON.Vector3.Zero();
  58108. this._normal = BABYLON.Vector3.Zero();
  58109. this._yaw = 0.0;
  58110. this._pitch = 0.0;
  58111. this._roll = 0.0;
  58112. this._halfroll = 0.0;
  58113. this._halfpitch = 0.0;
  58114. this._halfyaw = 0.0;
  58115. this._sinRoll = 0.0;
  58116. this._cosRoll = 0.0;
  58117. this._sinPitch = 0.0;
  58118. this._cosPitch = 0.0;
  58119. this._sinYaw = 0.0;
  58120. this._cosYaw = 0.0;
  58121. this._mustUnrotateFixedNormals = false;
  58122. this._minimum = BABYLON.Vector3.Zero();
  58123. this._maximum = BABYLON.Vector3.Zero();
  58124. this._minBbox = BABYLON.Vector3.Zero();
  58125. this._maxBbox = BABYLON.Vector3.Zero();
  58126. this._particlesIntersect = false;
  58127. this._depthSortFunction = function (p1, p2) {
  58128. return (p2.sqDistance - p1.sqDistance);
  58129. };
  58130. this._needs32Bits = false;
  58131. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58132. this._scaledPivot = BABYLON.Vector3.Zero();
  58133. this._particleHasParent = false;
  58134. this.name = name;
  58135. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58136. this._camera = scene.activeCamera;
  58137. this._pickable = options ? options.isPickable : false;
  58138. this._depthSort = options ? options.enableDepthSort : false;
  58139. this._particlesIntersect = options ? options.particleIntersection : false;
  58140. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58141. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58142. if (options && options.updatable) {
  58143. this._updatable = options.updatable;
  58144. }
  58145. else {
  58146. this._updatable = true;
  58147. }
  58148. if (this._pickable) {
  58149. this.pickedParticles = [];
  58150. }
  58151. if (this._depthSort) {
  58152. this.depthSortedParticles = [];
  58153. }
  58154. }
  58155. /**
  58156. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58157. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58158. * @returns the created mesh
  58159. */
  58160. SolidParticleSystem.prototype.buildMesh = function () {
  58161. if (this.nbParticles === 0) {
  58162. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58163. this.addShape(triangle, 1);
  58164. triangle.dispose();
  58165. }
  58166. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58167. this._positions32 = new Float32Array(this._positions);
  58168. this._uvs32 = new Float32Array(this._uvs);
  58169. this._colors32 = new Float32Array(this._colors);
  58170. if (this.recomputeNormals) {
  58171. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58172. }
  58173. this._normals32 = new Float32Array(this._normals);
  58174. this._fixedNormal32 = new Float32Array(this._normals);
  58175. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58176. this._unrotateFixedNormals();
  58177. }
  58178. var vertexData = new BABYLON.VertexData();
  58179. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58180. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58181. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58182. if (this._uvs32) {
  58183. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58184. ;
  58185. }
  58186. if (this._colors32) {
  58187. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58188. }
  58189. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58190. vertexData.applyToMesh(mesh, this._updatable);
  58191. this.mesh = mesh;
  58192. this.mesh.isPickable = this._pickable;
  58193. // free memory
  58194. if (!this._depthSort) {
  58195. this._indices = null;
  58196. }
  58197. this._positions = null;
  58198. this._normals = null;
  58199. this._uvs = null;
  58200. this._colors = null;
  58201. if (!this._updatable) {
  58202. this.particles.length = 0;
  58203. }
  58204. return mesh;
  58205. };
  58206. /**
  58207. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58208. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58209. * Thus the particles generated from `digest()` have their property `position` set yet.
  58210. * @param mesh ( Mesh ) is the mesh to be digested
  58211. * @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
  58212. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58213. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58214. * @returns the current SPS
  58215. */
  58216. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58217. var size = (options && options.facetNb) || 1;
  58218. var number = (options && options.number) || 0;
  58219. var delta = (options && options.delta) || 0;
  58220. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58221. var meshInd = mesh.getIndices();
  58222. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58223. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58224. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58225. var f = 0; // facet counter
  58226. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58227. // compute size from number
  58228. if (number) {
  58229. number = (number > totalFacets) ? totalFacets : number;
  58230. size = Math.round(totalFacets / number);
  58231. delta = 0;
  58232. }
  58233. else {
  58234. size = (size > totalFacets) ? totalFacets : size;
  58235. }
  58236. var facetPos = []; // submesh positions
  58237. var facetInd = []; // submesh indices
  58238. var facetUV = []; // submesh UV
  58239. var facetCol = []; // submesh colors
  58240. var barycenter = BABYLON.Vector3.Zero();
  58241. var sizeO = size;
  58242. while (f < totalFacets) {
  58243. size = sizeO + Math.floor((1 + delta) * Math.random());
  58244. if (f > totalFacets - size) {
  58245. size = totalFacets - f;
  58246. }
  58247. // reset temp arrays
  58248. facetPos.length = 0;
  58249. facetInd.length = 0;
  58250. facetUV.length = 0;
  58251. facetCol.length = 0;
  58252. // iterate over "size" facets
  58253. var fi = 0;
  58254. for (var j = f * 3; j < (f + size) * 3; j++) {
  58255. facetInd.push(fi);
  58256. var i = meshInd[j];
  58257. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58258. if (meshUV) {
  58259. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58260. }
  58261. if (meshCol) {
  58262. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58263. }
  58264. fi++;
  58265. }
  58266. // create a model shape for each single particle
  58267. var idx = this.nbParticles;
  58268. var shape = this._posToShape(facetPos);
  58269. var shapeUV = this._uvsToShapeUV(facetUV);
  58270. // compute the barycenter of the shape
  58271. var v;
  58272. for (v = 0; v < shape.length; v++) {
  58273. barycenter.addInPlace(shape[v]);
  58274. }
  58275. barycenter.scaleInPlace(1 / shape.length);
  58276. // shift the shape from its barycenter to the origin
  58277. for (v = 0; v < shape.length; v++) {
  58278. shape[v].subtractInPlace(barycenter);
  58279. }
  58280. var bInfo;
  58281. if (this._particlesIntersect) {
  58282. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58283. }
  58284. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58285. // add the particle in the SPS
  58286. var currentPos = this._positions.length;
  58287. var currentInd = this._indices.length;
  58288. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58289. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58290. // initialize the particle position
  58291. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58292. this._index += shape.length;
  58293. idx++;
  58294. this.nbParticles++;
  58295. this._shapeCounter++;
  58296. f += size;
  58297. }
  58298. return this;
  58299. };
  58300. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58301. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58302. var index = 0;
  58303. var idx = 0;
  58304. for (var p = 0; p < this.particles.length; p++) {
  58305. this._particle = this.particles[p];
  58306. this._shape = this._particle._model._shape;
  58307. if (this._particle.rotationQuaternion) {
  58308. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58309. }
  58310. else {
  58311. this._yaw = this._particle.rotation.y;
  58312. this._pitch = this._particle.rotation.x;
  58313. this._roll = this._particle.rotation.z;
  58314. this._quaternionRotationYPR();
  58315. }
  58316. this._quaternionToRotationMatrix();
  58317. this._rotMatrix.invertToRef(this._invertMatrix);
  58318. for (var pt = 0; pt < this._shape.length; pt++) {
  58319. idx = index + pt * 3;
  58320. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58321. this._fixedNormal32[idx] = this._normal.x;
  58322. this._fixedNormal32[idx + 1] = this._normal.y;
  58323. this._fixedNormal32[idx + 2] = this._normal.z;
  58324. }
  58325. index = idx + 3;
  58326. }
  58327. };
  58328. //reset copy
  58329. SolidParticleSystem.prototype._resetCopy = function () {
  58330. this._copy.position.x = 0;
  58331. this._copy.position.y = 0;
  58332. this._copy.position.z = 0;
  58333. this._copy.rotation.x = 0;
  58334. this._copy.rotation.y = 0;
  58335. this._copy.rotation.z = 0;
  58336. this._copy.rotationQuaternion = null;
  58337. this._copy.scaling.x = 1.0;
  58338. this._copy.scaling.y = 1.0;
  58339. this._copy.scaling.z = 1.0;
  58340. this._copy.uvs.x = 0;
  58341. this._copy.uvs.y = 0;
  58342. this._copy.uvs.z = 1.0;
  58343. this._copy.uvs.w = 1.0;
  58344. this._copy.color = null;
  58345. this._copy.translateFromPivot = false;
  58346. };
  58347. // _meshBuilder : inserts the shape model in the global SPS mesh
  58348. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58349. var i;
  58350. var u = 0;
  58351. var c = 0;
  58352. var n = 0;
  58353. this._resetCopy();
  58354. if (options && options.positionFunction) { // call to custom positionFunction
  58355. options.positionFunction(this._copy, idx, idxInShape);
  58356. this._mustUnrotateFixedNormals = true;
  58357. }
  58358. if (this._copy.rotationQuaternion) {
  58359. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58360. }
  58361. else {
  58362. this._yaw = this._copy.rotation.y;
  58363. this._pitch = this._copy.rotation.x;
  58364. this._roll = this._copy.rotation.z;
  58365. this._quaternionRotationYPR();
  58366. }
  58367. this._quaternionToRotationMatrix();
  58368. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58369. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58370. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58371. if (this._copy.translateFromPivot) {
  58372. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58373. }
  58374. else {
  58375. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58376. }
  58377. for (i = 0; i < shape.length; i++) {
  58378. this._vertex.x = shape[i].x;
  58379. this._vertex.y = shape[i].y;
  58380. this._vertex.z = shape[i].z;
  58381. if (options && options.vertexFunction) {
  58382. options.vertexFunction(this._copy, this._vertex, i);
  58383. }
  58384. this._vertex.x *= this._copy.scaling.x;
  58385. this._vertex.y *= this._copy.scaling.y;
  58386. this._vertex.z *= this._copy.scaling.z;
  58387. this._vertex.x -= this._scaledPivot.x;
  58388. this._vertex.y -= this._scaledPivot.y;
  58389. this._vertex.z -= this._scaledPivot.z;
  58390. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58391. this._rotated.addInPlace(this._pivotBackTranslation);
  58392. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58393. if (meshUV) {
  58394. 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);
  58395. u += 2;
  58396. }
  58397. if (this._copy.color) {
  58398. this._color = this._copy.color;
  58399. }
  58400. else if (meshCol && meshCol[c] !== undefined) {
  58401. this._color.r = meshCol[c];
  58402. this._color.g = meshCol[c + 1];
  58403. this._color.b = meshCol[c + 2];
  58404. this._color.a = meshCol[c + 3];
  58405. }
  58406. else {
  58407. this._color.r = 1.0;
  58408. this._color.g = 1.0;
  58409. this._color.b = 1.0;
  58410. this._color.a = 1.0;
  58411. }
  58412. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58413. c += 4;
  58414. if (!this.recomputeNormals && meshNor) {
  58415. this._normal.x = meshNor[n];
  58416. this._normal.y = meshNor[n + 1];
  58417. this._normal.z = meshNor[n + 2];
  58418. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58419. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58420. n += 3;
  58421. }
  58422. }
  58423. for (i = 0; i < meshInd.length; i++) {
  58424. var current_ind = p + meshInd[i];
  58425. indices.push(current_ind);
  58426. if (current_ind > 65535) {
  58427. this._needs32Bits = true;
  58428. }
  58429. }
  58430. if (this._pickable) {
  58431. var nbfaces = meshInd.length / 3;
  58432. for (i = 0; i < nbfaces; i++) {
  58433. this.pickedParticles.push({ idx: idx, faceId: i });
  58434. }
  58435. }
  58436. if (this._depthSort) {
  58437. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58438. }
  58439. return this._copy;
  58440. };
  58441. // returns a shape array from positions array
  58442. SolidParticleSystem.prototype._posToShape = function (positions) {
  58443. var shape = [];
  58444. for (var i = 0; i < positions.length; i += 3) {
  58445. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58446. }
  58447. return shape;
  58448. };
  58449. // returns a shapeUV array from a Vector4 uvs
  58450. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58451. var shapeUV = [];
  58452. if (uvs) {
  58453. for (var i = 0; i < uvs.length; i++)
  58454. shapeUV.push(uvs[i]);
  58455. }
  58456. return shapeUV;
  58457. };
  58458. // adds a new particle object in the particles array
  58459. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58460. if (bInfo === void 0) { bInfo = null; }
  58461. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58462. this.particles.push(sp);
  58463. return sp;
  58464. };
  58465. /**
  58466. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58467. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58468. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58469. * @param nb (positive integer) the number of particles to be created from this model
  58470. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58471. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58472. * @returns the number of shapes in the system
  58473. */
  58474. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58475. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58476. var meshInd = mesh.getIndices();
  58477. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58478. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58479. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58480. var bbInfo;
  58481. if (this._particlesIntersect) {
  58482. bbInfo = mesh.getBoundingInfo();
  58483. }
  58484. var shape = this._posToShape(meshPos);
  58485. var shapeUV = this._uvsToShapeUV(meshUV);
  58486. var posfunc = options ? options.positionFunction : null;
  58487. var vtxfunc = options ? options.vertexFunction : null;
  58488. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58489. // particles
  58490. var sp;
  58491. var currentCopy;
  58492. var idx = this.nbParticles;
  58493. for (var i = 0; i < nb; i++) {
  58494. var currentPos = this._positions.length;
  58495. var currentInd = this._indices.length;
  58496. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58497. if (this._updatable) {
  58498. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58499. sp.position.copyFrom(currentCopy.position);
  58500. sp.rotation.copyFrom(currentCopy.rotation);
  58501. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58502. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58503. }
  58504. if (currentCopy.color && sp.color) {
  58505. sp.color.copyFrom(currentCopy.color);
  58506. }
  58507. sp.scaling.copyFrom(currentCopy.scaling);
  58508. sp.uvs.copyFrom(currentCopy.uvs);
  58509. }
  58510. this._index += shape.length;
  58511. idx++;
  58512. }
  58513. this.nbParticles += nb;
  58514. this._shapeCounter++;
  58515. return this._shapeCounter - 1;
  58516. };
  58517. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58518. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58519. this._resetCopy();
  58520. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58521. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58522. }
  58523. if (this._copy.rotationQuaternion) {
  58524. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58525. }
  58526. else {
  58527. this._yaw = this._copy.rotation.y;
  58528. this._pitch = this._copy.rotation.x;
  58529. this._roll = this._copy.rotation.z;
  58530. this._quaternionRotationYPR();
  58531. }
  58532. this._quaternionToRotationMatrix();
  58533. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58534. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58535. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58536. if (this._copy.translateFromPivot) {
  58537. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58538. }
  58539. else {
  58540. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58541. }
  58542. this._shape = particle._model._shape;
  58543. for (var pt = 0; pt < this._shape.length; pt++) {
  58544. this._vertex.x = this._shape[pt].x;
  58545. this._vertex.y = this._shape[pt].y;
  58546. this._vertex.z = this._shape[pt].z;
  58547. if (particle._model._vertexFunction) {
  58548. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58549. }
  58550. this._vertex.x *= this._copy.scaling.x;
  58551. this._vertex.y *= this._copy.scaling.y;
  58552. this._vertex.z *= this._copy.scaling.z;
  58553. this._vertex.x -= this._scaledPivot.x;
  58554. this._vertex.y -= this._scaledPivot.y;
  58555. this._vertex.z -= this._scaledPivot.z;
  58556. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58557. this._rotated.addInPlace(this._pivotBackTranslation);
  58558. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58559. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58560. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58561. }
  58562. particle.position.x = 0.0;
  58563. particle.position.y = 0.0;
  58564. particle.position.z = 0.0;
  58565. particle.rotation.x = 0.0;
  58566. particle.rotation.y = 0.0;
  58567. particle.rotation.z = 0.0;
  58568. particle.rotationQuaternion = null;
  58569. particle.scaling.x = 1.0;
  58570. particle.scaling.y = 1.0;
  58571. particle.scaling.z = 1.0;
  58572. particle.uvs.x = 0.0;
  58573. particle.uvs.y = 0.0;
  58574. particle.uvs.z = 1.0;
  58575. particle.uvs.w = 1.0;
  58576. particle.pivot.x = 0.0;
  58577. particle.pivot.y = 0.0;
  58578. particle.pivot.z = 0.0;
  58579. particle.translateFromPivot = false;
  58580. particle.parentId = null;
  58581. };
  58582. /**
  58583. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58584. * @returns the SPS.
  58585. */
  58586. SolidParticleSystem.prototype.rebuildMesh = function () {
  58587. for (var p = 0; p < this.particles.length; p++) {
  58588. this._rebuildParticle(this.particles[p]);
  58589. }
  58590. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58591. return this;
  58592. };
  58593. /**
  58594. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58595. * This method calls `updateParticle()` for each particle of the SPS.
  58596. * For an animated SPS, it is usually called within the render loop.
  58597. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58598. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58599. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58600. * @returns the SPS.
  58601. */
  58602. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58603. if (start === void 0) { start = 0; }
  58604. if (end === void 0) { end = this.nbParticles - 1; }
  58605. if (update === void 0) { update = true; }
  58606. if (!this._updatable) {
  58607. return this;
  58608. }
  58609. // custom beforeUpdate
  58610. this.beforeUpdateParticles(start, end, update);
  58611. this._cam_axisX.x = 1.0;
  58612. this._cam_axisX.y = 0.0;
  58613. this._cam_axisX.z = 0.0;
  58614. this._cam_axisY.x = 0.0;
  58615. this._cam_axisY.y = 1.0;
  58616. this._cam_axisY.z = 0.0;
  58617. this._cam_axisZ.x = 0.0;
  58618. this._cam_axisZ.y = 0.0;
  58619. this._cam_axisZ.z = 1.0;
  58620. // cases when the World Matrix is to be computed first
  58621. if (this.billboard || this._depthSort) {
  58622. this.mesh.computeWorldMatrix(true);
  58623. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58624. }
  58625. // if the particles will always face the camera
  58626. if (this.billboard) {
  58627. // compute the camera position and un-rotate it by the current mesh rotation
  58628. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58629. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58630. this._cam_axisZ.normalize();
  58631. // same for camera up vector extracted from the cam view matrix
  58632. var view = this._camera.getViewMatrix(true);
  58633. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58634. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58635. this._cam_axisY.normalize();
  58636. this._cam_axisX.normalize();
  58637. }
  58638. // if depthSort, compute the camera global position in the mesh local system
  58639. if (this._depthSort) {
  58640. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58641. }
  58642. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58643. var idx = 0; // current position index in the global array positions32
  58644. var index = 0; // position start index in the global array positions32 of the current particle
  58645. var colidx = 0; // current color index in the global array colors32
  58646. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58647. var uvidx = 0; // current uv index in the global array uvs32
  58648. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58649. var pt = 0; // current index in the particle model shape
  58650. if (this.mesh.isFacetDataEnabled) {
  58651. this._computeBoundingBox = true;
  58652. }
  58653. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58654. if (this._computeBoundingBox) {
  58655. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58656. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58657. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58658. }
  58659. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58660. if (this.mesh._boundingInfo) {
  58661. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58662. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58663. }
  58664. }
  58665. }
  58666. // particle loop
  58667. index = this.particles[start]._pos;
  58668. var vpos = (index / 3) | 0;
  58669. colorIndex = vpos * 4;
  58670. uvIndex = vpos * 2;
  58671. for (var p = start; p <= end; p++) {
  58672. this._particle = this.particles[p];
  58673. this._shape = this._particle._model._shape;
  58674. this._shapeUV = this._particle._model._shapeUV;
  58675. // call to custom user function to update the particle properties
  58676. this.updateParticle(this._particle);
  58677. // camera-particle distance for depth sorting
  58678. if (this._depthSort && this._depthSortParticles) {
  58679. var dsp = this.depthSortedParticles[p];
  58680. dsp.ind = this._particle._ind;
  58681. dsp.indicesLength = this._particle._model._indicesLength;
  58682. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58683. }
  58684. // skip the computations for inactive or already invisible particles
  58685. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58686. // increment indexes for the next particle
  58687. pt = this._shape.length;
  58688. index += pt * 3;
  58689. colorIndex += pt * 4;
  58690. uvIndex += pt * 2;
  58691. continue;
  58692. }
  58693. if (this._particle.isVisible) {
  58694. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58695. this._particleHasParent = (this._particle.parentId !== null);
  58696. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58697. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58698. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58699. // particle rotation matrix
  58700. if (this.billboard) {
  58701. this._particle.rotation.x = 0.0;
  58702. this._particle.rotation.y = 0.0;
  58703. }
  58704. if (this._computeParticleRotation || this.billboard) {
  58705. if (this._particle.rotationQuaternion) {
  58706. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58707. }
  58708. else {
  58709. this._yaw = this._particle.rotation.y;
  58710. this._pitch = this._particle.rotation.x;
  58711. this._roll = this._particle.rotation.z;
  58712. this._quaternionRotationYPR();
  58713. }
  58714. this._quaternionToRotationMatrix();
  58715. }
  58716. if (this._particleHasParent) {
  58717. this._parent = this.particles[this._particle.parentId];
  58718. 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];
  58719. 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];
  58720. 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];
  58721. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58722. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58723. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58724. if (this._computeParticleRotation || this.billboard) {
  58725. 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];
  58726. 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];
  58727. 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];
  58728. 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];
  58729. 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];
  58730. 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];
  58731. 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];
  58732. 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];
  58733. 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];
  58734. }
  58735. }
  58736. else {
  58737. this._particle._globalPosition.x = this._particle.position.x;
  58738. this._particle._globalPosition.y = this._particle.position.y;
  58739. this._particle._globalPosition.z = this._particle.position.z;
  58740. if (this._computeParticleRotation || this.billboard) {
  58741. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58742. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58743. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58744. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58745. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58746. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58747. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58748. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58749. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58750. }
  58751. }
  58752. if (this._particle.translateFromPivot) {
  58753. this._pivotBackTranslation.x = 0.0;
  58754. this._pivotBackTranslation.y = 0.0;
  58755. this._pivotBackTranslation.z = 0.0;
  58756. }
  58757. else {
  58758. this._pivotBackTranslation.x = this._scaledPivot.x;
  58759. this._pivotBackTranslation.y = this._scaledPivot.y;
  58760. this._pivotBackTranslation.z = this._scaledPivot.z;
  58761. }
  58762. // particle vertex loop
  58763. for (pt = 0; pt < this._shape.length; pt++) {
  58764. idx = index + pt * 3;
  58765. colidx = colorIndex + pt * 4;
  58766. uvidx = uvIndex + pt * 2;
  58767. this._vertex.x = this._shape[pt].x;
  58768. this._vertex.y = this._shape[pt].y;
  58769. this._vertex.z = this._shape[pt].z;
  58770. if (this._computeParticleVertex) {
  58771. this.updateParticleVertex(this._particle, this._vertex, pt);
  58772. }
  58773. // positions
  58774. this._vertex.x *= this._particle.scaling.x;
  58775. this._vertex.y *= this._particle.scaling.y;
  58776. this._vertex.z *= this._particle.scaling.z;
  58777. this._vertex.x -= this._scaledPivot.x;
  58778. this._vertex.y -= this._scaledPivot.y;
  58779. this._vertex.z -= this._scaledPivot.z;
  58780. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58781. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58782. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58783. this._rotated.x += this._pivotBackTranslation.x;
  58784. this._rotated.y += this._pivotBackTranslation.y;
  58785. this._rotated.z += this._pivotBackTranslation.z;
  58786. 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;
  58787. 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;
  58788. 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;
  58789. if (this._computeBoundingBox) {
  58790. if (this._positions32[idx] < this._minimum.x) {
  58791. this._minimum.x = this._positions32[idx];
  58792. }
  58793. if (this._positions32[idx] > this._maximum.x) {
  58794. this._maximum.x = this._positions32[idx];
  58795. }
  58796. if (this._positions32[idx + 1] < this._minimum.y) {
  58797. this._minimum.y = this._positions32[idx + 1];
  58798. }
  58799. if (this._positions32[idx + 1] > this._maximum.y) {
  58800. this._maximum.y = this._positions32[idx + 1];
  58801. }
  58802. if (this._positions32[idx + 2] < this._minimum.z) {
  58803. this._minimum.z = this._positions32[idx + 2];
  58804. }
  58805. if (this._positions32[idx + 2] > this._maximum.z) {
  58806. this._maximum.z = this._positions32[idx + 2];
  58807. }
  58808. }
  58809. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58810. if (!this._computeParticleVertex) {
  58811. this._normal.x = this._fixedNormal32[idx];
  58812. this._normal.y = this._fixedNormal32[idx + 1];
  58813. this._normal.z = this._fixedNormal32[idx + 2];
  58814. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58815. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58816. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58817. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58818. 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;
  58819. 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;
  58820. }
  58821. if (this._computeParticleColor && this._particle.color) {
  58822. this._colors32[colidx] = this._particle.color.r;
  58823. this._colors32[colidx + 1] = this._particle.color.g;
  58824. this._colors32[colidx + 2] = this._particle.color.b;
  58825. this._colors32[colidx + 3] = this._particle.color.a;
  58826. }
  58827. if (this._computeParticleTexture) {
  58828. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58829. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58830. }
  58831. }
  58832. }
  58833. // particle just set invisible : scaled to zero and positioned at the origin
  58834. else {
  58835. this._particle._stillInvisible = true; // mark the particle as invisible
  58836. for (pt = 0; pt < this._shape.length; pt++) {
  58837. idx = index + pt * 3;
  58838. colidx = colorIndex + pt * 4;
  58839. uvidx = uvIndex + pt * 2;
  58840. this._positions32[idx] = 0.0;
  58841. this._positions32[idx + 1] = 0.0;
  58842. this._positions32[idx + 2] = 0.0;
  58843. this._normals32[idx] = 0.0;
  58844. this._normals32[idx + 1] = 0.0;
  58845. this._normals32[idx + 2] = 0.0;
  58846. if (this._computeParticleColor && this._particle.color) {
  58847. this._colors32[colidx] = this._particle.color.r;
  58848. this._colors32[colidx + 1] = this._particle.color.g;
  58849. this._colors32[colidx + 2] = this._particle.color.b;
  58850. this._colors32[colidx + 3] = this._particle.color.a;
  58851. }
  58852. if (this._computeParticleTexture) {
  58853. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58854. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58855. }
  58856. }
  58857. }
  58858. // if the particle intersections must be computed : update the bbInfo
  58859. if (this._particlesIntersect) {
  58860. var bInfo = this._particle._boundingInfo;
  58861. var bBox = bInfo.boundingBox;
  58862. var bSphere = bInfo.boundingSphere;
  58863. if (!this._bSphereOnly) {
  58864. // place, scale and rotate the particle bbox within the SPS local system, then update it
  58865. for (var b = 0; b < bBox.vectors.length; b++) {
  58866. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  58867. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  58868. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  58869. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58870. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58871. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58872. 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;
  58873. 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;
  58874. 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;
  58875. }
  58876. bBox._update(this.mesh._worldMatrix);
  58877. }
  58878. // place and scale the particle bouding sphere in the SPS local system, then update it
  58879. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  58880. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  58881. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  58882. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  58883. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  58884. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  58885. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  58886. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  58887. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  58888. 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));
  58889. bSphere._update(this.mesh._worldMatrix);
  58890. }
  58891. // increment indexes for the next particle
  58892. index = idx + 3;
  58893. colorIndex = colidx + 4;
  58894. uvIndex = uvidx + 2;
  58895. }
  58896. // if the VBO must be updated
  58897. if (update) {
  58898. if (this._computeParticleColor) {
  58899. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  58900. }
  58901. if (this._computeParticleTexture) {
  58902. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  58903. }
  58904. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58905. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  58906. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  58907. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  58908. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  58909. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  58910. for (var i = 0; i < this._normals32.length; i++) {
  58911. this._fixedNormal32[i] = this._normals32[i];
  58912. }
  58913. }
  58914. if (!this.mesh.areNormalsFrozen) {
  58915. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  58916. }
  58917. }
  58918. if (this._depthSort && this._depthSortParticles) {
  58919. this.depthSortedParticles.sort(this._depthSortFunction);
  58920. var dspl = this.depthSortedParticles.length;
  58921. var sorted = 0;
  58922. var lind = 0;
  58923. var sind = 0;
  58924. var sid = 0;
  58925. for (sorted = 0; sorted < dspl; sorted++) {
  58926. lind = this.depthSortedParticles[sorted].indicesLength;
  58927. sind = this.depthSortedParticles[sorted].ind;
  58928. for (var i = 0; i < lind; i++) {
  58929. this._indices32[sid] = this._indices[sind + i];
  58930. sid++;
  58931. }
  58932. }
  58933. this.mesh.updateIndices(this._indices32);
  58934. }
  58935. }
  58936. if (this._computeBoundingBox) {
  58937. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  58938. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  58939. }
  58940. this.afterUpdateParticles(start, end, update);
  58941. return this;
  58942. };
  58943. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  58944. this._halfroll = this._roll * 0.5;
  58945. this._halfpitch = this._pitch * 0.5;
  58946. this._halfyaw = this._yaw * 0.5;
  58947. this._sinRoll = Math.sin(this._halfroll);
  58948. this._cosRoll = Math.cos(this._halfroll);
  58949. this._sinPitch = Math.sin(this._halfpitch);
  58950. this._cosPitch = Math.cos(this._halfpitch);
  58951. this._sinYaw = Math.sin(this._halfyaw);
  58952. this._cosYaw = Math.cos(this._halfyaw);
  58953. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  58954. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  58955. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  58956. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  58957. };
  58958. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  58959. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  58960. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  58961. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  58962. this._rotMatrix.m[3] = 0;
  58963. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  58964. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  58965. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  58966. this._rotMatrix.m[7] = 0;
  58967. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  58968. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  58969. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  58970. this._rotMatrix.m[11] = 0;
  58971. this._rotMatrix.m[12] = 0;
  58972. this._rotMatrix.m[13] = 0;
  58973. this._rotMatrix.m[14] = 0;
  58974. this._rotMatrix.m[15] = 1.0;
  58975. };
  58976. /**
  58977. * Disposes the SPS.
  58978. */
  58979. SolidParticleSystem.prototype.dispose = function () {
  58980. this.mesh.dispose();
  58981. this.vars = null;
  58982. // drop references to internal big arrays for the GC
  58983. this._positions = null;
  58984. this._indices = null;
  58985. this._normals = null;
  58986. this._uvs = null;
  58987. this._colors = null;
  58988. this._indices32 = null;
  58989. this._positions32 = null;
  58990. this._normals32 = null;
  58991. this._fixedNormal32 = null;
  58992. this._uvs32 = null;
  58993. this._colors32 = null;
  58994. this.pickedParticles = null;
  58995. };
  58996. /**
  58997. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  58998. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58999. * @returns the SPS.
  59000. */
  59001. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59002. if (!this._isVisibilityBoxLocked) {
  59003. this.mesh.refreshBoundingInfo();
  59004. }
  59005. return this;
  59006. };
  59007. /**
  59008. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59009. * @param size the size (float) of the visibility box
  59010. * note : this doesn't lock the SPS mesh bounding box.
  59011. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59012. */
  59013. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59014. var vis = size / 2;
  59015. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59016. };
  59017. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59018. /**
  59019. * Gets whether the SPS as always visible or not
  59020. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59021. */
  59022. get: function () {
  59023. return this._alwaysVisible;
  59024. },
  59025. /**
  59026. * Sets the SPS as always visible or not
  59027. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59028. */
  59029. set: function (val) {
  59030. this._alwaysVisible = val;
  59031. this.mesh.alwaysSelectAsActiveMesh = val;
  59032. },
  59033. enumerable: true,
  59034. configurable: true
  59035. });
  59036. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59037. /**
  59038. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59039. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59040. */
  59041. get: function () {
  59042. return this._isVisibilityBoxLocked;
  59043. },
  59044. /**
  59045. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59046. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59047. */
  59048. set: function (val) {
  59049. this._isVisibilityBoxLocked = val;
  59050. var boundingInfo = this.mesh.getBoundingInfo();
  59051. boundingInfo.isLocked = val;
  59052. },
  59053. enumerable: true,
  59054. configurable: true
  59055. });
  59056. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59057. /**
  59058. * Gets if `setParticles()` computes the particle rotations or not.
  59059. * Default value : true. The SPS is faster when it's set to false.
  59060. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59061. */
  59062. get: function () {
  59063. return this._computeParticleRotation;
  59064. },
  59065. /**
  59066. * Tells to `setParticles()` to compute the particle rotations or not.
  59067. * Default value : true. The SPS is faster when it's set to false.
  59068. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59069. */
  59070. set: function (val) {
  59071. this._computeParticleRotation = val;
  59072. },
  59073. enumerable: true,
  59074. configurable: true
  59075. });
  59076. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59077. /**
  59078. * Gets if `setParticles()` computes the particle colors or not.
  59079. * Default value : true. The SPS is faster when it's set to false.
  59080. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59081. */
  59082. get: function () {
  59083. return this._computeParticleColor;
  59084. },
  59085. /**
  59086. * Tells to `setParticles()` to compute the particle colors or not.
  59087. * Default value : true. The SPS is faster when it's set to false.
  59088. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59089. */
  59090. set: function (val) {
  59091. this._computeParticleColor = val;
  59092. },
  59093. enumerable: true,
  59094. configurable: true
  59095. });
  59096. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59097. /**
  59098. * Gets if `setParticles()` computes the particle textures or not.
  59099. * Default value : true. The SPS is faster when it's set to false.
  59100. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59101. */
  59102. get: function () {
  59103. return this._computeParticleTexture;
  59104. },
  59105. set: function (val) {
  59106. this._computeParticleTexture = val;
  59107. },
  59108. enumerable: true,
  59109. configurable: true
  59110. });
  59111. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59112. /**
  59113. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59114. * Default value : false. The SPS is faster when it's set to false.
  59115. * Note : the particle custom vertex positions aren't stored values.
  59116. */
  59117. get: function () {
  59118. return this._computeParticleVertex;
  59119. },
  59120. /**
  59121. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59122. * Default value : false. The SPS is faster when it's set to false.
  59123. * Note : the particle custom vertex positions aren't stored values.
  59124. */
  59125. set: function (val) {
  59126. this._computeParticleVertex = val;
  59127. },
  59128. enumerable: true,
  59129. configurable: true
  59130. });
  59131. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59132. /**
  59133. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59134. */
  59135. get: function () {
  59136. return this._computeBoundingBox;
  59137. },
  59138. /**
  59139. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59140. */
  59141. set: function (val) {
  59142. this._computeBoundingBox = val;
  59143. },
  59144. enumerable: true,
  59145. configurable: true
  59146. });
  59147. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59148. /**
  59149. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59150. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59151. * Default : `true`
  59152. */
  59153. get: function () {
  59154. return this._depthSortParticles;
  59155. },
  59156. /**
  59157. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59158. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59159. * Default : `true`
  59160. */
  59161. set: function (val) {
  59162. this._depthSortParticles = val;
  59163. },
  59164. enumerable: true,
  59165. configurable: true
  59166. });
  59167. // =======================================================================
  59168. // Particle behavior logic
  59169. // these following methods may be overwritten by the user to fit his needs
  59170. /**
  59171. * This function does nothing. It may be overwritten to set all the particle first values.
  59172. * The SPS doesn't call this function, you may have to call it by your own.
  59173. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59174. */
  59175. SolidParticleSystem.prototype.initParticles = function () {
  59176. };
  59177. /**
  59178. * This function does nothing. It may be overwritten to recycle a particle.
  59179. * The SPS doesn't call this function, you may have to call it by your own.
  59180. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59181. * @param particle The particle to recycle
  59182. * @returns the recycled particle
  59183. */
  59184. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59185. return particle;
  59186. };
  59187. /**
  59188. * Updates a particle : this function should be overwritten by the user.
  59189. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59190. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59191. * @example : just set a particle position or velocity and recycle conditions
  59192. * @param particle The particle to update
  59193. * @returns the updated particle
  59194. */
  59195. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59196. return particle;
  59197. };
  59198. /**
  59199. * Updates a vertex of a particle : it can be overwritten by the user.
  59200. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59201. * @param particle the current particle
  59202. * @param vertex the current index of the current particle
  59203. * @param pt the index of the current vertex in the particle shape
  59204. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59205. * @example : just set a vertex particle position
  59206. * @returns the updated vertex
  59207. */
  59208. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59209. return vertex;
  59210. };
  59211. /**
  59212. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59213. * This does nothing and may be overwritten by the user.
  59214. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59215. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59216. * @param update the boolean update value actually passed to setParticles()
  59217. */
  59218. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59219. };
  59220. /**
  59221. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59222. * This will be passed three parameters.
  59223. * This does nothing and may be overwritten by the user.
  59224. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59225. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59226. * @param update the boolean update value actually passed to setParticles()
  59227. */
  59228. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59229. };
  59230. return SolidParticleSystem;
  59231. }());
  59232. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59233. })(BABYLON || (BABYLON = {}));
  59234. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59235. var BABYLON;
  59236. (function (BABYLON) {
  59237. var ShaderMaterial = /** @class */ (function (_super) {
  59238. __extends(ShaderMaterial, _super);
  59239. function ShaderMaterial(name, scene, shaderPath, options) {
  59240. var _this = _super.call(this, name, scene) || this;
  59241. _this._textures = {};
  59242. _this._textureArrays = {};
  59243. _this._floats = {};
  59244. _this._ints = {};
  59245. _this._floatsArrays = {};
  59246. _this._colors3 = {};
  59247. _this._colors3Arrays = {};
  59248. _this._colors4 = {};
  59249. _this._vectors2 = {};
  59250. _this._vectors3 = {};
  59251. _this._vectors4 = {};
  59252. _this._matrices = {};
  59253. _this._matrices3x3 = {};
  59254. _this._matrices2x2 = {};
  59255. _this._vectors2Arrays = {};
  59256. _this._vectors3Arrays = {};
  59257. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59258. _this._shaderPath = shaderPath;
  59259. options.needAlphaBlending = options.needAlphaBlending || false;
  59260. options.needAlphaTesting = options.needAlphaTesting || false;
  59261. options.attributes = options.attributes || ["position", "normal", "uv"];
  59262. options.uniforms = options.uniforms || ["worldViewProjection"];
  59263. options.uniformBuffers = options.uniformBuffers || [];
  59264. options.samplers = options.samplers || [];
  59265. options.defines = options.defines || [];
  59266. _this._options = options;
  59267. return _this;
  59268. }
  59269. ShaderMaterial.prototype.getClassName = function () {
  59270. return "ShaderMaterial";
  59271. };
  59272. ShaderMaterial.prototype.needAlphaBlending = function () {
  59273. return this._options.needAlphaBlending;
  59274. };
  59275. ShaderMaterial.prototype.needAlphaTesting = function () {
  59276. return this._options.needAlphaTesting;
  59277. };
  59278. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59279. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59280. this._options.uniforms.push(uniformName);
  59281. }
  59282. };
  59283. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59284. if (this._options.samplers.indexOf(name) === -1) {
  59285. this._options.samplers.push(name);
  59286. }
  59287. this._textures[name] = texture;
  59288. return this;
  59289. };
  59290. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59291. if (this._options.samplers.indexOf(name) === -1) {
  59292. this._options.samplers.push(name);
  59293. }
  59294. this._checkUniform(name);
  59295. this._textureArrays[name] = textures;
  59296. return this;
  59297. };
  59298. ShaderMaterial.prototype.setFloat = function (name, value) {
  59299. this._checkUniform(name);
  59300. this._floats[name] = value;
  59301. return this;
  59302. };
  59303. ShaderMaterial.prototype.setInt = function (name, value) {
  59304. this._checkUniform(name);
  59305. this._ints[name] = value;
  59306. return this;
  59307. };
  59308. ShaderMaterial.prototype.setFloats = function (name, value) {
  59309. this._checkUniform(name);
  59310. this._floatsArrays[name] = value;
  59311. return this;
  59312. };
  59313. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59314. this._checkUniform(name);
  59315. this._colors3[name] = value;
  59316. return this;
  59317. };
  59318. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59319. this._checkUniform(name);
  59320. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59321. color.toArray(arr, arr.length);
  59322. return arr;
  59323. }, []);
  59324. return this;
  59325. };
  59326. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59327. this._checkUniform(name);
  59328. this._colors4[name] = value;
  59329. return this;
  59330. };
  59331. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59332. this._checkUniform(name);
  59333. this._vectors2[name] = value;
  59334. return this;
  59335. };
  59336. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59337. this._checkUniform(name);
  59338. this._vectors3[name] = value;
  59339. return this;
  59340. };
  59341. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59342. this._checkUniform(name);
  59343. this._vectors4[name] = value;
  59344. return this;
  59345. };
  59346. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59347. this._checkUniform(name);
  59348. this._matrices[name] = value;
  59349. return this;
  59350. };
  59351. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59352. this._checkUniform(name);
  59353. this._matrices3x3[name] = value;
  59354. return this;
  59355. };
  59356. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59357. this._checkUniform(name);
  59358. this._matrices2x2[name] = value;
  59359. return this;
  59360. };
  59361. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59362. this._checkUniform(name);
  59363. this._vectors2Arrays[name] = value;
  59364. return this;
  59365. };
  59366. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59367. this._checkUniform(name);
  59368. this._vectors3Arrays[name] = value;
  59369. return this;
  59370. };
  59371. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59372. if (!mesh) {
  59373. return true;
  59374. }
  59375. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59376. return false;
  59377. }
  59378. return false;
  59379. };
  59380. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59381. var scene = this.getScene();
  59382. var engine = scene.getEngine();
  59383. if (!this.checkReadyOnEveryCall) {
  59384. if (this._renderId === scene.getRenderId()) {
  59385. if (this._checkCache(scene, mesh, useInstances)) {
  59386. return true;
  59387. }
  59388. }
  59389. }
  59390. // Instances
  59391. var defines = [];
  59392. var attribs = [];
  59393. var fallbacks = new BABYLON.EffectFallbacks();
  59394. if (useInstances) {
  59395. defines.push("#define INSTANCES");
  59396. }
  59397. for (var index = 0; index < this._options.defines.length; index++) {
  59398. defines.push(this._options.defines[index]);
  59399. }
  59400. for (var index = 0; index < this._options.attributes.length; index++) {
  59401. attribs.push(this._options.attributes[index]);
  59402. }
  59403. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59404. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59405. defines.push("#define VERTEXCOLOR");
  59406. }
  59407. // Bones
  59408. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59409. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59410. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59411. if (mesh.numBoneInfluencers > 4) {
  59412. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59413. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59414. }
  59415. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59416. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59417. fallbacks.addCPUSkinningFallback(0, mesh);
  59418. if (this._options.uniforms.indexOf("mBones") === -1) {
  59419. this._options.uniforms.push("mBones");
  59420. }
  59421. }
  59422. else {
  59423. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59424. }
  59425. // Textures
  59426. for (var name in this._textures) {
  59427. if (!this._textures[name].isReady()) {
  59428. return false;
  59429. }
  59430. }
  59431. // Alpha test
  59432. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59433. defines.push("#define ALPHATEST");
  59434. }
  59435. var previousEffect = this._effect;
  59436. var join = defines.join("\n");
  59437. this._effect = engine.createEffect(this._shaderPath, {
  59438. attributes: attribs,
  59439. uniformsNames: this._options.uniforms,
  59440. uniformBuffersNames: this._options.uniformBuffers,
  59441. samplers: this._options.samplers,
  59442. defines: join,
  59443. fallbacks: fallbacks,
  59444. onCompiled: this.onCompiled,
  59445. onError: this.onError
  59446. }, engine);
  59447. if (!this._effect.isReady()) {
  59448. return false;
  59449. }
  59450. if (previousEffect !== this._effect) {
  59451. scene.resetCachedMaterial();
  59452. }
  59453. this._renderId = scene.getRenderId();
  59454. return true;
  59455. };
  59456. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59457. var scene = this.getScene();
  59458. if (!this._effect) {
  59459. return;
  59460. }
  59461. if (this._options.uniforms.indexOf("world") !== -1) {
  59462. this._effect.setMatrix("world", world);
  59463. }
  59464. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59465. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59466. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59467. }
  59468. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59469. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59470. }
  59471. };
  59472. ShaderMaterial.prototype.bind = function (world, mesh) {
  59473. // Std values
  59474. this.bindOnlyWorldMatrix(world);
  59475. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59476. if (this._options.uniforms.indexOf("view") !== -1) {
  59477. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59478. }
  59479. if (this._options.uniforms.indexOf("projection") !== -1) {
  59480. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59481. }
  59482. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59483. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59484. }
  59485. // Bones
  59486. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59487. var name;
  59488. // Texture
  59489. for (name in this._textures) {
  59490. this._effect.setTexture(name, this._textures[name]);
  59491. }
  59492. // Texture arrays
  59493. for (name in this._textureArrays) {
  59494. this._effect.setTextureArray(name, this._textureArrays[name]);
  59495. }
  59496. // Int
  59497. for (name in this._ints) {
  59498. this._effect.setInt(name, this._ints[name]);
  59499. }
  59500. // Float
  59501. for (name in this._floats) {
  59502. this._effect.setFloat(name, this._floats[name]);
  59503. }
  59504. // Floats
  59505. for (name in this._floatsArrays) {
  59506. this._effect.setArray(name, this._floatsArrays[name]);
  59507. }
  59508. // Color3
  59509. for (name in this._colors3) {
  59510. this._effect.setColor3(name, this._colors3[name]);
  59511. }
  59512. for (name in this._colors3Arrays) {
  59513. this._effect.setArray3(name, this._colors3Arrays[name]);
  59514. }
  59515. // Color4
  59516. for (name in this._colors4) {
  59517. var color = this._colors4[name];
  59518. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59519. }
  59520. // Vector2
  59521. for (name in this._vectors2) {
  59522. this._effect.setVector2(name, this._vectors2[name]);
  59523. }
  59524. // Vector3
  59525. for (name in this._vectors3) {
  59526. this._effect.setVector3(name, this._vectors3[name]);
  59527. }
  59528. // Vector4
  59529. for (name in this._vectors4) {
  59530. this._effect.setVector4(name, this._vectors4[name]);
  59531. }
  59532. // Matrix
  59533. for (name in this._matrices) {
  59534. this._effect.setMatrix(name, this._matrices[name]);
  59535. }
  59536. // Matrix 3x3
  59537. for (name in this._matrices3x3) {
  59538. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59539. }
  59540. // Matrix 2x2
  59541. for (name in this._matrices2x2) {
  59542. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59543. }
  59544. // Vector2Array
  59545. for (name in this._vectors2Arrays) {
  59546. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59547. }
  59548. // Vector3Array
  59549. for (name in this._vectors3Arrays) {
  59550. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59551. }
  59552. }
  59553. this._afterBind(mesh);
  59554. };
  59555. ShaderMaterial.prototype.getActiveTextures = function () {
  59556. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59557. for (var name in this._textures) {
  59558. activeTextures.push(this._textures[name]);
  59559. }
  59560. for (var name in this._textureArrays) {
  59561. var array = this._textureArrays[name];
  59562. for (var index = 0; index < array.length; index++) {
  59563. activeTextures.push(array[index]);
  59564. }
  59565. }
  59566. return activeTextures;
  59567. };
  59568. ShaderMaterial.prototype.hasTexture = function (texture) {
  59569. if (_super.prototype.hasTexture.call(this, texture)) {
  59570. return true;
  59571. }
  59572. for (var name in this._textures) {
  59573. if (this._textures[name] === texture) {
  59574. return true;
  59575. }
  59576. }
  59577. for (var name in this._textureArrays) {
  59578. var array = this._textureArrays[name];
  59579. for (var index = 0; index < array.length; index++) {
  59580. if (array[index] === texture) {
  59581. return true;
  59582. }
  59583. }
  59584. }
  59585. return false;
  59586. };
  59587. ShaderMaterial.prototype.clone = function (name) {
  59588. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59589. return newShaderMaterial;
  59590. };
  59591. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59592. if (forceDisposeTextures) {
  59593. var name;
  59594. for (name in this._textures) {
  59595. this._textures[name].dispose();
  59596. }
  59597. for (name in this._textureArrays) {
  59598. var array = this._textureArrays[name];
  59599. for (var index = 0; index < array.length; index++) {
  59600. array[index].dispose();
  59601. }
  59602. }
  59603. }
  59604. this._textures = {};
  59605. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59606. };
  59607. ShaderMaterial.prototype.serialize = function () {
  59608. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59609. serializationObject.customType = "BABYLON.ShaderMaterial";
  59610. serializationObject.options = this._options;
  59611. serializationObject.shaderPath = this._shaderPath;
  59612. var name;
  59613. // Texture
  59614. serializationObject.textures = {};
  59615. for (name in this._textures) {
  59616. serializationObject.textures[name] = this._textures[name].serialize();
  59617. }
  59618. // Texture arrays
  59619. serializationObject.textureArrays = {};
  59620. for (name in this._textureArrays) {
  59621. serializationObject.textureArrays[name] = [];
  59622. var array = this._textureArrays[name];
  59623. for (var index = 0; index < array.length; index++) {
  59624. serializationObject.textureArrays[name].push(array[index].serialize());
  59625. }
  59626. }
  59627. // Float
  59628. serializationObject.floats = {};
  59629. for (name in this._floats) {
  59630. serializationObject.floats[name] = this._floats[name];
  59631. }
  59632. // Float s
  59633. serializationObject.FloatArrays = {};
  59634. for (name in this._floatsArrays) {
  59635. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59636. }
  59637. // Color3
  59638. serializationObject.colors3 = {};
  59639. for (name in this._colors3) {
  59640. serializationObject.colors3[name] = this._colors3[name].asArray();
  59641. }
  59642. // Color3 array
  59643. serializationObject.colors3Arrays = {};
  59644. for (name in this._colors3Arrays) {
  59645. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59646. }
  59647. // Color4
  59648. serializationObject.colors4 = {};
  59649. for (name in this._colors4) {
  59650. serializationObject.colors4[name] = this._colors4[name].asArray();
  59651. }
  59652. // Vector2
  59653. serializationObject.vectors2 = {};
  59654. for (name in this._vectors2) {
  59655. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59656. }
  59657. // Vector3
  59658. serializationObject.vectors3 = {};
  59659. for (name in this._vectors3) {
  59660. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59661. }
  59662. // Vector4
  59663. serializationObject.vectors4 = {};
  59664. for (name in this._vectors4) {
  59665. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59666. }
  59667. // Matrix
  59668. serializationObject.matrices = {};
  59669. for (name in this._matrices) {
  59670. serializationObject.matrices[name] = this._matrices[name].asArray();
  59671. }
  59672. // Matrix 3x3
  59673. serializationObject.matrices3x3 = {};
  59674. for (name in this._matrices3x3) {
  59675. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59676. }
  59677. // Matrix 2x2
  59678. serializationObject.matrices2x2 = {};
  59679. for (name in this._matrices2x2) {
  59680. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59681. }
  59682. // Vector2Array
  59683. serializationObject.vectors2Arrays = {};
  59684. for (name in this._vectors2Arrays) {
  59685. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59686. }
  59687. // Vector3Array
  59688. serializationObject.vectors3Arrays = {};
  59689. for (name in this._vectors3Arrays) {
  59690. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59691. }
  59692. return serializationObject;
  59693. };
  59694. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59695. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59696. var name;
  59697. // Texture
  59698. for (name in source.textures) {
  59699. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59700. }
  59701. // Texture arrays
  59702. for (name in source.textureArrays) {
  59703. var array = source.textureArrays[name];
  59704. var textureArray = new Array();
  59705. for (var index = 0; index < array.length; index++) {
  59706. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59707. }
  59708. material.setTextureArray(name, textureArray);
  59709. }
  59710. // Float
  59711. for (name in source.floats) {
  59712. material.setFloat(name, source.floats[name]);
  59713. }
  59714. // Float s
  59715. for (name in source.floatsArrays) {
  59716. material.setFloats(name, source.floatsArrays[name]);
  59717. }
  59718. // Color3
  59719. for (name in source.colors3) {
  59720. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59721. }
  59722. // Color3 arrays
  59723. for (name in source.colors3Arrays) {
  59724. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59725. if (i % 3 === 0) {
  59726. arr.push([num]);
  59727. }
  59728. else {
  59729. arr[arr.length - 1].push(num);
  59730. }
  59731. return arr;
  59732. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59733. material.setColor3Array(name, colors);
  59734. }
  59735. // Color4
  59736. for (name in source.colors4) {
  59737. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59738. }
  59739. // Vector2
  59740. for (name in source.vectors2) {
  59741. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59742. }
  59743. // Vector3
  59744. for (name in source.vectors3) {
  59745. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59746. }
  59747. // Vector4
  59748. for (name in source.vectors4) {
  59749. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59750. }
  59751. // Matrix
  59752. for (name in source.matrices) {
  59753. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59754. }
  59755. // Matrix 3x3
  59756. for (name in source.matrices3x3) {
  59757. material.setMatrix3x3(name, source.matrices3x3[name]);
  59758. }
  59759. // Matrix 2x2
  59760. for (name in source.matrices2x2) {
  59761. material.setMatrix2x2(name, source.matrices2x2[name]);
  59762. }
  59763. // Vector2Array
  59764. for (name in source.vectors2Arrays) {
  59765. material.setArray2(name, source.vectors2Arrays[name]);
  59766. }
  59767. // Vector3Array
  59768. for (name in source.vectors3Arrays) {
  59769. material.setArray3(name, source.vectors3Arrays[name]);
  59770. }
  59771. return material;
  59772. };
  59773. return ShaderMaterial;
  59774. }(BABYLON.Material));
  59775. BABYLON.ShaderMaterial = ShaderMaterial;
  59776. })(BABYLON || (BABYLON = {}));
  59777. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59778. var BABYLON;
  59779. (function (BABYLON) {
  59780. var GroundMesh = /** @class */ (function (_super) {
  59781. __extends(GroundMesh, _super);
  59782. function GroundMesh(name, scene) {
  59783. var _this = _super.call(this, name, scene) || this;
  59784. _this.generateOctree = false;
  59785. return _this;
  59786. }
  59787. GroundMesh.prototype.getClassName = function () {
  59788. return "GroundMesh";
  59789. };
  59790. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59791. get: function () {
  59792. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59793. },
  59794. enumerable: true,
  59795. configurable: true
  59796. });
  59797. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59798. get: function () {
  59799. return this._subdivisionsX;
  59800. },
  59801. enumerable: true,
  59802. configurable: true
  59803. });
  59804. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59805. get: function () {
  59806. return this._subdivisionsY;
  59807. },
  59808. enumerable: true,
  59809. configurable: true
  59810. });
  59811. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59812. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59813. this._subdivisionsX = chunksCount;
  59814. this._subdivisionsY = chunksCount;
  59815. this.subdivide(chunksCount);
  59816. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59817. };
  59818. /**
  59819. * Returns a height (y) value in the Worl system :
  59820. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59821. * Returns the ground y position if (x, z) are outside the ground surface.
  59822. */
  59823. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59824. var world = this.getWorldMatrix();
  59825. var invMat = BABYLON.Tmp.Matrix[5];
  59826. world.invertToRef(invMat);
  59827. var tmpVect = BABYLON.Tmp.Vector3[8];
  59828. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59829. x = tmpVect.x;
  59830. z = tmpVect.z;
  59831. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59832. return this.position.y;
  59833. }
  59834. if (!this._heightQuads || this._heightQuads.length == 0) {
  59835. this._initHeightQuads();
  59836. this._computeHeightQuads();
  59837. }
  59838. var facet = this._getFacetAt(x, z);
  59839. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59840. // return y in the World system
  59841. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59842. return tmpVect.y;
  59843. };
  59844. /**
  59845. * Returns a normalized vector (Vector3) orthogonal to the ground
  59846. * at the ground coordinates (x, z) expressed in the World system.
  59847. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59848. */
  59849. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59850. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59851. this.getNormalAtCoordinatesToRef(x, z, normal);
  59852. return normal;
  59853. };
  59854. /**
  59855. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59856. * at the ground coordinates (x, z) expressed in the World system.
  59857. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59858. * Returns the GroundMesh.
  59859. */
  59860. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59861. var world = this.getWorldMatrix();
  59862. var tmpMat = BABYLON.Tmp.Matrix[5];
  59863. world.invertToRef(tmpMat);
  59864. var tmpVect = BABYLON.Tmp.Vector3[8];
  59865. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59866. x = tmpVect.x;
  59867. z = tmpVect.z;
  59868. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59869. return this;
  59870. }
  59871. if (!this._heightQuads || this._heightQuads.length == 0) {
  59872. this._initHeightQuads();
  59873. this._computeHeightQuads();
  59874. }
  59875. var facet = this._getFacetAt(x, z);
  59876. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59877. return this;
  59878. };
  59879. /**
  59880. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59881. * if the ground has been updated.
  59882. * This can be used in the render loop.
  59883. * Returns the GroundMesh.
  59884. */
  59885. GroundMesh.prototype.updateCoordinateHeights = function () {
  59886. if (!this._heightQuads || this._heightQuads.length == 0) {
  59887. this._initHeightQuads();
  59888. }
  59889. this._computeHeightQuads();
  59890. return this;
  59891. };
  59892. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59893. GroundMesh.prototype._getFacetAt = function (x, z) {
  59894. // retrieve col and row from x, z coordinates in the ground local system
  59895. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59896. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59897. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59898. var facet;
  59899. if (z < quad.slope.x * x + quad.slope.y) {
  59900. facet = quad.facet1;
  59901. }
  59902. else {
  59903. facet = quad.facet2;
  59904. }
  59905. return facet;
  59906. };
  59907. // Creates and populates the heightMap array with "facet" elements :
  59908. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59909. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59910. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59911. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59912. // Returns the GroundMesh.
  59913. GroundMesh.prototype._initHeightQuads = function () {
  59914. var subdivisionsX = this._subdivisionsX;
  59915. var subdivisionsY = this._subdivisionsY;
  59916. this._heightQuads = new Array();
  59917. for (var row = 0; row < subdivisionsY; row++) {
  59918. for (var col = 0; col < subdivisionsX; col++) {
  59919. 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) };
  59920. this._heightQuads[row * subdivisionsX + col] = quad;
  59921. }
  59922. }
  59923. return this;
  59924. };
  59925. // Compute each quad element values and update the the heightMap array :
  59926. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59927. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59928. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59929. // Returns the GroundMesh.
  59930. GroundMesh.prototype._computeHeightQuads = function () {
  59931. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59932. if (!positions) {
  59933. return this;
  59934. }
  59935. var v1 = BABYLON.Tmp.Vector3[3];
  59936. var v2 = BABYLON.Tmp.Vector3[2];
  59937. var v3 = BABYLON.Tmp.Vector3[1];
  59938. var v4 = BABYLON.Tmp.Vector3[0];
  59939. var v1v2 = BABYLON.Tmp.Vector3[4];
  59940. var v1v3 = BABYLON.Tmp.Vector3[5];
  59941. var v1v4 = BABYLON.Tmp.Vector3[6];
  59942. var norm1 = BABYLON.Tmp.Vector3[7];
  59943. var norm2 = BABYLON.Tmp.Vector3[8];
  59944. var i = 0;
  59945. var j = 0;
  59946. var k = 0;
  59947. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59948. var h = 0;
  59949. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59950. var d2 = 0;
  59951. var subdivisionsX = this._subdivisionsX;
  59952. var subdivisionsY = this._subdivisionsY;
  59953. for (var row = 0; row < subdivisionsY; row++) {
  59954. for (var col = 0; col < subdivisionsX; col++) {
  59955. i = col * 3;
  59956. j = row * (subdivisionsX + 1) * 3;
  59957. k = (row + 1) * (subdivisionsX + 1) * 3;
  59958. v1.x = positions[j + i];
  59959. v1.y = positions[j + i + 1];
  59960. v1.z = positions[j + i + 2];
  59961. v2.x = positions[j + i + 3];
  59962. v2.y = positions[j + i + 4];
  59963. v2.z = positions[j + i + 5];
  59964. v3.x = positions[k + i];
  59965. v3.y = positions[k + i + 1];
  59966. v3.z = positions[k + i + 2];
  59967. v4.x = positions[k + i + 3];
  59968. v4.y = positions[k + i + 4];
  59969. v4.z = positions[k + i + 5];
  59970. // 2D slope V1V4
  59971. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59972. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59973. // facet equations :
  59974. // we compute each facet normal vector
  59975. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59976. // we compute the value d by applying the equation to v1 which belongs to the plane
  59977. // then we store the facet equation in a Vector4
  59978. v2.subtractToRef(v1, v1v2);
  59979. v3.subtractToRef(v1, v1v3);
  59980. v4.subtractToRef(v1, v1v4);
  59981. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59982. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59983. norm1.normalize();
  59984. norm2.normalize();
  59985. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59986. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59987. var quad = this._heightQuads[row * subdivisionsX + col];
  59988. quad.slope.copyFromFloats(cd, h);
  59989. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59990. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59991. }
  59992. }
  59993. return this;
  59994. };
  59995. GroundMesh.prototype.serialize = function (serializationObject) {
  59996. _super.prototype.serialize.call(this, serializationObject);
  59997. serializationObject.subdivisionsX = this._subdivisionsX;
  59998. serializationObject.subdivisionsY = this._subdivisionsY;
  59999. serializationObject.minX = this._minX;
  60000. serializationObject.maxX = this._maxX;
  60001. serializationObject.minZ = this._minZ;
  60002. serializationObject.maxZ = this._maxZ;
  60003. serializationObject.width = this._width;
  60004. serializationObject.height = this._height;
  60005. };
  60006. GroundMesh.Parse = function (parsedMesh, scene) {
  60007. var result = new GroundMesh(parsedMesh.name, scene);
  60008. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60009. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60010. result._minX = parsedMesh.minX;
  60011. result._maxX = parsedMesh.maxX;
  60012. result._minZ = parsedMesh.minZ;
  60013. result._maxZ = parsedMesh.maxZ;
  60014. result._width = parsedMesh.width;
  60015. result._height = parsedMesh.height;
  60016. return result;
  60017. };
  60018. return GroundMesh;
  60019. }(BABYLON.Mesh));
  60020. BABYLON.GroundMesh = GroundMesh;
  60021. })(BABYLON || (BABYLON = {}));
  60022. //# sourceMappingURL=babylon.groundMesh.js.map
  60023. var BABYLON;
  60024. (function (BABYLON) {
  60025. /**
  60026. * Creates an instance based on a source mesh.
  60027. */
  60028. var InstancedMesh = /** @class */ (function (_super) {
  60029. __extends(InstancedMesh, _super);
  60030. function InstancedMesh(name, source) {
  60031. var _this = _super.call(this, name, source.getScene()) || this;
  60032. source.instances.push(_this);
  60033. _this._sourceMesh = source;
  60034. _this.position.copyFrom(source.position);
  60035. _this.rotation.copyFrom(source.rotation);
  60036. _this.scaling.copyFrom(source.scaling);
  60037. if (source.rotationQuaternion) {
  60038. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60039. }
  60040. _this.infiniteDistance = source.infiniteDistance;
  60041. _this.setPivotMatrix(source.getPivotMatrix());
  60042. _this.refreshBoundingInfo();
  60043. _this._syncSubMeshes();
  60044. return _this;
  60045. }
  60046. /**
  60047. * Returns the string "InstancedMesh".
  60048. */
  60049. InstancedMesh.prototype.getClassName = function () {
  60050. return "InstancedMesh";
  60051. };
  60052. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60053. // Methods
  60054. get: function () {
  60055. return this._sourceMesh.receiveShadows;
  60056. },
  60057. enumerable: true,
  60058. configurable: true
  60059. });
  60060. Object.defineProperty(InstancedMesh.prototype, "material", {
  60061. get: function () {
  60062. return this._sourceMesh.material;
  60063. },
  60064. enumerable: true,
  60065. configurable: true
  60066. });
  60067. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60068. get: function () {
  60069. return this._sourceMesh.visibility;
  60070. },
  60071. enumerable: true,
  60072. configurable: true
  60073. });
  60074. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60075. get: function () {
  60076. return this._sourceMesh.skeleton;
  60077. },
  60078. enumerable: true,
  60079. configurable: true
  60080. });
  60081. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60082. get: function () {
  60083. return this._sourceMesh.renderingGroupId;
  60084. },
  60085. set: function (value) {
  60086. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60087. return;
  60088. }
  60089. //no-op with warning
  60090. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60091. },
  60092. enumerable: true,
  60093. configurable: true
  60094. });
  60095. /**
  60096. * Returns the total number of vertices (integer).
  60097. */
  60098. InstancedMesh.prototype.getTotalVertices = function () {
  60099. return this._sourceMesh.getTotalVertices();
  60100. };
  60101. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60102. get: function () {
  60103. return this._sourceMesh;
  60104. },
  60105. enumerable: true,
  60106. configurable: true
  60107. });
  60108. /**
  60109. * Is this node ready to be used/rendered
  60110. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60111. * @return {boolean} is it ready
  60112. */
  60113. InstancedMesh.prototype.isReady = function (completeCheck) {
  60114. if (completeCheck === void 0) { completeCheck = false; }
  60115. return this._sourceMesh.isReady(completeCheck, true);
  60116. };
  60117. /**
  60118. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60119. */
  60120. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60121. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60122. };
  60123. /**
  60124. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60125. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60126. * The `data` are either a numeric array either a Float32Array.
  60127. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60128. * 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).
  60129. * Note that a new underlying VertexBuffer object is created each call.
  60130. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60131. *
  60132. * Possible `kind` values :
  60133. * - BABYLON.VertexBuffer.PositionKind
  60134. * - BABYLON.VertexBuffer.UVKind
  60135. * - BABYLON.VertexBuffer.UV2Kind
  60136. * - BABYLON.VertexBuffer.UV3Kind
  60137. * - BABYLON.VertexBuffer.UV4Kind
  60138. * - BABYLON.VertexBuffer.UV5Kind
  60139. * - BABYLON.VertexBuffer.UV6Kind
  60140. * - BABYLON.VertexBuffer.ColorKind
  60141. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60142. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60143. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60144. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60145. *
  60146. * Returns the Mesh.
  60147. */
  60148. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60149. if (this.sourceMesh) {
  60150. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60151. }
  60152. return this.sourceMesh;
  60153. };
  60154. /**
  60155. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60156. * If the mesh has no geometry, it is simply returned as it is.
  60157. * The `data` are either a numeric array either a Float32Array.
  60158. * No new underlying VertexBuffer object is created.
  60159. * 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.
  60160. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60161. *
  60162. * Possible `kind` values :
  60163. * - BABYLON.VertexBuffer.PositionKind
  60164. * - BABYLON.VertexBuffer.UVKind
  60165. * - BABYLON.VertexBuffer.UV2Kind
  60166. * - BABYLON.VertexBuffer.UV3Kind
  60167. * - BABYLON.VertexBuffer.UV4Kind
  60168. * - BABYLON.VertexBuffer.UV5Kind
  60169. * - BABYLON.VertexBuffer.UV6Kind
  60170. * - BABYLON.VertexBuffer.ColorKind
  60171. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60172. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60173. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60174. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60175. *
  60176. * Returns the Mesh.
  60177. */
  60178. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60179. if (this.sourceMesh) {
  60180. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60181. }
  60182. return this.sourceMesh;
  60183. };
  60184. /**
  60185. * Sets the mesh indices.
  60186. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60187. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60188. * This method creates a new index buffer each call.
  60189. * Returns the Mesh.
  60190. */
  60191. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60192. if (totalVertices === void 0) { totalVertices = null; }
  60193. if (this.sourceMesh) {
  60194. this.sourceMesh.setIndices(indices, totalVertices);
  60195. }
  60196. return this.sourceMesh;
  60197. };
  60198. /**
  60199. * Boolean : True if the mesh owns the requested kind of data.
  60200. */
  60201. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60202. return this._sourceMesh.isVerticesDataPresent(kind);
  60203. };
  60204. /**
  60205. * Returns an array of indices (IndicesArray).
  60206. */
  60207. InstancedMesh.prototype.getIndices = function () {
  60208. return this._sourceMesh.getIndices();
  60209. };
  60210. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60211. get: function () {
  60212. return this._sourceMesh._positions;
  60213. },
  60214. enumerable: true,
  60215. configurable: true
  60216. });
  60217. /**
  60218. * Sets a new updated BoundingInfo to the mesh.
  60219. * Returns the mesh.
  60220. */
  60221. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60222. var meshBB = this._sourceMesh.getBoundingInfo();
  60223. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60224. this._updateBoundingInfo();
  60225. return this;
  60226. };
  60227. InstancedMesh.prototype._preActivate = function () {
  60228. if (this._currentLOD) {
  60229. this._currentLOD._preActivate();
  60230. }
  60231. return this;
  60232. };
  60233. InstancedMesh.prototype._activate = function (renderId) {
  60234. if (this._currentLOD) {
  60235. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60236. }
  60237. return this;
  60238. };
  60239. /**
  60240. * Returns the current associated LOD AbstractMesh.
  60241. */
  60242. InstancedMesh.prototype.getLOD = function (camera) {
  60243. if (!camera) {
  60244. return this;
  60245. }
  60246. var boundingInfo = this.getBoundingInfo();
  60247. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60248. if (this._currentLOD === this.sourceMesh) {
  60249. return this;
  60250. }
  60251. return this._currentLOD;
  60252. };
  60253. InstancedMesh.prototype._syncSubMeshes = function () {
  60254. this.releaseSubMeshes();
  60255. if (this._sourceMesh.subMeshes) {
  60256. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60257. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60258. }
  60259. }
  60260. return this;
  60261. };
  60262. InstancedMesh.prototype._generatePointsArray = function () {
  60263. return this._sourceMesh._generatePointsArray();
  60264. };
  60265. /**
  60266. * Creates a new InstancedMesh from the current mesh.
  60267. * - name (string) : the cloned mesh name
  60268. * - newParent (optional Node) : the optional Node to parent the clone to.
  60269. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60270. *
  60271. * Returns the clone.
  60272. */
  60273. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60274. var result = this._sourceMesh.createInstance(name);
  60275. // Deep copy
  60276. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60277. // Bounding info
  60278. this.refreshBoundingInfo();
  60279. // Parent
  60280. if (newParent) {
  60281. result.parent = newParent;
  60282. }
  60283. if (!doNotCloneChildren) {
  60284. // Children
  60285. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60286. var mesh = this.getScene().meshes[index];
  60287. if (mesh.parent === this) {
  60288. mesh.clone(mesh.name, result);
  60289. }
  60290. }
  60291. }
  60292. result.computeWorldMatrix(true);
  60293. return result;
  60294. };
  60295. /**
  60296. * Disposes the InstancedMesh.
  60297. * Returns nothing.
  60298. */
  60299. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60300. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60301. // Remove from mesh
  60302. var index = this._sourceMesh.instances.indexOf(this);
  60303. this._sourceMesh.instances.splice(index, 1);
  60304. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60305. };
  60306. return InstancedMesh;
  60307. }(BABYLON.AbstractMesh));
  60308. BABYLON.InstancedMesh = InstancedMesh;
  60309. })(BABYLON || (BABYLON = {}));
  60310. //# sourceMappingURL=babylon.instancedMesh.js.map
  60311. var BABYLON;
  60312. (function (BABYLON) {
  60313. var LinesMesh = /** @class */ (function (_super) {
  60314. __extends(LinesMesh, _super);
  60315. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60316. if (scene === void 0) { scene = null; }
  60317. if (parent === void 0) { parent = null; }
  60318. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60319. _this.useVertexColor = useVertexColor;
  60320. _this.useVertexAlpha = useVertexAlpha;
  60321. _this.color = new BABYLON.Color3(1, 1, 1);
  60322. _this.alpha = 1;
  60323. if (source) {
  60324. _this.color = source.color.clone();
  60325. _this.alpha = source.alpha;
  60326. _this.useVertexColor = source.useVertexColor;
  60327. _this.useVertexAlpha = source.useVertexAlpha;
  60328. }
  60329. _this._intersectionThreshold = 0.1;
  60330. var defines = [];
  60331. var options = {
  60332. attributes: [BABYLON.VertexBuffer.PositionKind],
  60333. uniforms: ["world", "viewProjection"],
  60334. needAlphaBlending: true,
  60335. defines: defines
  60336. };
  60337. if (useVertexAlpha === false) {
  60338. options.needAlphaBlending = false;
  60339. }
  60340. if (!useVertexColor) {
  60341. options.uniforms.push("color");
  60342. }
  60343. else {
  60344. options.defines.push("#define VERTEXCOLOR");
  60345. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60346. }
  60347. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60348. return _this;
  60349. }
  60350. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60351. /**
  60352. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60353. * This margin is expressed in world space coordinates, so its value may vary.
  60354. * Default value is 0.1
  60355. * @returns the intersection Threshold value.
  60356. */
  60357. get: function () {
  60358. return this._intersectionThreshold;
  60359. },
  60360. /**
  60361. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60362. * This margin is expressed in world space coordinates, so its value may vary.
  60363. * @param value the new threshold to apply
  60364. */
  60365. set: function (value) {
  60366. if (this._intersectionThreshold === value) {
  60367. return;
  60368. }
  60369. this._intersectionThreshold = value;
  60370. if (this.geometry) {
  60371. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60372. }
  60373. },
  60374. enumerable: true,
  60375. configurable: true
  60376. });
  60377. /**
  60378. * Returns the string "LineMesh"
  60379. */
  60380. LinesMesh.prototype.getClassName = function () {
  60381. return "LinesMesh";
  60382. };
  60383. Object.defineProperty(LinesMesh.prototype, "material", {
  60384. get: function () {
  60385. return this._colorShader;
  60386. },
  60387. set: function (value) {
  60388. // Do nothing
  60389. },
  60390. enumerable: true,
  60391. configurable: true
  60392. });
  60393. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60394. get: function () {
  60395. return false;
  60396. },
  60397. enumerable: true,
  60398. configurable: true
  60399. });
  60400. LinesMesh.prototype.createInstance = function (name) {
  60401. throw new Error("LinesMeshes do not support createInstance.");
  60402. };
  60403. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60404. if (!this._geometry) {
  60405. return this;
  60406. }
  60407. // VBOs
  60408. this._geometry._bind(this._colorShader.getEffect());
  60409. // Color
  60410. if (!this.useVertexColor) {
  60411. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60412. }
  60413. return this;
  60414. };
  60415. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60416. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60417. return this;
  60418. }
  60419. var engine = this.getScene().getEngine();
  60420. // Draw order
  60421. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60422. return this;
  60423. };
  60424. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60425. this._colorShader.dispose();
  60426. _super.prototype.dispose.call(this, doNotRecurse);
  60427. };
  60428. /**
  60429. * Returns a new LineMesh object cloned from the current one.
  60430. */
  60431. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60432. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60433. };
  60434. return LinesMesh;
  60435. }(BABYLON.Mesh));
  60436. BABYLON.LinesMesh = LinesMesh;
  60437. })(BABYLON || (BABYLON = {}));
  60438. //# sourceMappingURL=babylon.linesMesh.js.map
  60439. var BABYLON;
  60440. (function (BABYLON) {
  60441. /**
  60442. * Class containing static functions to help procedurally build meshes
  60443. */
  60444. var MeshBuilder = /** @class */ (function () {
  60445. function MeshBuilder() {
  60446. }
  60447. MeshBuilder.updateSideOrientation = function (orientation) {
  60448. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60449. return BABYLON.Mesh.DOUBLESIDE;
  60450. }
  60451. if (orientation === undefined || orientation === null) {
  60452. return BABYLON.Mesh.FRONTSIDE;
  60453. }
  60454. return orientation;
  60455. };
  60456. /**
  60457. * Creates a box mesh
  60458. * * The parameter `size` sets the size (float) of each box side (default 1)
  60459. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60460. * * 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)
  60461. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60462. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60463. * * 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
  60464. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60465. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60466. * @param name defines the name of the mesh
  60467. * @param options defines the options used to create the mesh
  60468. * @param scene defines the hosting scene
  60469. * @returns the box mesh
  60470. */
  60471. MeshBuilder.CreateBox = function (name, options, scene) {
  60472. if (scene === void 0) { scene = null; }
  60473. var box = new BABYLON.Mesh(name, scene);
  60474. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60475. box._originalBuilderSideOrientation = options.sideOrientation;
  60476. var vertexData = BABYLON.VertexData.CreateBox(options);
  60477. vertexData.applyToMesh(box, options.updatable);
  60478. return box;
  60479. };
  60480. /**
  60481. * Creates a sphere mesh
  60482. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60483. * * 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`)
  60484. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60485. * * 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
  60486. * * 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)
  60487. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60488. * * 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
  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 options defines the options used to create the mesh
  60492. * @param scene defines the hosting scene
  60493. * @returns the sphere mesh
  60494. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60495. */
  60496. MeshBuilder.CreateSphere = function (name, options, scene) {
  60497. var sphere = new BABYLON.Mesh(name, scene);
  60498. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60499. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60500. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60501. vertexData.applyToMesh(sphere, options.updatable);
  60502. return sphere;
  60503. };
  60504. /**
  60505. * Creates a plane polygonal mesh. By default, this is a disc
  60506. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60507. * * 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
  60508. * * 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
  60509. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60510. * * 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
  60511. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60512. * @param name defines the name of the mesh
  60513. * @param options defines the options used to create the mesh
  60514. * @param scene defines the hosting scene
  60515. * @returns the plane polygonal mesh
  60516. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60517. */
  60518. MeshBuilder.CreateDisc = function (name, options, scene) {
  60519. if (scene === void 0) { scene = null; }
  60520. var disc = new BABYLON.Mesh(name, scene);
  60521. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60522. disc._originalBuilderSideOrientation = options.sideOrientation;
  60523. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60524. vertexData.applyToMesh(disc, options.updatable);
  60525. return disc;
  60526. };
  60527. /**
  60528. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60529. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60530. * * 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`)
  60531. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60532. * * 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
  60533. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60534. * * 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
  60535. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60536. * @param name defines the name of the mesh
  60537. * @param options defines the options used to create the mesh
  60538. * @param scene defines the hosting scene
  60539. * @returns the icosahedron mesh
  60540. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60541. */
  60542. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60543. var sphere = new BABYLON.Mesh(name, scene);
  60544. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60545. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60546. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60547. vertexData.applyToMesh(sphere, options.updatable);
  60548. return sphere;
  60549. };
  60550. ;
  60551. /**
  60552. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60553. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60554. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60555. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60556. * * 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
  60557. * * 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
  60558. * * 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
  60559. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60560. * * 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
  60561. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60562. * * 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
  60563. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60564. * * 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
  60565. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60566. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60567. * @param name defines the name of the mesh
  60568. * @param options defines the options used to create the mesh
  60569. * @param scene defines the hosting scene
  60570. * @returns the ribbon mesh
  60571. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60572. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60573. */
  60574. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60575. if (scene === void 0) { scene = null; }
  60576. var pathArray = options.pathArray;
  60577. var closeArray = options.closeArray;
  60578. var closePath = options.closePath;
  60579. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60580. var instance = options.instance;
  60581. var updatable = options.updatable;
  60582. if (instance) { // existing ribbon instance update
  60583. // positionFunction : ribbon case
  60584. // only pathArray and sideOrientation parameters are taken into account for positions update
  60585. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60586. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60587. var positionFunction = function (positions) {
  60588. var minlg = pathArray[0].length;
  60589. var i = 0;
  60590. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60591. for (var si = 1; si <= ns; si++) {
  60592. for (var p = 0; p < pathArray.length; p++) {
  60593. var path = pathArray[p];
  60594. var l = path.length;
  60595. minlg = (minlg < l) ? minlg : l;
  60596. var j = 0;
  60597. while (j < minlg) {
  60598. positions[i] = path[j].x;
  60599. positions[i + 1] = path[j].y;
  60600. positions[i + 2] = path[j].z;
  60601. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60602. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60603. }
  60604. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60605. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60606. }
  60607. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60608. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60609. }
  60610. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60611. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60612. }
  60613. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60614. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60615. }
  60616. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60617. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60618. }
  60619. j++;
  60620. i += 3;
  60621. }
  60622. if (instance._closePath) {
  60623. positions[i] = path[0].x;
  60624. positions[i + 1] = path[0].y;
  60625. positions[i + 2] = path[0].z;
  60626. i += 3;
  60627. }
  60628. }
  60629. }
  60630. };
  60631. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60632. positionFunction(positions);
  60633. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60634. instance._boundingInfo.update(instance._worldMatrix);
  60635. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60636. if (options.colors) {
  60637. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60638. for (var c = 0; c < options.colors.length; c++) {
  60639. colors[c * 4] = options.colors[c].r;
  60640. colors[c * 4 + 1] = options.colors[c].g;
  60641. colors[c * 4 + 2] = options.colors[c].b;
  60642. colors[c * 4 + 3] = options.colors[c].a;
  60643. }
  60644. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60645. }
  60646. if (options.uvs) {
  60647. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60648. for (var i = 0; i < options.uvs.length; i++) {
  60649. uvs[i * 2] = options.uvs[i].x;
  60650. uvs[i * 2 + 1] = options.uvs[i].y;
  60651. }
  60652. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60653. }
  60654. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60655. var indices = instance.getIndices();
  60656. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60657. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60658. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60659. if (instance._closePath) {
  60660. var indexFirst = 0;
  60661. var indexLast = 0;
  60662. for (var p = 0; p < pathArray.length; p++) {
  60663. indexFirst = instance._idx[p] * 3;
  60664. if (p + 1 < pathArray.length) {
  60665. indexLast = (instance._idx[p + 1] - 1) * 3;
  60666. }
  60667. else {
  60668. indexLast = normals.length - 3;
  60669. }
  60670. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60671. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60672. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60673. normals[indexLast] = normals[indexFirst];
  60674. normals[indexLast + 1] = normals[indexFirst + 1];
  60675. normals[indexLast + 2] = normals[indexFirst + 2];
  60676. }
  60677. }
  60678. if (!(instance.areNormalsFrozen)) {
  60679. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60680. }
  60681. }
  60682. return instance;
  60683. }
  60684. else { // new ribbon creation
  60685. var ribbon = new BABYLON.Mesh(name, scene);
  60686. ribbon._originalBuilderSideOrientation = sideOrientation;
  60687. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60688. if (closePath) {
  60689. ribbon._idx = vertexData._idx;
  60690. }
  60691. ribbon._closePath = closePath;
  60692. ribbon._closeArray = closeArray;
  60693. vertexData.applyToMesh(ribbon, updatable);
  60694. return ribbon;
  60695. }
  60696. };
  60697. /**
  60698. * Creates a cylinder or a cone mesh
  60699. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60700. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60701. * * 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.
  60702. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60703. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60704. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60705. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60706. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60707. * * 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).
  60708. * * 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
  60709. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60710. * * 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
  60711. * * 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.
  60712. * * If `enclose` is false, a ring surface is one element.
  60713. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60714. * * 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
  60715. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60716. * * 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
  60717. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60718. * @param name defines the name of the mesh
  60719. * @param options defines the options used to create the mesh
  60720. * @param scene defines the hosting scene
  60721. * @returns the cylinder mesh
  60722. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60723. */
  60724. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60725. var cylinder = new BABYLON.Mesh(name, scene);
  60726. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60727. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60728. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60729. vertexData.applyToMesh(cylinder, options.updatable);
  60730. return cylinder;
  60731. };
  60732. /**
  60733. * Creates a torus mesh
  60734. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60735. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60736. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60737. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60738. * * 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
  60739. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60740. * @param name defines the name of the mesh
  60741. * @param options defines the options used to create the mesh
  60742. * @param scene defines the hosting scene
  60743. * @returns the torus mesh
  60744. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60745. */
  60746. MeshBuilder.CreateTorus = function (name, options, scene) {
  60747. var torus = new BABYLON.Mesh(name, scene);
  60748. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60749. torus._originalBuilderSideOrientation = options.sideOrientation;
  60750. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60751. vertexData.applyToMesh(torus, options.updatable);
  60752. return torus;
  60753. };
  60754. /**
  60755. * Creates a torus knot mesh
  60756. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60757. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60758. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60759. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60760. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60761. * * 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
  60762. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60763. * @param name defines the name of the mesh
  60764. * @param options defines the options used to create the mesh
  60765. * @param scene defines the hosting scene
  60766. * @returns the torus knot mesh
  60767. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60768. */
  60769. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60770. var torusKnot = new BABYLON.Mesh(name, scene);
  60771. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60772. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60773. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60774. vertexData.applyToMesh(torusKnot, options.updatable);
  60775. return torusKnot;
  60776. };
  60777. /**
  60778. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60779. * * 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
  60780. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60781. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60782. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60783. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60784. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60785. * * 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
  60786. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60787. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60788. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  60789. * @param name defines the name of the new line system
  60790. * @param options defines the options used to create the line system
  60791. * @param scene defines the hosting scene
  60792. * @returns a new line system mesh
  60793. */
  60794. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60795. var instance = options.instance;
  60796. var lines = options.lines;
  60797. var colors = options.colors;
  60798. if (instance) { // lines update
  60799. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60800. var vertexColor;
  60801. var lineColors;
  60802. if (colors) {
  60803. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60804. }
  60805. var i = 0;
  60806. var c = 0;
  60807. for (var l = 0; l < lines.length; l++) {
  60808. var points = lines[l];
  60809. for (var p = 0; p < points.length; p++) {
  60810. positions[i] = points[p].x;
  60811. positions[i + 1] = points[p].y;
  60812. positions[i + 2] = points[p].z;
  60813. if (colors && vertexColor) {
  60814. lineColors = colors[l];
  60815. vertexColor[c] = lineColors[p].r;
  60816. vertexColor[c + 1] = lineColors[p].g;
  60817. vertexColor[c + 2] = lineColors[p].b;
  60818. vertexColor[c + 3] = lineColors[p].a;
  60819. c += 4;
  60820. }
  60821. i += 3;
  60822. }
  60823. }
  60824. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60825. if (colors && vertexColor) {
  60826. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60827. }
  60828. return instance;
  60829. }
  60830. // line system creation
  60831. var useVertexColor = (colors) ? true : false;
  60832. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60833. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60834. vertexData.applyToMesh(lineSystem, options.updatable);
  60835. return lineSystem;
  60836. };
  60837. /**
  60838. * Creates a line mesh
  60839. * 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
  60840. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60841. * * The parameter `points` is an array successive Vector3
  60842. * * 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
  60843. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60844. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60845. * * When updating an instance, remember that only point positions can change, not the number of points
  60846. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60847. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  60848. * @param name defines the name of the new line system
  60849. * @param options defines the options used to create the line system
  60850. * @param scene defines the hosting scene
  60851. * @returns a new line mesh
  60852. */
  60853. MeshBuilder.CreateLines = function (name, options, scene) {
  60854. if (scene === void 0) { scene = null; }
  60855. var colors = (options.colors) ? [options.colors] : null;
  60856. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  60857. return lines;
  60858. };
  60859. /**
  60860. * Creates a dashed line mesh
  60861. * * 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
  60862. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60863. * * The parameter `points` is an array successive Vector3
  60864. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  60865. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  60866. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  60867. * * 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
  60868. * * When updating an instance, remember that only point positions can change, not the number of points
  60869. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60870. * @param name defines the name of the mesh
  60871. * @param options defines the options used to create the mesh
  60872. * @param scene defines the hosting scene
  60873. * @returns the dashed line mesh
  60874. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  60875. */
  60876. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  60877. if (scene === void 0) { scene = null; }
  60878. var points = options.points;
  60879. var instance = options.instance;
  60880. var gapSize = options.gapSize || 1;
  60881. var dashSize = options.dashSize || 3;
  60882. if (instance) { // dashed lines update
  60883. var positionFunction = function (positions) {
  60884. var curvect = BABYLON.Vector3.Zero();
  60885. var nbSeg = positions.length / 6;
  60886. var lg = 0;
  60887. var nb = 0;
  60888. var shft = 0;
  60889. var dashshft = 0;
  60890. var curshft = 0;
  60891. var p = 0;
  60892. var i = 0;
  60893. var j = 0;
  60894. for (i = 0; i < points.length - 1; i++) {
  60895. points[i + 1].subtractToRef(points[i], curvect);
  60896. lg += curvect.length();
  60897. }
  60898. shft = lg / nbSeg;
  60899. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  60900. for (i = 0; i < points.length - 1; i++) {
  60901. points[i + 1].subtractToRef(points[i], curvect);
  60902. nb = Math.floor(curvect.length() / shft);
  60903. curvect.normalize();
  60904. j = 0;
  60905. while (j < nb && p < positions.length) {
  60906. curshft = shft * j;
  60907. positions[p] = points[i].x + curshft * curvect.x;
  60908. positions[p + 1] = points[i].y + curshft * curvect.y;
  60909. positions[p + 2] = points[i].z + curshft * curvect.z;
  60910. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  60911. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  60912. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  60913. p += 6;
  60914. j++;
  60915. }
  60916. }
  60917. while (p < positions.length) {
  60918. positions[p] = points[i].x;
  60919. positions[p + 1] = points[i].y;
  60920. positions[p + 2] = points[i].z;
  60921. p += 3;
  60922. }
  60923. };
  60924. instance.updateMeshPositions(positionFunction, false);
  60925. return instance;
  60926. }
  60927. // dashed lines creation
  60928. var dashedLines = new BABYLON.LinesMesh(name, scene);
  60929. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  60930. vertexData.applyToMesh(dashedLines, options.updatable);
  60931. dashedLines.dashSize = dashSize;
  60932. dashedLines.gapSize = gapSize;
  60933. return dashedLines;
  60934. };
  60935. /**
  60936. * 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.
  60937. * * 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.
  60938. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60939. * * 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.
  60940. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  60941. * * 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
  60942. * * 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
  60943. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  60944. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60945. * * 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
  60946. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  60947. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60948. * @param name defines the name of the mesh
  60949. * @param options defines the options used to create the mesh
  60950. * @param scene defines the hosting scene
  60951. * @returns the extruded shape mesh
  60952. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60953. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60954. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60955. */
  60956. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  60957. if (scene === void 0) { scene = null; }
  60958. var path = options.path;
  60959. var shape = options.shape;
  60960. var scale = options.scale || 1;
  60961. var rotation = options.rotation || 0;
  60962. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60963. var updatable = options.updatable;
  60964. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60965. var instance = options.instance || null;
  60966. var invertUV = options.invertUV || false;
  60967. 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);
  60968. };
  60969. /**
  60970. * Creates an custom extruded shape mesh.
  60971. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  60972. * * 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.
  60973. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60974. * * 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
  60975. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  60976. * * 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
  60977. * * It must returns a float value that will be the scale value applied to the shape on each path point
  60978. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  60979. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  60980. * * 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
  60981. * * 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
  60982. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  60983. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60984. * * 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
  60985. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60986. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60987. * @param name defines the name of the mesh
  60988. * @param options defines the options used to create the mesh
  60989. * @param scene defines the hosting scene
  60990. * @returns the custom extruded shape mesh
  60991. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  60992. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60993. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60994. */
  60995. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  60996. var path = options.path;
  60997. var shape = options.shape;
  60998. var scaleFunction = options.scaleFunction || (function () { return 1; });
  60999. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61000. var ribbonCloseArray = options.ribbonCloseArray || false;
  61001. var ribbonClosePath = options.ribbonClosePath || false;
  61002. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61003. var updatable = options.updatable;
  61004. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61005. var instance = options.instance;
  61006. var invertUV = options.invertUV || false;
  61007. 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);
  61008. };
  61009. /**
  61010. * Creates lathe mesh.
  61011. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61012. * * 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
  61013. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61014. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61015. * * 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
  61016. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61017. * * 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
  61018. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61019. * * 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
  61020. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61021. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61022. * @param name defines the name of the mesh
  61023. * @param options defines the options used to create the mesh
  61024. * @param scene defines the hosting scene
  61025. * @returns the lathe mesh
  61026. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61027. */
  61028. MeshBuilder.CreateLathe = function (name, options, scene) {
  61029. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61030. var closed = (options.closed === undefined) ? true : options.closed;
  61031. var shape = options.shape;
  61032. var radius = options.radius || 1;
  61033. var tessellation = options.tessellation || 64;
  61034. var updatable = options.updatable;
  61035. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61036. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61037. var pi2 = Math.PI * 2;
  61038. var paths = new Array();
  61039. var invertUV = options.invertUV || false;
  61040. var i = 0;
  61041. var p = 0;
  61042. var step = pi2 / tessellation * arc;
  61043. var rotated;
  61044. var path = new Array();
  61045. ;
  61046. for (i = 0; i <= tessellation; i++) {
  61047. var path = [];
  61048. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61049. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61050. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61051. }
  61052. for (p = 0; p < shape.length; p++) {
  61053. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61054. path.push(rotated);
  61055. }
  61056. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61057. 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));
  61058. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61059. }
  61060. paths.push(path);
  61061. }
  61062. // lathe ribbon
  61063. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61064. return lathe;
  61065. };
  61066. /**
  61067. * Creates a plane mesh
  61068. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61069. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61070. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61071. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61072. * * 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
  61073. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61074. * @param name defines the name of the mesh
  61075. * @param options defines the options used to create the mesh
  61076. * @param scene defines the hosting scene
  61077. * @returns the plane mesh
  61078. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61079. */
  61080. MeshBuilder.CreatePlane = function (name, options, scene) {
  61081. var plane = new BABYLON.Mesh(name, scene);
  61082. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61083. plane._originalBuilderSideOrientation = options.sideOrientation;
  61084. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61085. vertexData.applyToMesh(plane, options.updatable);
  61086. if (options.sourcePlane) {
  61087. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61088. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61089. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61090. plane.rotate(vectorProduct, product);
  61091. }
  61092. return plane;
  61093. };
  61094. /**
  61095. * Creates a ground mesh
  61096. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61097. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61098. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61099. * @param name defines the name of the mesh
  61100. * @param options defines the options used to create the mesh
  61101. * @param scene defines the hosting scene
  61102. * @returns the ground mesh
  61103. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61104. */
  61105. MeshBuilder.CreateGround = function (name, options, scene) {
  61106. var ground = new BABYLON.GroundMesh(name, scene);
  61107. ground._setReady(false);
  61108. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61109. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61110. ground._width = options.width || 1;
  61111. ground._height = options.height || 1;
  61112. ground._maxX = ground._width / 2;
  61113. ground._maxZ = ground._height / 2;
  61114. ground._minX = -ground._maxX;
  61115. ground._minZ = -ground._maxZ;
  61116. var vertexData = BABYLON.VertexData.CreateGround(options);
  61117. vertexData.applyToMesh(ground, options.updatable);
  61118. ground._setReady(true);
  61119. return ground;
  61120. };
  61121. /**
  61122. * Creates a tiled ground mesh
  61123. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61124. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61125. * * 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
  61126. * * 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
  61127. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61128. * @param name defines the name of the mesh
  61129. * @param options defines the options used to create the mesh
  61130. * @param scene defines the hosting scene
  61131. * @returns the tiled ground mesh
  61132. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61133. */
  61134. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61135. var tiledGround = new BABYLON.Mesh(name, scene);
  61136. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61137. vertexData.applyToMesh(tiledGround, options.updatable);
  61138. return tiledGround;
  61139. };
  61140. /**
  61141. * Creates a ground mesh from a height map
  61142. * * The parameter `url` sets the URL of the height map image resource.
  61143. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61144. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61145. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61146. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61147. * * 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.
  61148. * * 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).
  61149. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61150. * @param name defines the name of the mesh
  61151. * @param url defines the url to the height map
  61152. * @param options defines the options used to create the mesh
  61153. * @param scene defines the hosting scene
  61154. * @returns the ground mesh
  61155. * @see http://doc.babylonjs.com/babylon101/height_map
  61156. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61157. */
  61158. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61159. var width = options.width || 10.0;
  61160. var height = options.height || 10.0;
  61161. var subdivisions = options.subdivisions || 1 | 0;
  61162. var minHeight = options.minHeight || 0.0;
  61163. var maxHeight = options.maxHeight || 1.0;
  61164. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61165. var updatable = options.updatable;
  61166. var onReady = options.onReady;
  61167. var ground = new BABYLON.GroundMesh(name, scene);
  61168. ground._subdivisionsX = subdivisions;
  61169. ground._subdivisionsY = subdivisions;
  61170. ground._width = width;
  61171. ground._height = height;
  61172. ground._maxX = ground._width / 2.0;
  61173. ground._maxZ = ground._height / 2.0;
  61174. ground._minX = -ground._maxX;
  61175. ground._minZ = -ground._maxZ;
  61176. ground._setReady(false);
  61177. var onload = function (img) {
  61178. // Getting height map data
  61179. var canvas = document.createElement("canvas");
  61180. var context = canvas.getContext("2d");
  61181. if (!context) {
  61182. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61183. }
  61184. if (scene.isDisposed) {
  61185. return;
  61186. }
  61187. var bufferWidth = img.width;
  61188. var bufferHeight = img.height;
  61189. canvas.width = bufferWidth;
  61190. canvas.height = bufferHeight;
  61191. context.drawImage(img, 0, 0);
  61192. // Create VertexData from map data
  61193. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61194. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61195. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61196. width: width, height: height,
  61197. subdivisions: subdivisions,
  61198. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61199. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61200. });
  61201. vertexData.applyToMesh(ground, updatable);
  61202. //execute ready callback, if set
  61203. if (onReady) {
  61204. onReady(ground);
  61205. }
  61206. ground._setReady(true);
  61207. };
  61208. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61209. return ground;
  61210. };
  61211. /**
  61212. * Creates a polygon mesh
  61213. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61214. * * 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
  61215. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61216. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61217. * * 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)
  61218. * * Remember you can only change the shape positions, not their number when updating a polygon
  61219. * @param name defines the name of the mesh
  61220. * @param options defines the options used to create the mesh
  61221. * @param scene defines the hosting scene
  61222. * @returns the polygon mesh
  61223. */
  61224. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61225. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61226. var shape = options.shape;
  61227. var holes = options.holes || [];
  61228. var depth = options.depth || 0;
  61229. var contours = [];
  61230. var hole = [];
  61231. for (var i = 0; i < shape.length; i++) {
  61232. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61233. }
  61234. var epsilon = 0.00000001;
  61235. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61236. contours.pop();
  61237. }
  61238. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61239. for (var hNb = 0; hNb < holes.length; hNb++) {
  61240. hole = [];
  61241. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61242. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61243. }
  61244. polygonTriangulation.addHole(hole);
  61245. }
  61246. var polygon = polygonTriangulation.build(options.updatable, depth);
  61247. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61248. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61249. vertexData.applyToMesh(polygon, options.updatable);
  61250. return polygon;
  61251. };
  61252. ;
  61253. /**
  61254. * Creates an extruded polygon mesh, with depth in the Y direction.
  61255. * * 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)
  61256. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61257. * @param name defines the name of the mesh
  61258. * @param options defines the options used to create the mesh
  61259. * @param scene defines the hosting scene
  61260. * @returns the polygon mesh
  61261. */
  61262. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61263. return MeshBuilder.CreatePolygon(name, options, scene);
  61264. };
  61265. ;
  61266. /**
  61267. * Creates a tube mesh.
  61268. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61269. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61270. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61271. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61272. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61273. * * 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)
  61274. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61275. * * 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
  61276. * * 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
  61277. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61278. * * 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
  61279. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61280. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61281. * @param name defines the name of the mesh
  61282. * @param options defines the options used to create the mesh
  61283. * @param scene defines the hosting scene
  61284. * @returns the tube mesh
  61285. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61286. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61287. */
  61288. MeshBuilder.CreateTube = function (name, options, scene) {
  61289. var path = options.path;
  61290. var instance = options.instance;
  61291. var radius = 1.0;
  61292. if (instance) {
  61293. radius = instance.radius;
  61294. }
  61295. if (options.radius !== undefined) {
  61296. radius = options.radius;
  61297. }
  61298. ;
  61299. var tessellation = options.tessellation || 64 | 0;
  61300. var radiusFunction = options.radiusFunction || null;
  61301. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61302. var invertUV = options.invertUV || false;
  61303. var updatable = options.updatable;
  61304. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61305. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61306. // tube geometry
  61307. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61308. var tangents = path3D.getTangents();
  61309. var normals = path3D.getNormals();
  61310. var distances = path3D.getDistances();
  61311. var pi2 = Math.PI * 2;
  61312. var step = pi2 / tessellation * arc;
  61313. var returnRadius = function () { return radius; };
  61314. var radiusFunctionFinal = radiusFunction || returnRadius;
  61315. var circlePath;
  61316. var rad;
  61317. var normal;
  61318. var rotated;
  61319. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61320. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61321. for (var i = 0; i < path.length; i++) {
  61322. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61323. circlePath = Array(); // current circle array
  61324. normal = normals[i]; // current normal
  61325. for (var t = 0; t < tessellation; t++) {
  61326. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61327. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61328. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61329. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61330. circlePath[t] = rotated;
  61331. }
  61332. circlePaths[index] = circlePath;
  61333. index++;
  61334. }
  61335. // cap
  61336. var capPath = function (nbPoints, pathIndex) {
  61337. var pointCap = Array();
  61338. for (var i = 0; i < nbPoints; i++) {
  61339. pointCap.push(path[pathIndex]);
  61340. }
  61341. return pointCap;
  61342. };
  61343. switch (cap) {
  61344. case BABYLON.Mesh.NO_CAP:
  61345. break;
  61346. case BABYLON.Mesh.CAP_START:
  61347. circlePaths[0] = capPath(tessellation, 0);
  61348. circlePaths[1] = circlePaths[2].slice(0);
  61349. break;
  61350. case BABYLON.Mesh.CAP_END:
  61351. circlePaths[index] = circlePaths[index - 1].slice(0);
  61352. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61353. break;
  61354. case BABYLON.Mesh.CAP_ALL:
  61355. circlePaths[0] = capPath(tessellation, 0);
  61356. circlePaths[1] = circlePaths[2].slice(0);
  61357. circlePaths[index] = circlePaths[index - 1].slice(0);
  61358. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61359. break;
  61360. default:
  61361. break;
  61362. }
  61363. return circlePaths;
  61364. };
  61365. var path3D;
  61366. var pathArray;
  61367. if (instance) { // tube update
  61368. var arc = options.arc || instance.arc;
  61369. path3D = (instance.path3D).update(path);
  61370. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61371. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61372. instance.path3D = path3D;
  61373. instance.pathArray = pathArray;
  61374. instance.arc = arc;
  61375. instance.radius = radius;
  61376. return instance;
  61377. }
  61378. // tube creation
  61379. path3D = new BABYLON.Path3D(path);
  61380. var newPathArray = new Array();
  61381. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61382. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61383. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61384. tube.pathArray = pathArray;
  61385. tube.path3D = path3D;
  61386. tube.tessellation = tessellation;
  61387. tube.cap = cap;
  61388. tube.arc = options.arc;
  61389. tube.radius = radius;
  61390. return tube;
  61391. };
  61392. /**
  61393. * Creates a polyhedron mesh
  61394. * * 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
  61395. * * The parameter `size` (positive float, default 1) sets the polygon size
  61396. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61397. * * 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`
  61398. * * 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
  61399. * * 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)`)
  61400. * * 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
  61401. * * 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
  61402. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61403. * * 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
  61404. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61405. * @param name defines the name of the mesh
  61406. * @param options defines the options used to create the mesh
  61407. * @param scene defines the hosting scene
  61408. * @returns the polyhedron mesh
  61409. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61410. */
  61411. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61412. var polyhedron = new BABYLON.Mesh(name, scene);
  61413. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61414. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61415. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61416. vertexData.applyToMesh(polyhedron, options.updatable);
  61417. return polyhedron;
  61418. };
  61419. /**
  61420. * Creates a decal mesh.
  61421. * 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
  61422. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61423. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61424. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61425. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61426. * @param name defines the name of the mesh
  61427. * @param sourceMesh defines the mesh where the decal must be applied
  61428. * @param options defines the options used to create the mesh
  61429. * @param scene defines the hosting scene
  61430. * @returns the decal mesh
  61431. * @see http://doc.babylonjs.com/how_to/decals
  61432. */
  61433. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61434. var indices = sourceMesh.getIndices();
  61435. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61436. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61437. var position = options.position || BABYLON.Vector3.Zero();
  61438. var normal = options.normal || BABYLON.Vector3.Up();
  61439. var size = options.size || BABYLON.Vector3.One();
  61440. var angle = options.angle || 0;
  61441. // Getting correct rotation
  61442. if (!normal) {
  61443. var target = new BABYLON.Vector3(0, 0, 1);
  61444. var camera = sourceMesh.getScene().activeCamera;
  61445. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61446. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61447. }
  61448. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61449. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61450. var pitch = Math.atan2(normal.y, len);
  61451. // Matrix
  61452. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61453. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61454. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61455. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61456. var vertexData = new BABYLON.VertexData();
  61457. vertexData.indices = [];
  61458. vertexData.positions = [];
  61459. vertexData.normals = [];
  61460. vertexData.uvs = [];
  61461. var currentVertexDataIndex = 0;
  61462. var extractDecalVector3 = function (indexId) {
  61463. var result = new BABYLON.PositionNormalVertex();
  61464. if (!indices || !positions || !normals) {
  61465. return result;
  61466. }
  61467. var vertexId = indices[indexId];
  61468. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61469. // Send vector to decal local world
  61470. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61471. // Get normal
  61472. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61473. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61474. return result;
  61475. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61476. var clip = function (vertices, axis) {
  61477. if (vertices.length === 0) {
  61478. return vertices;
  61479. }
  61480. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61481. var clipVertices = function (v0, v1) {
  61482. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61483. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61484. };
  61485. var result = new Array();
  61486. for (var index = 0; index < vertices.length; index += 3) {
  61487. var v1Out;
  61488. var v2Out;
  61489. var v3Out;
  61490. var total = 0;
  61491. var nV1 = null;
  61492. var nV2 = null;
  61493. var nV3 = null;
  61494. var nV4 = null;
  61495. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61496. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61497. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61498. v1Out = d1 > 0;
  61499. v2Out = d2 > 0;
  61500. v3Out = d3 > 0;
  61501. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61502. switch (total) {
  61503. case 0:
  61504. result.push(vertices[index]);
  61505. result.push(vertices[index + 1]);
  61506. result.push(vertices[index + 2]);
  61507. break;
  61508. case 1:
  61509. if (v1Out) {
  61510. nV1 = vertices[index + 1];
  61511. nV2 = vertices[index + 2];
  61512. nV3 = clipVertices(vertices[index], nV1);
  61513. nV4 = clipVertices(vertices[index], nV2);
  61514. }
  61515. if (v2Out) {
  61516. nV1 = vertices[index];
  61517. nV2 = vertices[index + 2];
  61518. nV3 = clipVertices(vertices[index + 1], nV1);
  61519. nV4 = clipVertices(vertices[index + 1], nV2);
  61520. result.push(nV3);
  61521. result.push(nV2.clone());
  61522. result.push(nV1.clone());
  61523. result.push(nV2.clone());
  61524. result.push(nV3.clone());
  61525. result.push(nV4);
  61526. break;
  61527. }
  61528. if (v3Out) {
  61529. nV1 = vertices[index];
  61530. nV2 = vertices[index + 1];
  61531. nV3 = clipVertices(vertices[index + 2], nV1);
  61532. nV4 = clipVertices(vertices[index + 2], nV2);
  61533. }
  61534. if (nV1 && nV2 && nV3 && nV4) {
  61535. result.push(nV1.clone());
  61536. result.push(nV2.clone());
  61537. result.push(nV3);
  61538. result.push(nV4);
  61539. result.push(nV3.clone());
  61540. result.push(nV2.clone());
  61541. }
  61542. break;
  61543. case 2:
  61544. if (!v1Out) {
  61545. nV1 = vertices[index].clone();
  61546. nV2 = clipVertices(nV1, vertices[index + 1]);
  61547. nV3 = clipVertices(nV1, vertices[index + 2]);
  61548. result.push(nV1);
  61549. result.push(nV2);
  61550. result.push(nV3);
  61551. }
  61552. if (!v2Out) {
  61553. nV1 = vertices[index + 1].clone();
  61554. nV2 = clipVertices(nV1, vertices[index + 2]);
  61555. nV3 = clipVertices(nV1, vertices[index]);
  61556. result.push(nV1);
  61557. result.push(nV2);
  61558. result.push(nV3);
  61559. }
  61560. if (!v3Out) {
  61561. nV1 = vertices[index + 2].clone();
  61562. nV2 = clipVertices(nV1, vertices[index]);
  61563. nV3 = clipVertices(nV1, vertices[index + 1]);
  61564. result.push(nV1);
  61565. result.push(nV2);
  61566. result.push(nV3);
  61567. }
  61568. break;
  61569. case 3:
  61570. break;
  61571. }
  61572. }
  61573. return result;
  61574. };
  61575. for (var index = 0; index < indices.length; index += 3) {
  61576. var faceVertices = new Array();
  61577. faceVertices.push(extractDecalVector3(index));
  61578. faceVertices.push(extractDecalVector3(index + 1));
  61579. faceVertices.push(extractDecalVector3(index + 2));
  61580. // Clip
  61581. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61582. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61583. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61584. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61585. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61586. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61587. if (faceVertices.length === 0) {
  61588. continue;
  61589. }
  61590. // Add UVs and get back to world
  61591. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61592. var vertex = faceVertices[vIndex];
  61593. //TODO check for Int32Array | Uint32Array | Uint16Array
  61594. vertexData.indices.push(currentVertexDataIndex);
  61595. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61596. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61597. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61598. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61599. currentVertexDataIndex++;
  61600. }
  61601. }
  61602. // Return mesh
  61603. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61604. vertexData.applyToMesh(decal);
  61605. decal.position = position.clone();
  61606. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61607. return decal;
  61608. };
  61609. // Privates
  61610. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61611. // extrusion geometry
  61612. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61613. var tangents = path3D.getTangents();
  61614. var normals = path3D.getNormals();
  61615. var binormals = path3D.getBinormals();
  61616. var distances = path3D.getDistances();
  61617. var angle = 0;
  61618. var returnScale = function () { return scale !== null ? scale : 1; };
  61619. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61620. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61621. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61622. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61623. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61624. for (var i = 0; i < curve.length; i++) {
  61625. var shapePath = new Array();
  61626. var angleStep = rotate(i, distances[i]);
  61627. var scaleRatio = scl(i, distances[i]);
  61628. for (var p = 0; p < shape.length; p++) {
  61629. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61630. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61631. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61632. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61633. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61634. shapePath[p] = rotated;
  61635. }
  61636. shapePaths[index] = shapePath;
  61637. angle += angleStep;
  61638. index++;
  61639. }
  61640. // cap
  61641. var capPath = function (shapePath) {
  61642. var pointCap = Array();
  61643. var barycenter = BABYLON.Vector3.Zero();
  61644. var i;
  61645. for (i = 0; i < shapePath.length; i++) {
  61646. barycenter.addInPlace(shapePath[i]);
  61647. }
  61648. barycenter.scaleInPlace(1.0 / shapePath.length);
  61649. for (i = 0; i < shapePath.length; i++) {
  61650. pointCap.push(barycenter);
  61651. }
  61652. return pointCap;
  61653. };
  61654. switch (cap) {
  61655. case BABYLON.Mesh.NO_CAP:
  61656. break;
  61657. case BABYLON.Mesh.CAP_START:
  61658. shapePaths[0] = capPath(shapePaths[2]);
  61659. shapePaths[1] = shapePaths[2];
  61660. break;
  61661. case BABYLON.Mesh.CAP_END:
  61662. shapePaths[index] = shapePaths[index - 1];
  61663. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61664. break;
  61665. case BABYLON.Mesh.CAP_ALL:
  61666. shapePaths[0] = capPath(shapePaths[2]);
  61667. shapePaths[1] = shapePaths[2];
  61668. shapePaths[index] = shapePaths[index - 1];
  61669. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61670. break;
  61671. default:
  61672. break;
  61673. }
  61674. return shapePaths;
  61675. };
  61676. var path3D;
  61677. var pathArray;
  61678. if (instance) { // instance update
  61679. path3D = (instance.path3D).update(curve);
  61680. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61681. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61682. return instance;
  61683. }
  61684. // extruded shape creation
  61685. path3D = new BABYLON.Path3D(curve);
  61686. var newShapePaths = new Array();
  61687. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61688. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61689. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61690. extrudedGeneric.pathArray = pathArray;
  61691. extrudedGeneric.path3D = path3D;
  61692. extrudedGeneric.cap = cap;
  61693. return extrudedGeneric;
  61694. };
  61695. return MeshBuilder;
  61696. }());
  61697. BABYLON.MeshBuilder = MeshBuilder;
  61698. })(BABYLON || (BABYLON = {}));
  61699. //# sourceMappingURL=babylon.meshBuilder.js.map
  61700. var BABYLON;
  61701. (function (BABYLON) {
  61702. /**
  61703. * Draco compression (https://google.github.io/draco/)
  61704. */
  61705. var DracoCompression = /** @class */ (function () {
  61706. /**
  61707. * Constructor
  61708. */
  61709. function DracoCompression() {
  61710. }
  61711. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61712. /**
  61713. * Returns true if the decoder is available.
  61714. */
  61715. get: function () {
  61716. if (typeof DracoDecoderModule !== "undefined") {
  61717. return true;
  61718. }
  61719. var decoder = DracoCompression.Configuration.decoder;
  61720. if (decoder) {
  61721. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61722. return true;
  61723. }
  61724. if (decoder.fallbackUrl) {
  61725. return true;
  61726. }
  61727. }
  61728. return false;
  61729. },
  61730. enumerable: true,
  61731. configurable: true
  61732. });
  61733. /**
  61734. * Stop all async operations and release resources.
  61735. */
  61736. DracoCompression.prototype.dispose = function () {
  61737. };
  61738. /**
  61739. * Decode Draco compressed mesh data to vertex data.
  61740. * @param data The array buffer view for the Draco compression data
  61741. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61742. * @returns A promise that resolves with the decoded vertex data
  61743. */
  61744. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61745. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61746. var module = wrappedModule.module;
  61747. var vertexData = new BABYLON.VertexData();
  61748. var buffer = new module.DecoderBuffer();
  61749. buffer.Init(data, data.byteLength);
  61750. var decoder = new module.Decoder();
  61751. var geometry;
  61752. var status;
  61753. try {
  61754. var type = decoder.GetEncodedGeometryType(buffer);
  61755. switch (type) {
  61756. case module.TRIANGULAR_MESH:
  61757. geometry = new module.Mesh();
  61758. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61759. break;
  61760. case module.POINT_CLOUD:
  61761. geometry = new module.PointCloud();
  61762. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61763. break;
  61764. default:
  61765. throw new Error("Invalid geometry type " + type);
  61766. }
  61767. if (!status.ok() || !geometry.ptr) {
  61768. throw new Error(status.error_msg());
  61769. }
  61770. var numPoints = geometry.num_points();
  61771. if (type === module.TRIANGULAR_MESH) {
  61772. var numFaces = geometry.num_faces();
  61773. var faceIndices = new module.DracoInt32Array();
  61774. try {
  61775. var indices = new Uint32Array(numFaces * 3);
  61776. for (var i = 0; i < numFaces; i++) {
  61777. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61778. var offset = i * 3;
  61779. indices[offset + 0] = faceIndices.GetValue(0);
  61780. indices[offset + 1] = faceIndices.GetValue(1);
  61781. indices[offset + 2] = faceIndices.GetValue(2);
  61782. }
  61783. vertexData.indices = indices;
  61784. }
  61785. finally {
  61786. module.destroy(faceIndices);
  61787. }
  61788. }
  61789. for (var kind in attributes) {
  61790. var uniqueId = attributes[kind];
  61791. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61792. var dracoData = new module.DracoFloat32Array();
  61793. try {
  61794. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61795. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61796. for (var i = 0; i < babylonData.length; i++) {
  61797. babylonData[i] = dracoData.GetValue(i);
  61798. }
  61799. vertexData.set(babylonData, kind);
  61800. }
  61801. finally {
  61802. module.destroy(dracoData);
  61803. }
  61804. }
  61805. }
  61806. finally {
  61807. if (geometry) {
  61808. module.destroy(geometry);
  61809. }
  61810. module.destroy(decoder);
  61811. module.destroy(buffer);
  61812. }
  61813. return vertexData;
  61814. });
  61815. };
  61816. DracoCompression._GetDecoderModule = function () {
  61817. if (!DracoCompression._DecoderModulePromise) {
  61818. var promise = null;
  61819. var config_1 = {};
  61820. if (typeof DracoDecoderModule !== "undefined") {
  61821. promise = Promise.resolve();
  61822. }
  61823. else {
  61824. var decoder = DracoCompression.Configuration.decoder;
  61825. if (decoder) {
  61826. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61827. promise = Promise.all([
  61828. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61829. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61830. config_1.wasmBinary = data;
  61831. })
  61832. ]);
  61833. }
  61834. else if (decoder.fallbackUrl) {
  61835. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61836. }
  61837. }
  61838. }
  61839. if (!promise) {
  61840. throw new Error("Draco decoder module is not available");
  61841. }
  61842. DracoCompression._DecoderModulePromise = promise.then(function () {
  61843. return new Promise(function (resolve) {
  61844. config_1.onModuleLoaded = function (decoderModule) {
  61845. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61846. resolve({ module: decoderModule });
  61847. };
  61848. DracoDecoderModule(config_1);
  61849. });
  61850. });
  61851. }
  61852. return DracoCompression._DecoderModulePromise;
  61853. };
  61854. DracoCompression._LoadScriptAsync = function (url) {
  61855. return new Promise(function (resolve, reject) {
  61856. BABYLON.Tools.LoadScript(url, function () {
  61857. resolve();
  61858. }, function (message) {
  61859. reject(new Error(message));
  61860. });
  61861. });
  61862. };
  61863. DracoCompression._LoadFileAsync = function (url) {
  61864. return new Promise(function (resolve, reject) {
  61865. BABYLON.Tools.LoadFile(url, function (data) {
  61866. resolve(data);
  61867. }, undefined, undefined, true, function (request, exception) {
  61868. reject(exception);
  61869. });
  61870. });
  61871. };
  61872. /**
  61873. * The configuration.
  61874. */
  61875. DracoCompression.Configuration = {
  61876. decoder: {
  61877. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  61878. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  61879. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61880. }
  61881. };
  61882. return DracoCompression;
  61883. }());
  61884. BABYLON.DracoCompression = DracoCompression;
  61885. })(BABYLON || (BABYLON = {}));
  61886. //# sourceMappingURL=babylon.dracoCompression.js.map
  61887. var BABYLON;
  61888. (function (BABYLON) {
  61889. var AudioEngine = /** @class */ (function () {
  61890. function AudioEngine() {
  61891. this._audioContext = null;
  61892. this._audioContextInitialized = false;
  61893. this.canUseWebAudio = false;
  61894. this.WarnedWebAudioUnsupported = false;
  61895. this.unlocked = false;
  61896. this.isMP3supported = false;
  61897. this.isOGGsupported = false;
  61898. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  61899. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  61900. this.canUseWebAudio = true;
  61901. }
  61902. var audioElem = document.createElement('audio');
  61903. try {
  61904. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  61905. this.isMP3supported = true;
  61906. }
  61907. }
  61908. catch (e) {
  61909. // protect error during capability check.
  61910. }
  61911. try {
  61912. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  61913. this.isOGGsupported = true;
  61914. }
  61915. }
  61916. catch (e) {
  61917. // protect error during capability check.
  61918. }
  61919. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  61920. this._unlockiOSaudio();
  61921. }
  61922. else {
  61923. this.unlocked = true;
  61924. }
  61925. }
  61926. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  61927. get: function () {
  61928. if (!this._audioContextInitialized) {
  61929. this._initializeAudioContext();
  61930. }
  61931. return this._audioContext;
  61932. },
  61933. enumerable: true,
  61934. configurable: true
  61935. });
  61936. AudioEngine.prototype._unlockiOSaudio = function () {
  61937. var _this = this;
  61938. var unlockaudio = function () {
  61939. if (!_this.audioContext) {
  61940. return;
  61941. }
  61942. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  61943. var source = _this.audioContext.createBufferSource();
  61944. source.buffer = buffer;
  61945. source.connect(_this.audioContext.destination);
  61946. source.start(0);
  61947. setTimeout(function () {
  61948. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  61949. _this.unlocked = true;
  61950. window.removeEventListener('touchend', unlockaudio, false);
  61951. if (_this.onAudioUnlocked) {
  61952. _this.onAudioUnlocked();
  61953. }
  61954. }
  61955. }, 0);
  61956. };
  61957. window.addEventListener('touchend', unlockaudio, false);
  61958. };
  61959. AudioEngine.prototype._initializeAudioContext = function () {
  61960. try {
  61961. if (this.canUseWebAudio) {
  61962. this._audioContext = new AudioContext();
  61963. // create a global volume gain node
  61964. this.masterGain = this._audioContext.createGain();
  61965. this.masterGain.gain.value = 1;
  61966. this.masterGain.connect(this._audioContext.destination);
  61967. this._audioContextInitialized = true;
  61968. }
  61969. }
  61970. catch (e) {
  61971. this.canUseWebAudio = false;
  61972. BABYLON.Tools.Error("Web Audio: " + e.message);
  61973. }
  61974. };
  61975. AudioEngine.prototype.dispose = function () {
  61976. if (this.canUseWebAudio && this._audioContextInitialized) {
  61977. if (this._connectedAnalyser && this._audioContext) {
  61978. this._connectedAnalyser.stopDebugCanvas();
  61979. this._connectedAnalyser.dispose();
  61980. this.masterGain.disconnect();
  61981. this.masterGain.connect(this._audioContext.destination);
  61982. this._connectedAnalyser = null;
  61983. }
  61984. this.masterGain.gain.value = 1;
  61985. }
  61986. this.WarnedWebAudioUnsupported = false;
  61987. };
  61988. AudioEngine.prototype.getGlobalVolume = function () {
  61989. if (this.canUseWebAudio && this._audioContextInitialized) {
  61990. return this.masterGain.gain.value;
  61991. }
  61992. else {
  61993. return -1;
  61994. }
  61995. };
  61996. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  61997. if (this.canUseWebAudio && this._audioContextInitialized) {
  61998. this.masterGain.gain.value = newVolume;
  61999. }
  62000. };
  62001. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62002. if (this._connectedAnalyser) {
  62003. this._connectedAnalyser.stopDebugCanvas();
  62004. }
  62005. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62006. this._connectedAnalyser = analyser;
  62007. this.masterGain.disconnect();
  62008. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62009. }
  62010. };
  62011. return AudioEngine;
  62012. }());
  62013. BABYLON.AudioEngine = AudioEngine;
  62014. })(BABYLON || (BABYLON = {}));
  62015. //# sourceMappingURL=babylon.audioEngine.js.map
  62016. var BABYLON;
  62017. (function (BABYLON) {
  62018. var Sound = /** @class */ (function () {
  62019. /**
  62020. * Create a sound and attach it to a scene
  62021. * @param name Name of your sound
  62022. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  62023. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62024. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62025. */
  62026. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62027. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62028. var _this = this;
  62029. this.autoplay = false;
  62030. this.loop = false;
  62031. this.useCustomAttenuation = false;
  62032. this.spatialSound = false;
  62033. this.refDistance = 1;
  62034. this.rolloffFactor = 1;
  62035. this.maxDistance = 100;
  62036. this.distanceModel = "linear";
  62037. this._panningModel = "equalpower";
  62038. this._playbackRate = 1;
  62039. this._streaming = false;
  62040. this._startTime = 0;
  62041. this._startOffset = 0;
  62042. this._position = BABYLON.Vector3.Zero();
  62043. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62044. this._volume = 1;
  62045. this._isReadyToPlay = false;
  62046. this.isPlaying = false;
  62047. this.isPaused = false;
  62048. this._isDirectional = false;
  62049. // Used if you'd like to create a directional sound.
  62050. // If not set, the sound will be omnidirectional
  62051. this._coneInnerAngle = 360;
  62052. this._coneOuterAngle = 360;
  62053. this._coneOuterGain = 0;
  62054. this._isOutputConnected = false;
  62055. this._urlType = "Unknown";
  62056. this.name = name;
  62057. this._scene = scene;
  62058. this._readyToPlayCallback = readyToPlayCallback;
  62059. // Default custom attenuation function is a linear attenuation
  62060. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62061. if (currentDistance < maxDistance) {
  62062. return currentVolume * (1 - currentDistance / maxDistance);
  62063. }
  62064. else {
  62065. return 0;
  62066. }
  62067. };
  62068. if (options) {
  62069. this.autoplay = options.autoplay || false;
  62070. this.loop = options.loop || false;
  62071. // if volume === 0, we need another way to check this option
  62072. if (options.volume !== undefined) {
  62073. this._volume = options.volume;
  62074. }
  62075. this.spatialSound = options.spatialSound || false;
  62076. this.maxDistance = options.maxDistance || 100;
  62077. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62078. this.rolloffFactor = options.rolloffFactor || 1;
  62079. this.refDistance = options.refDistance || 1;
  62080. this.distanceModel = options.distanceModel || "linear";
  62081. this._playbackRate = options.playbackRate || 1;
  62082. this._streaming = options.streaming || false;
  62083. }
  62084. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62085. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62086. this._soundGain.gain.value = this._volume;
  62087. this._inputAudioNode = this._soundGain;
  62088. this._ouputAudioNode = this._soundGain;
  62089. if (this.spatialSound) {
  62090. this._createSpatialParameters();
  62091. }
  62092. this._scene.mainSoundTrack.AddSound(this);
  62093. var validParameter = true;
  62094. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62095. if (urlOrArrayBuffer) {
  62096. try {
  62097. if (typeof (urlOrArrayBuffer) === "string")
  62098. this._urlType = "String";
  62099. if (Array.isArray(urlOrArrayBuffer))
  62100. this._urlType = "Array";
  62101. if (urlOrArrayBuffer instanceof ArrayBuffer)
  62102. this._urlType = "ArrayBuffer";
  62103. var urls = [];
  62104. var codecSupportedFound = false;
  62105. switch (this._urlType) {
  62106. case "ArrayBuffer":
  62107. if (urlOrArrayBuffer.byteLength > 0) {
  62108. codecSupportedFound = true;
  62109. this._soundLoaded(urlOrArrayBuffer);
  62110. }
  62111. break;
  62112. case "String":
  62113. urls.push(urlOrArrayBuffer);
  62114. case "Array":
  62115. if (urls.length === 0)
  62116. urls = urlOrArrayBuffer;
  62117. // If we found a supported format, we load it immediately and stop the loop
  62118. for (var i = 0; i < urls.length; i++) {
  62119. var url = urls[i];
  62120. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62121. codecSupportedFound = true;
  62122. }
  62123. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62124. codecSupportedFound = true;
  62125. }
  62126. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62127. codecSupportedFound = true;
  62128. }
  62129. if (url.indexOf("blob:") !== -1) {
  62130. codecSupportedFound = true;
  62131. }
  62132. if (codecSupportedFound) {
  62133. // Loading sound using XHR2
  62134. if (!this._streaming) {
  62135. this._scene._loadFile(url, function (data) {
  62136. _this._soundLoaded(data);
  62137. }, undefined, true, true, function (exception) {
  62138. if (exception) {
  62139. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62140. }
  62141. BABYLON.Tools.Error("Sound creation aborted.");
  62142. _this._scene.mainSoundTrack.RemoveSound(_this);
  62143. });
  62144. }
  62145. // Streaming sound using HTML5 Audio tag
  62146. else {
  62147. this._htmlAudioElement = new Audio(url);
  62148. this._htmlAudioElement.controls = false;
  62149. this._htmlAudioElement.loop = this.loop;
  62150. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62151. this._htmlAudioElement.preload = "auto";
  62152. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62153. _this._isReadyToPlay = true;
  62154. if (_this.autoplay) {
  62155. _this.play();
  62156. }
  62157. if (_this._readyToPlayCallback) {
  62158. _this._readyToPlayCallback();
  62159. }
  62160. });
  62161. document.body.appendChild(this._htmlAudioElement);
  62162. }
  62163. break;
  62164. }
  62165. }
  62166. break;
  62167. default:
  62168. validParameter = false;
  62169. break;
  62170. }
  62171. if (!validParameter) {
  62172. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62173. }
  62174. else {
  62175. if (!codecSupportedFound) {
  62176. this._isReadyToPlay = true;
  62177. // Simulating a ready to play event to avoid breaking code path
  62178. if (this._readyToPlayCallback) {
  62179. window.setTimeout(function () {
  62180. if (_this._readyToPlayCallback) {
  62181. _this._readyToPlayCallback();
  62182. }
  62183. }, 1000);
  62184. }
  62185. }
  62186. }
  62187. }
  62188. catch (ex) {
  62189. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62190. this._scene.mainSoundTrack.RemoveSound(this);
  62191. }
  62192. }
  62193. }
  62194. else {
  62195. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62196. this._scene.mainSoundTrack.AddSound(this);
  62197. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62198. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62199. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62200. }
  62201. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62202. if (this._readyToPlayCallback) {
  62203. window.setTimeout(function () {
  62204. if (_this._readyToPlayCallback) {
  62205. _this._readyToPlayCallback();
  62206. }
  62207. }, 1000);
  62208. }
  62209. }
  62210. }
  62211. Sound.prototype.dispose = function () {
  62212. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62213. if (this.isPlaying) {
  62214. this.stop();
  62215. }
  62216. this._isReadyToPlay = false;
  62217. if (this.soundTrackId === -1) {
  62218. this._scene.mainSoundTrack.RemoveSound(this);
  62219. }
  62220. else {
  62221. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62222. }
  62223. if (this._soundGain) {
  62224. this._soundGain.disconnect();
  62225. this._soundGain = null;
  62226. }
  62227. if (this._soundPanner) {
  62228. this._soundPanner.disconnect();
  62229. this._soundPanner = null;
  62230. }
  62231. if (this._soundSource) {
  62232. this._soundSource.disconnect();
  62233. this._soundSource = null;
  62234. }
  62235. this._audioBuffer = null;
  62236. if (this._htmlAudioElement) {
  62237. this._htmlAudioElement.pause();
  62238. this._htmlAudioElement.src = "";
  62239. document.body.removeChild(this._htmlAudioElement);
  62240. }
  62241. if (this._connectedMesh && this._registerFunc) {
  62242. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62243. this._connectedMesh = null;
  62244. }
  62245. }
  62246. };
  62247. Sound.prototype.isReady = function () {
  62248. return this._isReadyToPlay;
  62249. };
  62250. Sound.prototype._soundLoaded = function (audioData) {
  62251. var _this = this;
  62252. if (!BABYLON.Engine.audioEngine.audioContext) {
  62253. return;
  62254. }
  62255. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62256. _this._audioBuffer = buffer;
  62257. _this._isReadyToPlay = true;
  62258. if (_this.autoplay) {
  62259. _this.play();
  62260. }
  62261. if (_this._readyToPlayCallback) {
  62262. _this._readyToPlayCallback();
  62263. }
  62264. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62265. };
  62266. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62267. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62268. this._audioBuffer = audioBuffer;
  62269. this._isReadyToPlay = true;
  62270. }
  62271. };
  62272. Sound.prototype.updateOptions = function (options) {
  62273. if (options) {
  62274. this.loop = options.loop || this.loop;
  62275. this.maxDistance = options.maxDistance || this.maxDistance;
  62276. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62277. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62278. this.refDistance = options.refDistance || this.refDistance;
  62279. this.distanceModel = options.distanceModel || this.distanceModel;
  62280. this._playbackRate = options.playbackRate || this._playbackRate;
  62281. this._updateSpatialParameters();
  62282. if (this.isPlaying) {
  62283. if (this._streaming) {
  62284. this._htmlAudioElement.playbackRate = this._playbackRate;
  62285. }
  62286. else {
  62287. if (this._soundSource) {
  62288. this._soundSource.playbackRate.value = this._playbackRate;
  62289. }
  62290. }
  62291. }
  62292. }
  62293. };
  62294. Sound.prototype._createSpatialParameters = function () {
  62295. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62296. if (this._scene.headphone) {
  62297. this._panningModel = "HRTF";
  62298. }
  62299. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62300. this._updateSpatialParameters();
  62301. this._soundPanner.connect(this._ouputAudioNode);
  62302. this._inputAudioNode = this._soundPanner;
  62303. }
  62304. };
  62305. Sound.prototype._updateSpatialParameters = function () {
  62306. if (this.spatialSound && this._soundPanner) {
  62307. if (this.useCustomAttenuation) {
  62308. // Tricks to disable in a way embedded Web Audio attenuation
  62309. this._soundPanner.distanceModel = "linear";
  62310. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62311. this._soundPanner.refDistance = 1;
  62312. this._soundPanner.rolloffFactor = 1;
  62313. this._soundPanner.panningModel = this._panningModel;
  62314. }
  62315. else {
  62316. this._soundPanner.distanceModel = this.distanceModel;
  62317. this._soundPanner.maxDistance = this.maxDistance;
  62318. this._soundPanner.refDistance = this.refDistance;
  62319. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62320. this._soundPanner.panningModel = this._panningModel;
  62321. }
  62322. }
  62323. };
  62324. Sound.prototype.switchPanningModelToHRTF = function () {
  62325. this._panningModel = "HRTF";
  62326. this._switchPanningModel();
  62327. };
  62328. Sound.prototype.switchPanningModelToEqualPower = function () {
  62329. this._panningModel = "equalpower";
  62330. this._switchPanningModel();
  62331. };
  62332. Sound.prototype._switchPanningModel = function () {
  62333. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62334. this._soundPanner.panningModel = this._panningModel;
  62335. }
  62336. };
  62337. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62338. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62339. if (this._isOutputConnected) {
  62340. this._ouputAudioNode.disconnect();
  62341. }
  62342. this._ouputAudioNode.connect(soundTrackAudioNode);
  62343. this._isOutputConnected = true;
  62344. }
  62345. };
  62346. /**
  62347. * Transform this sound into a directional source
  62348. * @param coneInnerAngle Size of the inner cone in degree
  62349. * @param coneOuterAngle Size of the outer cone in degree
  62350. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62351. */
  62352. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62353. if (coneOuterAngle < coneInnerAngle) {
  62354. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62355. return;
  62356. }
  62357. this._coneInnerAngle = coneInnerAngle;
  62358. this._coneOuterAngle = coneOuterAngle;
  62359. this._coneOuterGain = coneOuterGain;
  62360. this._isDirectional = true;
  62361. if (this.isPlaying && this.loop) {
  62362. this.stop();
  62363. this.play();
  62364. }
  62365. };
  62366. Sound.prototype.setPosition = function (newPosition) {
  62367. this._position = newPosition;
  62368. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62369. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62370. }
  62371. };
  62372. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62373. this._localDirection = newLocalDirection;
  62374. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62375. this._updateDirection();
  62376. }
  62377. };
  62378. Sound.prototype._updateDirection = function () {
  62379. if (!this._connectedMesh || !this._soundPanner) {
  62380. return;
  62381. }
  62382. var mat = this._connectedMesh.getWorldMatrix();
  62383. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62384. direction.normalize();
  62385. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62386. };
  62387. Sound.prototype.updateDistanceFromListener = function () {
  62388. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62389. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62390. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62391. }
  62392. };
  62393. Sound.prototype.setAttenuationFunction = function (callback) {
  62394. this._customAttenuationFunction = callback;
  62395. };
  62396. /**
  62397. * Play the sound
  62398. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62399. * @param offset (optional) Start the sound setting it at a specific time
  62400. */
  62401. Sound.prototype.play = function (time, offset) {
  62402. var _this = this;
  62403. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62404. try {
  62405. if (this._startOffset < 0) {
  62406. time = -this._startOffset;
  62407. this._startOffset = 0;
  62408. }
  62409. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62410. if (!this._soundSource || !this._streamingSource) {
  62411. if (this.spatialSound && this._soundPanner) {
  62412. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62413. if (this._isDirectional) {
  62414. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62415. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62416. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62417. if (this._connectedMesh) {
  62418. this._updateDirection();
  62419. }
  62420. else {
  62421. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62422. }
  62423. }
  62424. }
  62425. }
  62426. if (this._streaming) {
  62427. if (!this._streamingSource) {
  62428. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62429. this._htmlAudioElement.onended = function () { _this._onended(); };
  62430. this._htmlAudioElement.playbackRate = this._playbackRate;
  62431. }
  62432. this._streamingSource.disconnect();
  62433. this._streamingSource.connect(this._inputAudioNode);
  62434. this._htmlAudioElement.play();
  62435. }
  62436. else {
  62437. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62438. this._soundSource.buffer = this._audioBuffer;
  62439. this._soundSource.connect(this._inputAudioNode);
  62440. this._soundSource.loop = this.loop;
  62441. this._soundSource.playbackRate.value = this._playbackRate;
  62442. this._soundSource.onended = function () { _this._onended(); };
  62443. if (this._soundSource.buffer) {
  62444. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62445. }
  62446. }
  62447. this._startTime = startTime;
  62448. this.isPlaying = true;
  62449. this.isPaused = false;
  62450. }
  62451. catch (ex) {
  62452. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62453. }
  62454. }
  62455. };
  62456. Sound.prototype._onended = function () {
  62457. this.isPlaying = false;
  62458. if (this.onended) {
  62459. this.onended();
  62460. }
  62461. };
  62462. /**
  62463. * Stop the sound
  62464. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62465. */
  62466. Sound.prototype.stop = function (time) {
  62467. if (this.isPlaying) {
  62468. if (this._streaming) {
  62469. this._htmlAudioElement.pause();
  62470. // Test needed for Firefox or it will generate an Invalid State Error
  62471. if (this._htmlAudioElement.currentTime > 0) {
  62472. this._htmlAudioElement.currentTime = 0;
  62473. }
  62474. }
  62475. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62476. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62477. this._soundSource.stop(stopTime);
  62478. this._soundSource.onended = function () { };
  62479. if (!this.isPaused) {
  62480. this._startOffset = 0;
  62481. }
  62482. }
  62483. this.isPlaying = false;
  62484. }
  62485. };
  62486. Sound.prototype.pause = function () {
  62487. if (this.isPlaying) {
  62488. this.isPaused = true;
  62489. if (this._streaming) {
  62490. this._htmlAudioElement.pause();
  62491. }
  62492. else if (BABYLON.Engine.audioEngine.audioContext) {
  62493. this.stop(0);
  62494. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62495. }
  62496. }
  62497. };
  62498. Sound.prototype.setVolume = function (newVolume, time) {
  62499. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62500. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62501. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62502. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62503. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62504. }
  62505. else {
  62506. this._soundGain.gain.value = newVolume;
  62507. }
  62508. }
  62509. this._volume = newVolume;
  62510. };
  62511. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62512. this._playbackRate = newPlaybackRate;
  62513. if (this.isPlaying) {
  62514. if (this._streaming) {
  62515. this._htmlAudioElement.playbackRate = this._playbackRate;
  62516. }
  62517. else if (this._soundSource) {
  62518. this._soundSource.playbackRate.value = this._playbackRate;
  62519. }
  62520. }
  62521. };
  62522. Sound.prototype.getVolume = function () {
  62523. return this._volume;
  62524. };
  62525. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62526. var _this = this;
  62527. if (this._connectedMesh && this._registerFunc) {
  62528. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62529. this._registerFunc = null;
  62530. }
  62531. this._connectedMesh = meshToConnectTo;
  62532. if (!this.spatialSound) {
  62533. this.spatialSound = true;
  62534. this._createSpatialParameters();
  62535. if (this.isPlaying && this.loop) {
  62536. this.stop();
  62537. this.play();
  62538. }
  62539. }
  62540. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62541. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62542. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62543. };
  62544. Sound.prototype.detachFromMesh = function () {
  62545. if (this._connectedMesh && this._registerFunc) {
  62546. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62547. this._registerFunc = null;
  62548. this._connectedMesh = null;
  62549. }
  62550. };
  62551. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62552. if (!node.getBoundingInfo) {
  62553. return;
  62554. }
  62555. var mesh = node;
  62556. var boundingInfo = mesh.getBoundingInfo();
  62557. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62558. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62559. this._updateDirection();
  62560. }
  62561. };
  62562. Sound.prototype.clone = function () {
  62563. var _this = this;
  62564. if (!this._streaming) {
  62565. var setBufferAndRun = function () {
  62566. if (_this._isReadyToPlay) {
  62567. clonedSound._audioBuffer = _this.getAudioBuffer();
  62568. clonedSound._isReadyToPlay = true;
  62569. if (clonedSound.autoplay) {
  62570. clonedSound.play();
  62571. }
  62572. }
  62573. else {
  62574. window.setTimeout(setBufferAndRun, 300);
  62575. }
  62576. };
  62577. var currentOptions = {
  62578. autoplay: this.autoplay, loop: this.loop,
  62579. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62580. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62581. refDistance: this.refDistance, distanceModel: this.distanceModel
  62582. };
  62583. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62584. if (this.useCustomAttenuation) {
  62585. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62586. }
  62587. clonedSound.setPosition(this._position);
  62588. clonedSound.setPlaybackRate(this._playbackRate);
  62589. setBufferAndRun();
  62590. return clonedSound;
  62591. }
  62592. // Can't clone a streaming sound
  62593. else {
  62594. return null;
  62595. }
  62596. };
  62597. Sound.prototype.getAudioBuffer = function () {
  62598. return this._audioBuffer;
  62599. };
  62600. Sound.prototype.serialize = function () {
  62601. var serializationObject = {
  62602. name: this.name,
  62603. url: this.name,
  62604. autoplay: this.autoplay,
  62605. loop: this.loop,
  62606. volume: this._volume,
  62607. spatialSound: this.spatialSound,
  62608. maxDistance: this.maxDistance,
  62609. rolloffFactor: this.rolloffFactor,
  62610. refDistance: this.refDistance,
  62611. distanceModel: this.distanceModel,
  62612. playbackRate: this._playbackRate,
  62613. panningModel: this._panningModel,
  62614. soundTrackId: this.soundTrackId
  62615. };
  62616. if (this.spatialSound) {
  62617. if (this._connectedMesh)
  62618. serializationObject.connectedMeshId = this._connectedMesh.id;
  62619. serializationObject.position = this._position.asArray();
  62620. serializationObject.refDistance = this.refDistance;
  62621. serializationObject.distanceModel = this.distanceModel;
  62622. serializationObject.isDirectional = this._isDirectional;
  62623. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62624. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62625. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62626. serializationObject.coneOuterGain = this._coneOuterGain;
  62627. }
  62628. return serializationObject;
  62629. };
  62630. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62631. var soundName = parsedSound.name;
  62632. var soundUrl;
  62633. if (parsedSound.url) {
  62634. soundUrl = rootUrl + parsedSound.url;
  62635. }
  62636. else {
  62637. soundUrl = rootUrl + soundName;
  62638. }
  62639. var options = {
  62640. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62641. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62642. rolloffFactor: parsedSound.rolloffFactor,
  62643. refDistance: parsedSound.refDistance,
  62644. distanceModel: parsedSound.distanceModel,
  62645. playbackRate: parsedSound.playbackRate
  62646. };
  62647. var newSound;
  62648. if (!sourceSound) {
  62649. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62650. scene._addPendingData(newSound);
  62651. }
  62652. else {
  62653. var setBufferAndRun = function () {
  62654. if (sourceSound._isReadyToPlay) {
  62655. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62656. newSound._isReadyToPlay = true;
  62657. if (newSound.autoplay) {
  62658. newSound.play();
  62659. }
  62660. }
  62661. else {
  62662. window.setTimeout(setBufferAndRun, 300);
  62663. }
  62664. };
  62665. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62666. setBufferAndRun();
  62667. }
  62668. if (parsedSound.position) {
  62669. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62670. newSound.setPosition(soundPosition);
  62671. }
  62672. if (parsedSound.isDirectional) {
  62673. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62674. if (parsedSound.localDirectionToMesh) {
  62675. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62676. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62677. }
  62678. }
  62679. if (parsedSound.connectedMeshId) {
  62680. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62681. if (connectedMesh) {
  62682. newSound.attachToMesh(connectedMesh);
  62683. }
  62684. }
  62685. return newSound;
  62686. };
  62687. return Sound;
  62688. }());
  62689. BABYLON.Sound = Sound;
  62690. })(BABYLON || (BABYLON = {}));
  62691. //# sourceMappingURL=babylon.sound.js.map
  62692. var BABYLON;
  62693. (function (BABYLON) {
  62694. var SoundTrack = /** @class */ (function () {
  62695. function SoundTrack(scene, options) {
  62696. this.id = -1;
  62697. this._isMainTrack = false;
  62698. this._isInitialized = false;
  62699. this._scene = scene;
  62700. this.soundCollection = new Array();
  62701. this._options = options;
  62702. if (!this._isMainTrack) {
  62703. this._scene.soundTracks.push(this);
  62704. this.id = this._scene.soundTracks.length - 1;
  62705. }
  62706. }
  62707. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62708. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62709. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62710. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62711. if (this._options) {
  62712. if (this._options.volume) {
  62713. this._outputAudioNode.gain.value = this._options.volume;
  62714. }
  62715. if (this._options.mainTrack) {
  62716. this._isMainTrack = this._options.mainTrack;
  62717. }
  62718. }
  62719. this._isInitialized = true;
  62720. }
  62721. };
  62722. SoundTrack.prototype.dispose = function () {
  62723. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62724. if (this._connectedAnalyser) {
  62725. this._connectedAnalyser.stopDebugCanvas();
  62726. }
  62727. while (this.soundCollection.length) {
  62728. this.soundCollection[0].dispose();
  62729. }
  62730. if (this._outputAudioNode) {
  62731. this._outputAudioNode.disconnect();
  62732. }
  62733. this._outputAudioNode = null;
  62734. }
  62735. };
  62736. SoundTrack.prototype.AddSound = function (sound) {
  62737. if (!this._isInitialized) {
  62738. this._initializeSoundTrackAudioGraph();
  62739. }
  62740. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62741. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62742. }
  62743. if (sound.soundTrackId) {
  62744. if (sound.soundTrackId === -1) {
  62745. this._scene.mainSoundTrack.RemoveSound(sound);
  62746. }
  62747. else {
  62748. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62749. }
  62750. }
  62751. this.soundCollection.push(sound);
  62752. sound.soundTrackId = this.id;
  62753. };
  62754. SoundTrack.prototype.RemoveSound = function (sound) {
  62755. var index = this.soundCollection.indexOf(sound);
  62756. if (index !== -1) {
  62757. this.soundCollection.splice(index, 1);
  62758. }
  62759. };
  62760. SoundTrack.prototype.setVolume = function (newVolume) {
  62761. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62762. this._outputAudioNode.gain.value = newVolume;
  62763. }
  62764. };
  62765. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62766. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62767. for (var i = 0; i < this.soundCollection.length; i++) {
  62768. this.soundCollection[i].switchPanningModelToHRTF();
  62769. }
  62770. }
  62771. };
  62772. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62773. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62774. for (var i = 0; i < this.soundCollection.length; i++) {
  62775. this.soundCollection[i].switchPanningModelToEqualPower();
  62776. }
  62777. }
  62778. };
  62779. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62780. if (this._connectedAnalyser) {
  62781. this._connectedAnalyser.stopDebugCanvas();
  62782. }
  62783. this._connectedAnalyser = analyser;
  62784. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62785. this._outputAudioNode.disconnect();
  62786. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62787. }
  62788. };
  62789. return SoundTrack;
  62790. }());
  62791. BABYLON.SoundTrack = SoundTrack;
  62792. })(BABYLON || (BABYLON = {}));
  62793. //# sourceMappingURL=babylon.soundtrack.js.map
  62794. var BABYLON;
  62795. (function (BABYLON) {
  62796. /**
  62797. * Class used to work with sound analyzer using fast fourier transform (FFT)
  62798. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  62799. */
  62800. var Analyser = /** @class */ (function () {
  62801. /**
  62802. * Creates a new analyser
  62803. * @param scene defines hosting scene
  62804. */
  62805. function Analyser(scene) {
  62806. /**
  62807. * Gets or sets the smoothing
  62808. * @ignorenaming
  62809. */
  62810. this.SMOOTHING = 0.75;
  62811. /**
  62812. * Gets or sets the FFT table size
  62813. * @ignorenaming
  62814. */
  62815. this.FFT_SIZE = 512;
  62816. /**
  62817. * Gets or sets the bar graph amplitude
  62818. * @ignorenaming
  62819. */
  62820. this.BARGRAPHAMPLITUDE = 256;
  62821. /**
  62822. * Gets or sets the position of the debug canvas
  62823. * @ignorenaming
  62824. */
  62825. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  62826. /**
  62827. * Gets or sets the debug canvas size
  62828. * @ignorenaming
  62829. */
  62830. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  62831. this._scene = scene;
  62832. this._audioEngine = BABYLON.Engine.audioEngine;
  62833. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  62834. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  62835. this._webAudioAnalyser.minDecibels = -140;
  62836. this._webAudioAnalyser.maxDecibels = 0;
  62837. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62838. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62839. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  62840. }
  62841. }
  62842. /**
  62843. * Get the number of data values you will have to play with for the visualization
  62844. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  62845. * @returns a number
  62846. */
  62847. Analyser.prototype.getFrequencyBinCount = function () {
  62848. if (this._audioEngine.canUseWebAudio) {
  62849. return this._webAudioAnalyser.frequencyBinCount;
  62850. }
  62851. else {
  62852. return 0;
  62853. }
  62854. };
  62855. /**
  62856. * Gets the current frequency data as a byte array
  62857. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62858. * @returns a Uint8Array
  62859. */
  62860. Analyser.prototype.getByteFrequencyData = function () {
  62861. if (this._audioEngine.canUseWebAudio) {
  62862. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62863. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62864. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  62865. }
  62866. return this._byteFreqs;
  62867. };
  62868. /**
  62869. * Gets the current waveform as a byte array
  62870. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  62871. * @returns a Uint8Array
  62872. */
  62873. Analyser.prototype.getByteTimeDomainData = function () {
  62874. if (this._audioEngine.canUseWebAudio) {
  62875. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62876. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62877. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  62878. }
  62879. return this._byteTime;
  62880. };
  62881. /**
  62882. * Gets the current frequency data as a float array
  62883. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62884. * @returns a Float32Array
  62885. */
  62886. Analyser.prototype.getFloatFrequencyData = function () {
  62887. if (this._audioEngine.canUseWebAudio) {
  62888. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62889. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62890. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  62891. }
  62892. return this._floatFreqs;
  62893. };
  62894. /**
  62895. * Renders the debug canvas
  62896. */
  62897. Analyser.prototype.drawDebugCanvas = function () {
  62898. var _this = this;
  62899. if (this._audioEngine.canUseWebAudio) {
  62900. if (!this._debugCanvas) {
  62901. this._debugCanvas = document.createElement("canvas");
  62902. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  62903. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  62904. this._debugCanvas.style.position = "absolute";
  62905. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  62906. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  62907. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  62908. document.body.appendChild(this._debugCanvas);
  62909. this._registerFunc = function () {
  62910. _this.drawDebugCanvas();
  62911. };
  62912. this._scene.registerBeforeRender(this._registerFunc);
  62913. }
  62914. if (this._registerFunc && this._debugCanvasContext) {
  62915. var workingArray = this.getByteFrequencyData();
  62916. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  62917. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  62918. // Draw the frequency domain chart.
  62919. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  62920. var value = workingArray[i];
  62921. var percent = value / this.BARGRAPHAMPLITUDE;
  62922. var height = this.DEBUGCANVASSIZE.height * percent;
  62923. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  62924. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  62925. var hue = i / this.getFrequencyBinCount() * 360;
  62926. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  62927. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  62928. }
  62929. }
  62930. }
  62931. };
  62932. /**
  62933. * Stops rendering the debug canvas and removes it
  62934. */
  62935. Analyser.prototype.stopDebugCanvas = function () {
  62936. if (this._debugCanvas) {
  62937. if (this._registerFunc) {
  62938. this._scene.unregisterBeforeRender(this._registerFunc);
  62939. this._registerFunc = null;
  62940. }
  62941. document.body.removeChild(this._debugCanvas);
  62942. this._debugCanvas = null;
  62943. this._debugCanvasContext = null;
  62944. }
  62945. };
  62946. /**
  62947. * Connects two audio nodes
  62948. * @param inputAudioNode defines first node to connect
  62949. * @param outputAudioNode defines second node to connect
  62950. */
  62951. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  62952. if (this._audioEngine.canUseWebAudio) {
  62953. inputAudioNode.connect(this._webAudioAnalyser);
  62954. this._webAudioAnalyser.connect(outputAudioNode);
  62955. }
  62956. };
  62957. /**
  62958. * Releases all associated resources
  62959. */
  62960. Analyser.prototype.dispose = function () {
  62961. if (this._audioEngine.canUseWebAudio) {
  62962. this._webAudioAnalyser.disconnect();
  62963. }
  62964. };
  62965. return Analyser;
  62966. }());
  62967. BABYLON.Analyser = Analyser;
  62968. })(BABYLON || (BABYLON = {}));
  62969. //# sourceMappingURL=babylon.analyser.js.map
  62970. var BABYLON;
  62971. (function (BABYLON) {
  62972. var CubeTexture = /** @class */ (function (_super) {
  62973. __extends(CubeTexture, _super);
  62974. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  62975. if (extensions === void 0) { extensions = null; }
  62976. if (noMipmap === void 0) { noMipmap = false; }
  62977. if (files === void 0) { files = null; }
  62978. if (onLoad === void 0) { onLoad = null; }
  62979. if (onError === void 0) { onError = null; }
  62980. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  62981. if (prefiltered === void 0) { prefiltered = false; }
  62982. if (forcedExtension === void 0) { forcedExtension = null; }
  62983. var _this = _super.call(this, scene) || this;
  62984. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  62985. /**
  62986. * Gets or sets the center of the bounding box associated with the cube texture
  62987. * It must define where the camera used to render the texture was set
  62988. */
  62989. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62990. _this._rotationY = 0;
  62991. _this.name = rootUrl;
  62992. _this.url = rootUrl;
  62993. _this._noMipmap = noMipmap;
  62994. _this.hasAlpha = false;
  62995. _this._format = format;
  62996. _this._prefiltered = prefiltered;
  62997. _this.isCube = true;
  62998. _this._textureMatrix = BABYLON.Matrix.Identity();
  62999. if (prefiltered) {
  63000. _this.gammaSpace = false;
  63001. }
  63002. if (!rootUrl && !files) {
  63003. return _this;
  63004. }
  63005. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63006. var lastDot = rootUrl.lastIndexOf(".");
  63007. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63008. var isDDS = (extension === ".dds");
  63009. if (!files) {
  63010. if (!isDDS && !extensions) {
  63011. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63012. }
  63013. files = [];
  63014. if (extensions) {
  63015. for (var index = 0; index < extensions.length; index++) {
  63016. files.push(rootUrl + extensions[index]);
  63017. }
  63018. }
  63019. }
  63020. _this._files = files;
  63021. if (!_this._texture) {
  63022. if (!scene.useDelayedTextureLoading) {
  63023. if (prefiltered) {
  63024. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  63025. }
  63026. else {
  63027. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  63028. }
  63029. }
  63030. else {
  63031. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63032. }
  63033. }
  63034. else if (onLoad) {
  63035. if (_this._texture.isReady) {
  63036. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63037. }
  63038. else {
  63039. _this._texture.onLoadedObservable.add(onLoad);
  63040. }
  63041. }
  63042. return _this;
  63043. }
  63044. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63045. get: function () {
  63046. return this._boundingBoxSize;
  63047. },
  63048. /**
  63049. * Gets or sets the size of the bounding box associated with the cube texture
  63050. * When defined, the cubemap will switch to local mode
  63051. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63052. * @example https://www.babylonjs-playground.com/#RNASML
  63053. */
  63054. set: function (value) {
  63055. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63056. return;
  63057. }
  63058. this._boundingBoxSize = value;
  63059. var scene = this.getScene();
  63060. if (scene) {
  63061. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63062. }
  63063. },
  63064. enumerable: true,
  63065. configurable: true
  63066. });
  63067. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63068. /**
  63069. * Gets texture matrix rotation angle around Y axis radians.
  63070. */
  63071. get: function () {
  63072. return this._rotationY;
  63073. },
  63074. /**
  63075. * Sets texture matrix rotation angle around Y axis in radians.
  63076. */
  63077. set: function (value) {
  63078. this._rotationY = value;
  63079. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63080. },
  63081. enumerable: true,
  63082. configurable: true
  63083. });
  63084. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63085. var rootUrlKey = "";
  63086. files.forEach(function (url) { return rootUrlKey += url; });
  63087. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63088. };
  63089. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  63090. if (forcedExtension === void 0) { forcedExtension = null; }
  63091. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  63092. };
  63093. // Methods
  63094. CubeTexture.prototype.delayLoad = function () {
  63095. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63096. return;
  63097. }
  63098. var scene = this.getScene();
  63099. if (!scene) {
  63100. return;
  63101. }
  63102. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63103. this._texture = this._getFromCache(this.url, this._noMipmap);
  63104. if (!this._texture) {
  63105. if (this._prefiltered) {
  63106. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  63107. }
  63108. else {
  63109. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63110. }
  63111. }
  63112. };
  63113. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63114. return this._textureMatrix;
  63115. };
  63116. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63117. this._textureMatrix = value;
  63118. };
  63119. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63120. var texture = BABYLON.SerializationHelper.Parse(function () {
  63121. var prefiltered = false;
  63122. if (parsedTexture.prefiltered) {
  63123. prefiltered = parsedTexture.prefiltered;
  63124. }
  63125. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63126. }, parsedTexture, scene);
  63127. // Local Cubemaps
  63128. if (parsedTexture.boundingBoxPosition) {
  63129. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63130. }
  63131. if (parsedTexture.boundingBoxSize) {
  63132. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63133. }
  63134. // Animations
  63135. if (parsedTexture.animations) {
  63136. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63137. var parsedAnimation = parsedTexture.animations[animationIndex];
  63138. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63139. }
  63140. }
  63141. return texture;
  63142. };
  63143. CubeTexture.prototype.clone = function () {
  63144. var _this = this;
  63145. return BABYLON.SerializationHelper.Clone(function () {
  63146. var scene = _this.getScene();
  63147. if (!scene) {
  63148. return _this;
  63149. }
  63150. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63151. }, this);
  63152. };
  63153. __decorate([
  63154. BABYLON.serialize("rotationY")
  63155. ], CubeTexture.prototype, "_rotationY", void 0);
  63156. return CubeTexture;
  63157. }(BABYLON.BaseTexture));
  63158. BABYLON.CubeTexture = CubeTexture;
  63159. })(BABYLON || (BABYLON = {}));
  63160. //# sourceMappingURL=babylon.cubeTexture.js.map
  63161. var BABYLON;
  63162. (function (BABYLON) {
  63163. var RenderTargetTexture = /** @class */ (function (_super) {
  63164. __extends(RenderTargetTexture, _super);
  63165. /**
  63166. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63167. * or used a shadow, depth texture...
  63168. * @param name The friendly name of the texture
  63169. * @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)
  63170. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63171. * @param generateMipMaps True if mip maps need to be generated after render.
  63172. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63173. * @param type The type of the buffer in the RTT (int, half float, float...)
  63174. * @param isCube True if a cube texture needs to be created
  63175. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63176. * @param generateDepthBuffer True to generate a depth buffer
  63177. * @param generateStencilBuffer True to generate a stencil buffer
  63178. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63179. */
  63180. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63181. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63182. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63183. if (isCube === void 0) { isCube = false; }
  63184. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63185. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63186. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63187. if (isMulti === void 0) { isMulti = false; }
  63188. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63189. _this.isCube = isCube;
  63190. /**
  63191. * Use this list to define the list of mesh you want to render.
  63192. */
  63193. _this.renderList = new Array();
  63194. _this.renderParticles = true;
  63195. _this.renderSprites = false;
  63196. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63197. _this.ignoreCameraViewport = false;
  63198. // Events
  63199. /**
  63200. * An event triggered when the texture is unbind.
  63201. */
  63202. _this.onBeforeBindObservable = new BABYLON.Observable();
  63203. /**
  63204. * An event triggered when the texture is unbind.
  63205. */
  63206. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63207. /**
  63208. * An event triggered before rendering the texture
  63209. */
  63210. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63211. /**
  63212. * An event triggered after rendering the texture
  63213. */
  63214. _this.onAfterRenderObservable = new BABYLON.Observable();
  63215. /**
  63216. * An event triggered after the texture clear
  63217. */
  63218. _this.onClearObservable = new BABYLON.Observable();
  63219. _this._currentRefreshId = -1;
  63220. _this._refreshRate = 1;
  63221. _this._samples = 1;
  63222. /**
  63223. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63224. * It must define where the camera used to render the texture is set
  63225. */
  63226. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63227. scene = _this.getScene();
  63228. if (!scene) {
  63229. return _this;
  63230. }
  63231. _this._engine = scene.getEngine();
  63232. _this.name = name;
  63233. _this.isRenderTarget = true;
  63234. _this._initialSizeParameter = size;
  63235. _this._processSizeParameter(size);
  63236. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63237. });
  63238. _this._generateMipMaps = generateMipMaps ? true : false;
  63239. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63240. // Rendering groups
  63241. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63242. if (isMulti) {
  63243. return _this;
  63244. }
  63245. _this._renderTargetOptions = {
  63246. generateMipMaps: generateMipMaps,
  63247. type: type,
  63248. samplingMode: samplingMode,
  63249. generateDepthBuffer: generateDepthBuffer,
  63250. generateStencilBuffer: generateStencilBuffer
  63251. };
  63252. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63253. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63254. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63255. }
  63256. if (isCube) {
  63257. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63258. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63259. _this._textureMatrix = BABYLON.Matrix.Identity();
  63260. }
  63261. else {
  63262. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63263. }
  63264. return _this;
  63265. }
  63266. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63267. get: function () {
  63268. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63269. },
  63270. enumerable: true,
  63271. configurable: true
  63272. });
  63273. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63274. get: function () {
  63275. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63276. },
  63277. enumerable: true,
  63278. configurable: true
  63279. });
  63280. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63281. get: function () {
  63282. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63283. },
  63284. enumerable: true,
  63285. configurable: true
  63286. });
  63287. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63288. set: function (callback) {
  63289. if (this._onAfterUnbindObserver) {
  63290. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63291. }
  63292. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63293. },
  63294. enumerable: true,
  63295. configurable: true
  63296. });
  63297. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63298. set: function (callback) {
  63299. if (this._onBeforeRenderObserver) {
  63300. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63301. }
  63302. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63303. },
  63304. enumerable: true,
  63305. configurable: true
  63306. });
  63307. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63308. set: function (callback) {
  63309. if (this._onAfterRenderObserver) {
  63310. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63311. }
  63312. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63313. },
  63314. enumerable: true,
  63315. configurable: true
  63316. });
  63317. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63318. set: function (callback) {
  63319. if (this._onClearObserver) {
  63320. this.onClearObservable.remove(this._onClearObserver);
  63321. }
  63322. this._onClearObserver = this.onClearObservable.add(callback);
  63323. },
  63324. enumerable: true,
  63325. configurable: true
  63326. });
  63327. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63328. get: function () {
  63329. return this._renderTargetOptions;
  63330. },
  63331. enumerable: true,
  63332. configurable: true
  63333. });
  63334. RenderTargetTexture.prototype._onRatioRescale = function () {
  63335. if (this._sizeRatio) {
  63336. this.resize(this._initialSizeParameter);
  63337. }
  63338. };
  63339. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63340. get: function () {
  63341. return this._boundingBoxSize;
  63342. },
  63343. /**
  63344. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63345. * When defined, the cubemap will switch to local mode
  63346. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63347. * @example https://www.babylonjs-playground.com/#RNASML
  63348. */
  63349. set: function (value) {
  63350. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63351. return;
  63352. }
  63353. this._boundingBoxSize = value;
  63354. var scene = this.getScene();
  63355. if (scene) {
  63356. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63357. }
  63358. },
  63359. enumerable: true,
  63360. configurable: true
  63361. });
  63362. /**
  63363. * Creates a depth stencil texture.
  63364. * This is only available in WebGL 2 or with the depth texture extension available.
  63365. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63366. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63367. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63368. */
  63369. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63370. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63371. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63372. if (generateStencil === void 0) { generateStencil = false; }
  63373. if (!this.getScene()) {
  63374. return;
  63375. }
  63376. var engine = this.getScene().getEngine();
  63377. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63378. bilinearFiltering: bilinearFiltering,
  63379. comparisonFunction: comparisonFunction,
  63380. generateStencil: generateStencil,
  63381. isCube: this.isCube
  63382. });
  63383. engine.setFrameBufferDepthStencilTexture(this);
  63384. };
  63385. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63386. if (size.ratio) {
  63387. this._sizeRatio = size.ratio;
  63388. this._size = {
  63389. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63390. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63391. };
  63392. }
  63393. else {
  63394. this._size = size;
  63395. }
  63396. };
  63397. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63398. get: function () {
  63399. return this._samples;
  63400. },
  63401. set: function (value) {
  63402. if (this._samples === value) {
  63403. return;
  63404. }
  63405. var scene = this.getScene();
  63406. if (!scene) {
  63407. return;
  63408. }
  63409. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63410. },
  63411. enumerable: true,
  63412. configurable: true
  63413. });
  63414. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63415. this._currentRefreshId = -1;
  63416. };
  63417. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63418. get: function () {
  63419. return this._refreshRate;
  63420. },
  63421. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63422. set: function (value) {
  63423. this._refreshRate = value;
  63424. this.resetRefreshCounter();
  63425. },
  63426. enumerable: true,
  63427. configurable: true
  63428. });
  63429. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63430. if (!this._postProcessManager) {
  63431. var scene = this.getScene();
  63432. if (!scene) {
  63433. return;
  63434. }
  63435. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63436. this._postProcesses = new Array();
  63437. }
  63438. this._postProcesses.push(postProcess);
  63439. this._postProcesses[0].autoClear = false;
  63440. };
  63441. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63442. if (!this._postProcesses) {
  63443. return;
  63444. }
  63445. if (dispose) {
  63446. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63447. var postProcess = _a[_i];
  63448. postProcess.dispose();
  63449. }
  63450. }
  63451. this._postProcesses = [];
  63452. };
  63453. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63454. if (!this._postProcesses) {
  63455. return;
  63456. }
  63457. var index = this._postProcesses.indexOf(postProcess);
  63458. if (index === -1) {
  63459. return;
  63460. }
  63461. this._postProcesses.splice(index, 1);
  63462. if (this._postProcesses.length > 0) {
  63463. this._postProcesses[0].autoClear = false;
  63464. }
  63465. };
  63466. RenderTargetTexture.prototype._shouldRender = function () {
  63467. if (this._currentRefreshId === -1) { // At least render once
  63468. this._currentRefreshId = 1;
  63469. return true;
  63470. }
  63471. if (this.refreshRate === this._currentRefreshId) {
  63472. this._currentRefreshId = 1;
  63473. return true;
  63474. }
  63475. this._currentRefreshId++;
  63476. return false;
  63477. };
  63478. RenderTargetTexture.prototype.getRenderSize = function () {
  63479. if (this._size.width) {
  63480. return this._size.width;
  63481. }
  63482. return this._size;
  63483. };
  63484. RenderTargetTexture.prototype.getRenderWidth = function () {
  63485. if (this._size.width) {
  63486. return this._size.width;
  63487. }
  63488. return this._size;
  63489. };
  63490. RenderTargetTexture.prototype.getRenderHeight = function () {
  63491. if (this._size.width) {
  63492. return this._size.height;
  63493. }
  63494. return this._size;
  63495. };
  63496. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63497. get: function () {
  63498. return true;
  63499. },
  63500. enumerable: true,
  63501. configurable: true
  63502. });
  63503. RenderTargetTexture.prototype.scale = function (ratio) {
  63504. var newSize = this.getRenderSize() * ratio;
  63505. this.resize(newSize);
  63506. };
  63507. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63508. if (this.isCube) {
  63509. return this._textureMatrix;
  63510. }
  63511. return _super.prototype.getReflectionTextureMatrix.call(this);
  63512. };
  63513. RenderTargetTexture.prototype.resize = function (size) {
  63514. this.releaseInternalTexture();
  63515. var scene = this.getScene();
  63516. if (!scene) {
  63517. return;
  63518. }
  63519. this._processSizeParameter(size);
  63520. if (this.isCube) {
  63521. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63522. }
  63523. else {
  63524. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63525. }
  63526. };
  63527. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63528. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63529. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63530. var scene = this.getScene();
  63531. if (!scene) {
  63532. return;
  63533. }
  63534. var engine = scene.getEngine();
  63535. if (this.useCameraPostProcesses !== undefined) {
  63536. useCameraPostProcess = this.useCameraPostProcesses;
  63537. }
  63538. if (this._waitingRenderList) {
  63539. this.renderList = [];
  63540. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63541. var id = this._waitingRenderList[index];
  63542. var mesh_1 = scene.getMeshByID(id);
  63543. if (mesh_1) {
  63544. this.renderList.push(mesh_1);
  63545. }
  63546. }
  63547. delete this._waitingRenderList;
  63548. }
  63549. // Is predicate defined?
  63550. if (this.renderListPredicate) {
  63551. if (this.renderList) {
  63552. this.renderList.splice(0); // Clear previous renderList
  63553. }
  63554. else {
  63555. this.renderList = [];
  63556. }
  63557. var scene = this.getScene();
  63558. if (!scene) {
  63559. return;
  63560. }
  63561. var sceneMeshes = scene.meshes;
  63562. for (var index = 0; index < sceneMeshes.length; index++) {
  63563. var mesh = sceneMeshes[index];
  63564. if (this.renderListPredicate(mesh)) {
  63565. this.renderList.push(mesh);
  63566. }
  63567. }
  63568. }
  63569. this.onBeforeBindObservable.notifyObservers(this);
  63570. // Set custom projection.
  63571. // Needs to be before binding to prevent changing the aspect ratio.
  63572. var camera;
  63573. if (this.activeCamera) {
  63574. camera = this.activeCamera;
  63575. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63576. if (this.activeCamera !== scene.activeCamera) {
  63577. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63578. }
  63579. }
  63580. else {
  63581. camera = scene.activeCamera;
  63582. if (camera) {
  63583. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63584. }
  63585. }
  63586. // Prepare renderingManager
  63587. this._renderingManager.reset();
  63588. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63589. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63590. var sceneRenderId = scene.getRenderId();
  63591. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63592. var mesh = currentRenderList[meshIndex];
  63593. if (mesh) {
  63594. if (!mesh.isReady(this.refreshRate === 0)) {
  63595. this.resetRefreshCounter();
  63596. continue;
  63597. }
  63598. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63599. var isMasked = void 0;
  63600. if (!this.renderList && camera) {
  63601. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63602. }
  63603. else {
  63604. isMasked = false;
  63605. }
  63606. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63607. mesh._activate(sceneRenderId);
  63608. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63609. var subMesh = mesh.subMeshes[subIndex];
  63610. scene._activeIndices.addCount(subMesh.indexCount, false);
  63611. this._renderingManager.dispatch(subMesh, mesh);
  63612. }
  63613. }
  63614. }
  63615. }
  63616. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63617. var particleSystem = scene.particleSystems[particleIndex];
  63618. var emitter = particleSystem.emitter;
  63619. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63620. continue;
  63621. }
  63622. if (currentRenderList.indexOf(emitter) >= 0) {
  63623. this._renderingManager.dispatchParticles(particleSystem);
  63624. }
  63625. }
  63626. if (this.isCube) {
  63627. for (var face = 0; face < 6; face++) {
  63628. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63629. scene.incrementRenderId();
  63630. scene.resetCachedMaterial();
  63631. }
  63632. }
  63633. else {
  63634. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63635. }
  63636. this.onAfterUnbindObservable.notifyObservers(this);
  63637. if (scene.activeCamera) {
  63638. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63639. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63640. }
  63641. engine.setViewport(scene.activeCamera.viewport);
  63642. }
  63643. scene.resetCachedMaterial();
  63644. };
  63645. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63646. var minimum = 128;
  63647. var x = renderDimension * scale;
  63648. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63649. // Ensure we don't exceed the render dimension (while staying POT)
  63650. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63651. };
  63652. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63653. var _this = this;
  63654. if (!this._texture) {
  63655. return;
  63656. }
  63657. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63658. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63659. });
  63660. };
  63661. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63662. var scene = this.getScene();
  63663. if (!scene) {
  63664. return;
  63665. }
  63666. var engine = scene.getEngine();
  63667. if (!this._texture) {
  63668. return;
  63669. }
  63670. // Bind
  63671. if (this._postProcessManager) {
  63672. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63673. }
  63674. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63675. if (this._texture) {
  63676. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63677. }
  63678. }
  63679. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63680. // Clear
  63681. if (this.onClearObservable.hasObservers()) {
  63682. this.onClearObservable.notifyObservers(engine);
  63683. }
  63684. else {
  63685. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63686. }
  63687. if (!this._doNotChangeAspectRatio) {
  63688. scene.updateTransformMatrix(true);
  63689. }
  63690. // Render
  63691. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63692. if (this._postProcessManager) {
  63693. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63694. }
  63695. else if (useCameraPostProcess) {
  63696. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63697. }
  63698. if (!this._doNotChangeAspectRatio) {
  63699. scene.updateTransformMatrix(true);
  63700. }
  63701. // Dump ?
  63702. if (dumpForDebug) {
  63703. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63704. }
  63705. // Unbind
  63706. if (!this.isCube || faceIndex === 5) {
  63707. if (this.isCube) {
  63708. if (faceIndex === 5) {
  63709. engine.generateMipMapsForCubemap(this._texture);
  63710. }
  63711. }
  63712. this.unbindFrameBuffer(engine, faceIndex);
  63713. }
  63714. else {
  63715. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63716. }
  63717. };
  63718. /**
  63719. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63720. * This allowed control for front to back rendering or reversly depending of the special needs.
  63721. *
  63722. * @param renderingGroupId The rendering group id corresponding to its index
  63723. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63724. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63725. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63726. */
  63727. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63728. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63729. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63730. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63731. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63732. };
  63733. /**
  63734. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63735. *
  63736. * @param renderingGroupId The rendering group id corresponding to its index
  63737. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63738. */
  63739. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63740. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63741. };
  63742. RenderTargetTexture.prototype.clone = function () {
  63743. var textureSize = this.getSize();
  63744. 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);
  63745. // Base texture
  63746. newTexture.hasAlpha = this.hasAlpha;
  63747. newTexture.level = this.level;
  63748. // RenderTarget Texture
  63749. newTexture.coordinatesMode = this.coordinatesMode;
  63750. if (this.renderList) {
  63751. newTexture.renderList = this.renderList.slice(0);
  63752. }
  63753. return newTexture;
  63754. };
  63755. RenderTargetTexture.prototype.serialize = function () {
  63756. if (!this.name) {
  63757. return null;
  63758. }
  63759. var serializationObject = _super.prototype.serialize.call(this);
  63760. serializationObject.renderTargetSize = this.getRenderSize();
  63761. serializationObject.renderList = [];
  63762. if (this.renderList) {
  63763. for (var index = 0; index < this.renderList.length; index++) {
  63764. serializationObject.renderList.push(this.renderList[index].id);
  63765. }
  63766. }
  63767. return serializationObject;
  63768. };
  63769. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63770. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63771. var objBuffer = this.getInternalTexture();
  63772. var scene = this.getScene();
  63773. if (objBuffer && scene) {
  63774. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63775. }
  63776. };
  63777. RenderTargetTexture.prototype.dispose = function () {
  63778. if (this._postProcessManager) {
  63779. this._postProcessManager.dispose();
  63780. this._postProcessManager = null;
  63781. }
  63782. this.clearPostProcesses(true);
  63783. if (this._resizeObserver) {
  63784. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  63785. this._resizeObserver = null;
  63786. }
  63787. this.renderList = null;
  63788. // Remove from custom render targets
  63789. var scene = this.getScene();
  63790. if (!scene) {
  63791. return;
  63792. }
  63793. var index = scene.customRenderTargets.indexOf(this);
  63794. if (index >= 0) {
  63795. scene.customRenderTargets.splice(index, 1);
  63796. }
  63797. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  63798. var camera = _a[_i];
  63799. index = camera.customRenderTargets.indexOf(this);
  63800. if (index >= 0) {
  63801. camera.customRenderTargets.splice(index, 1);
  63802. }
  63803. }
  63804. _super.prototype.dispose.call(this);
  63805. };
  63806. RenderTargetTexture.prototype._rebuild = function () {
  63807. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63808. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63809. }
  63810. if (this._postProcessManager) {
  63811. this._postProcessManager._rebuild();
  63812. }
  63813. };
  63814. /**
  63815. * Clear the info related to rendering groups preventing retention point in material dispose.
  63816. */
  63817. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  63818. if (this._renderingManager) {
  63819. this._renderingManager.freeRenderingGroups();
  63820. }
  63821. };
  63822. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  63823. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  63824. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  63825. return RenderTargetTexture;
  63826. }(BABYLON.Texture));
  63827. BABYLON.RenderTargetTexture = RenderTargetTexture;
  63828. })(BABYLON || (BABYLON = {}));
  63829. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  63830. var BABYLON;
  63831. (function (BABYLON) {
  63832. ;
  63833. var MultiRenderTarget = /** @class */ (function (_super) {
  63834. __extends(MultiRenderTarget, _super);
  63835. function MultiRenderTarget(name, size, count, scene, options) {
  63836. var _this = this;
  63837. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  63838. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  63839. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  63840. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  63841. _this._engine = scene.getEngine();
  63842. if (!_this.isSupported) {
  63843. _this.dispose();
  63844. return;
  63845. }
  63846. var types = [];
  63847. var samplingModes = [];
  63848. for (var i = 0; i < count; i++) {
  63849. if (options && options.types && options.types[i] !== undefined) {
  63850. types.push(options.types[i]);
  63851. }
  63852. else {
  63853. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63854. }
  63855. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  63856. samplingModes.push(options.samplingModes[i]);
  63857. }
  63858. else {
  63859. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63860. }
  63861. }
  63862. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  63863. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  63864. _this._size = size;
  63865. _this._multiRenderTargetOptions = {
  63866. samplingModes: samplingModes,
  63867. generateMipMaps: generateMipMaps,
  63868. generateDepthBuffer: generateDepthBuffer,
  63869. generateStencilBuffer: generateStencilBuffer,
  63870. generateDepthTexture: generateDepthTexture,
  63871. types: types,
  63872. textureCount: count
  63873. };
  63874. _this._createInternalTextures();
  63875. _this._createTextures();
  63876. return _this;
  63877. }
  63878. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  63879. get: function () {
  63880. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  63881. },
  63882. enumerable: true,
  63883. configurable: true
  63884. });
  63885. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  63886. get: function () {
  63887. return this._textures;
  63888. },
  63889. enumerable: true,
  63890. configurable: true
  63891. });
  63892. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  63893. get: function () {
  63894. return this._textures[this._textures.length - 1];
  63895. },
  63896. enumerable: true,
  63897. configurable: true
  63898. });
  63899. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  63900. set: function (wrap) {
  63901. if (this._textures) {
  63902. for (var i = 0; i < this._textures.length; i++) {
  63903. this._textures[i].wrapU = wrap;
  63904. }
  63905. }
  63906. },
  63907. enumerable: true,
  63908. configurable: true
  63909. });
  63910. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  63911. set: function (wrap) {
  63912. if (this._textures) {
  63913. for (var i = 0; i < this._textures.length; i++) {
  63914. this._textures[i].wrapV = wrap;
  63915. }
  63916. }
  63917. },
  63918. enumerable: true,
  63919. configurable: true
  63920. });
  63921. MultiRenderTarget.prototype._rebuild = function () {
  63922. this.releaseInternalTextures();
  63923. this._createInternalTextures();
  63924. for (var i = 0; i < this._internalTextures.length; i++) {
  63925. var texture = this._textures[i];
  63926. texture._texture = this._internalTextures[i];
  63927. }
  63928. // Keeps references to frame buffer and stencil/depth buffer
  63929. this._texture = this._internalTextures[0];
  63930. };
  63931. MultiRenderTarget.prototype._createInternalTextures = function () {
  63932. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  63933. };
  63934. MultiRenderTarget.prototype._createTextures = function () {
  63935. this._textures = [];
  63936. for (var i = 0; i < this._internalTextures.length; i++) {
  63937. var texture = new BABYLON.Texture(null, this.getScene());
  63938. texture._texture = this._internalTextures[i];
  63939. this._textures.push(texture);
  63940. }
  63941. // Keeps references to frame buffer and stencil/depth buffer
  63942. this._texture = this._internalTextures[0];
  63943. };
  63944. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  63945. get: function () {
  63946. return this._samples;
  63947. },
  63948. set: function (value) {
  63949. if (this._samples === value) {
  63950. return;
  63951. }
  63952. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  63953. },
  63954. enumerable: true,
  63955. configurable: true
  63956. });
  63957. MultiRenderTarget.prototype.resize = function (size) {
  63958. this.releaseInternalTextures();
  63959. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  63960. this._createInternalTextures();
  63961. };
  63962. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63963. var _this = this;
  63964. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  63965. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63966. });
  63967. };
  63968. MultiRenderTarget.prototype.dispose = function () {
  63969. this.releaseInternalTextures();
  63970. _super.prototype.dispose.call(this);
  63971. };
  63972. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  63973. if (!this._internalTextures) {
  63974. return;
  63975. }
  63976. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  63977. if (this._internalTextures[i] !== undefined) {
  63978. this._internalTextures[i].dispose();
  63979. this._internalTextures.splice(i, 1);
  63980. }
  63981. }
  63982. };
  63983. return MultiRenderTarget;
  63984. }(BABYLON.RenderTargetTexture));
  63985. BABYLON.MultiRenderTarget = MultiRenderTarget;
  63986. })(BABYLON || (BABYLON = {}));
  63987. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  63988. var BABYLON;
  63989. (function (BABYLON) {
  63990. var MirrorTexture = /** @class */ (function (_super) {
  63991. __extends(MirrorTexture, _super);
  63992. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  63993. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63994. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  63995. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63996. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  63997. _this.scene = scene;
  63998. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  63999. _this._transformMatrix = BABYLON.Matrix.Zero();
  64000. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64001. _this._adaptiveBlurKernel = 0;
  64002. _this._blurKernelX = 0;
  64003. _this._blurKernelY = 0;
  64004. _this._blurRatio = 1.0;
  64005. _this.ignoreCameraViewport = true;
  64006. _this._updateGammaSpace();
  64007. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64008. _this._updateGammaSpace;
  64009. });
  64010. _this.onBeforeRenderObservable.add(function () {
  64011. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64012. _this._savedViewMatrix = scene.getViewMatrix();
  64013. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64014. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64015. scene.clipPlane = _this.mirrorPlane;
  64016. scene.getEngine().cullBackFaces = false;
  64017. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64018. });
  64019. _this.onAfterRenderObservable.add(function () {
  64020. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64021. scene.getEngine().cullBackFaces = true;
  64022. scene._mirroredCameraPosition = null;
  64023. delete scene.clipPlane;
  64024. });
  64025. return _this;
  64026. }
  64027. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64028. get: function () {
  64029. return this._blurRatio;
  64030. },
  64031. set: function (value) {
  64032. if (this._blurRatio === value) {
  64033. return;
  64034. }
  64035. this._blurRatio = value;
  64036. this._preparePostProcesses();
  64037. },
  64038. enumerable: true,
  64039. configurable: true
  64040. });
  64041. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64042. set: function (value) {
  64043. this._adaptiveBlurKernel = value;
  64044. this._autoComputeBlurKernel();
  64045. },
  64046. enumerable: true,
  64047. configurable: true
  64048. });
  64049. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64050. set: function (value) {
  64051. this.blurKernelX = value;
  64052. this.blurKernelY = value;
  64053. },
  64054. enumerable: true,
  64055. configurable: true
  64056. });
  64057. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64058. get: function () {
  64059. return this._blurKernelX;
  64060. },
  64061. set: function (value) {
  64062. if (this._blurKernelX === value) {
  64063. return;
  64064. }
  64065. this._blurKernelX = value;
  64066. this._preparePostProcesses();
  64067. },
  64068. enumerable: true,
  64069. configurable: true
  64070. });
  64071. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64072. get: function () {
  64073. return this._blurKernelY;
  64074. },
  64075. set: function (value) {
  64076. if (this._blurKernelY === value) {
  64077. return;
  64078. }
  64079. this._blurKernelY = value;
  64080. this._preparePostProcesses();
  64081. },
  64082. enumerable: true,
  64083. configurable: true
  64084. });
  64085. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64086. var engine = this.getScene().getEngine();
  64087. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64088. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64089. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64090. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64091. };
  64092. MirrorTexture.prototype._onRatioRescale = function () {
  64093. if (this._sizeRatio) {
  64094. this.resize(this._initialSizeParameter);
  64095. if (!this._adaptiveBlurKernel) {
  64096. this._preparePostProcesses();
  64097. }
  64098. }
  64099. if (this._adaptiveBlurKernel) {
  64100. this._autoComputeBlurKernel();
  64101. }
  64102. };
  64103. MirrorTexture.prototype._updateGammaSpace = function () {
  64104. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64105. };
  64106. MirrorTexture.prototype._preparePostProcesses = function () {
  64107. this.clearPostProcesses(true);
  64108. if (this._blurKernelX && this._blurKernelY) {
  64109. var engine = this.getScene().getEngine();
  64110. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64111. 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);
  64112. this._blurX.autoClear = false;
  64113. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64114. this._blurX.inputTexture = this._texture;
  64115. }
  64116. else {
  64117. this._blurX.alwaysForcePOT = true;
  64118. }
  64119. 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);
  64120. this._blurY.autoClear = false;
  64121. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64122. this.addPostProcess(this._blurX);
  64123. this.addPostProcess(this._blurY);
  64124. }
  64125. else {
  64126. if (this._blurY) {
  64127. this.removePostProcess(this._blurY);
  64128. this._blurY.dispose();
  64129. this._blurY = null;
  64130. }
  64131. if (this._blurX) {
  64132. this.removePostProcess(this._blurX);
  64133. this._blurX.dispose();
  64134. this._blurX = null;
  64135. }
  64136. }
  64137. };
  64138. MirrorTexture.prototype.clone = function () {
  64139. var scene = this.getScene();
  64140. if (!scene) {
  64141. return this;
  64142. }
  64143. var textureSize = this.getSize();
  64144. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64145. // Base texture
  64146. newTexture.hasAlpha = this.hasAlpha;
  64147. newTexture.level = this.level;
  64148. // Mirror Texture
  64149. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64150. if (this.renderList) {
  64151. newTexture.renderList = this.renderList.slice(0);
  64152. }
  64153. return newTexture;
  64154. };
  64155. MirrorTexture.prototype.serialize = function () {
  64156. if (!this.name) {
  64157. return null;
  64158. }
  64159. var serializationObject = _super.prototype.serialize.call(this);
  64160. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64161. return serializationObject;
  64162. };
  64163. MirrorTexture.prototype.dispose = function () {
  64164. _super.prototype.dispose.call(this);
  64165. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64166. };
  64167. return MirrorTexture;
  64168. }(BABYLON.RenderTargetTexture));
  64169. BABYLON.MirrorTexture = MirrorTexture;
  64170. })(BABYLON || (BABYLON = {}));
  64171. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64172. var BABYLON;
  64173. (function (BABYLON) {
  64174. /**
  64175. * Creates a refraction texture used by refraction channel of the standard material.
  64176. * @param name the texture name
  64177. * @param size size of the underlying texture
  64178. * @param scene root scene
  64179. */
  64180. var RefractionTexture = /** @class */ (function (_super) {
  64181. __extends(RefractionTexture, _super);
  64182. function RefractionTexture(name, size, scene, generateMipMaps) {
  64183. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64184. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64185. _this.depth = 2.0;
  64186. _this.onBeforeRenderObservable.add(function () {
  64187. scene.clipPlane = _this.refractionPlane;
  64188. });
  64189. _this.onAfterRenderObservable.add(function () {
  64190. delete scene.clipPlane;
  64191. });
  64192. return _this;
  64193. }
  64194. RefractionTexture.prototype.clone = function () {
  64195. var scene = this.getScene();
  64196. if (!scene) {
  64197. return this;
  64198. }
  64199. var textureSize = this.getSize();
  64200. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64201. // Base texture
  64202. newTexture.hasAlpha = this.hasAlpha;
  64203. newTexture.level = this.level;
  64204. // Refraction Texture
  64205. newTexture.refractionPlane = this.refractionPlane.clone();
  64206. if (this.renderList) {
  64207. newTexture.renderList = this.renderList.slice(0);
  64208. }
  64209. newTexture.depth = this.depth;
  64210. return newTexture;
  64211. };
  64212. RefractionTexture.prototype.serialize = function () {
  64213. if (!this.name) {
  64214. return null;
  64215. }
  64216. var serializationObject = _super.prototype.serialize.call(this);
  64217. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64218. serializationObject.depth = this.depth;
  64219. return serializationObject;
  64220. };
  64221. return RefractionTexture;
  64222. }(BABYLON.RenderTargetTexture));
  64223. BABYLON.RefractionTexture = RefractionTexture;
  64224. })(BABYLON || (BABYLON = {}));
  64225. //# sourceMappingURL=babylon.refractionTexture.js.map
  64226. var BABYLON;
  64227. (function (BABYLON) {
  64228. /**
  64229. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64230. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64231. */
  64232. var DynamicTexture = /** @class */ (function (_super) {
  64233. __extends(DynamicTexture, _super);
  64234. /**
  64235. * Creates a {BABYLON.DynamicTexture}
  64236. * @param name defines the name of the texture
  64237. * @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
  64238. * @param scene defines the scene where you want the texture
  64239. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64240. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64241. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64242. */
  64243. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64244. if (scene === void 0) { scene = null; }
  64245. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64246. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64247. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64248. _this.name = name;
  64249. _this._engine = _this.getScene().getEngine();
  64250. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64251. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64252. _this._generateMipMaps = generateMipMaps;
  64253. if (options.getContext) {
  64254. _this._canvas = options;
  64255. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64256. }
  64257. else {
  64258. _this._canvas = document.createElement("canvas");
  64259. if (options.width || options.width === 0) {
  64260. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64261. }
  64262. else {
  64263. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64264. }
  64265. }
  64266. var textureSize = _this.getSize();
  64267. _this._canvas.width = textureSize.width;
  64268. _this._canvas.height = textureSize.height;
  64269. _this._context = _this._canvas.getContext("2d");
  64270. return _this;
  64271. }
  64272. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64273. /**
  64274. * Gets the current state of canRescale
  64275. */
  64276. get: function () {
  64277. return true;
  64278. },
  64279. enumerable: true,
  64280. configurable: true
  64281. });
  64282. DynamicTexture.prototype._recreate = function (textureSize) {
  64283. this._canvas.width = textureSize.width;
  64284. this._canvas.height = textureSize.height;
  64285. this.releaseInternalTexture();
  64286. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64287. };
  64288. /**
  64289. * Scales the texture
  64290. * @param ratio the scale factor to apply to both width and height
  64291. */
  64292. DynamicTexture.prototype.scale = function (ratio) {
  64293. var textureSize = this.getSize();
  64294. textureSize.width *= ratio;
  64295. textureSize.height *= ratio;
  64296. this._recreate(textureSize);
  64297. };
  64298. /**
  64299. * Resizes the texture
  64300. * @param width the new width
  64301. * @param height the new height
  64302. */
  64303. DynamicTexture.prototype.scaleTo = function (width, height) {
  64304. var textureSize = this.getSize();
  64305. textureSize.width = width;
  64306. textureSize.height = height;
  64307. this._recreate(textureSize);
  64308. };
  64309. /**
  64310. * Gets the context of the canvas used by the texture
  64311. * @returns the canvas context of the dynamic texture
  64312. */
  64313. DynamicTexture.prototype.getContext = function () {
  64314. return this._context;
  64315. };
  64316. /**
  64317. * Clears the texture
  64318. */
  64319. DynamicTexture.prototype.clear = function () {
  64320. var size = this.getSize();
  64321. this._context.fillRect(0, 0, size.width, size.height);
  64322. };
  64323. /**
  64324. * Updates the texture
  64325. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64326. */
  64327. DynamicTexture.prototype.update = function (invertY) {
  64328. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  64329. };
  64330. /**
  64331. * Draws text onto the texture
  64332. * @param text defines the text to be drawn
  64333. * @param x defines the placement of the text from the left
  64334. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64335. * @param font defines the font to be used with font-style, font-size, font-name
  64336. * @param color defines the color used for the text
  64337. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64338. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64339. * @param update defines whether texture is immediately update (default is true)
  64340. */
  64341. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64342. if (update === void 0) { update = true; }
  64343. var size = this.getSize();
  64344. if (clearColor) {
  64345. this._context.fillStyle = clearColor;
  64346. this._context.fillRect(0, 0, size.width, size.height);
  64347. }
  64348. this._context.font = font;
  64349. if (x === null || x === undefined) {
  64350. var textSize = this._context.measureText(text);
  64351. x = (size.width - textSize.width) / 2;
  64352. }
  64353. if (y === null || y === undefined) {
  64354. var fontSize = parseInt((font.replace(/\D/g, '')));
  64355. ;
  64356. y = (size.height / 2) + (fontSize / 3.65);
  64357. }
  64358. this._context.fillStyle = color;
  64359. this._context.fillText(text, x, y);
  64360. if (update) {
  64361. this.update(invertY);
  64362. }
  64363. };
  64364. /**
  64365. * Clones the texture
  64366. * @returns the clone of the texture.
  64367. */
  64368. DynamicTexture.prototype.clone = function () {
  64369. var scene = this.getScene();
  64370. if (!scene) {
  64371. return this;
  64372. }
  64373. var textureSize = this.getSize();
  64374. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64375. // Base texture
  64376. newTexture.hasAlpha = this.hasAlpha;
  64377. newTexture.level = this.level;
  64378. // Dynamic Texture
  64379. newTexture.wrapU = this.wrapU;
  64380. newTexture.wrapV = this.wrapV;
  64381. return newTexture;
  64382. };
  64383. /** @hidden */
  64384. DynamicTexture.prototype._rebuild = function () {
  64385. this.update();
  64386. };
  64387. return DynamicTexture;
  64388. }(BABYLON.Texture));
  64389. BABYLON.DynamicTexture = DynamicTexture;
  64390. })(BABYLON || (BABYLON = {}));
  64391. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64392. var BABYLON;
  64393. (function (BABYLON) {
  64394. var VideoTexture = /** @class */ (function (_super) {
  64395. __extends(VideoTexture, _super);
  64396. /**
  64397. * Creates a video texture.
  64398. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64399. * @param {string | null} name optional name, will detect from video source, if not defined
  64400. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64401. * @param {BABYLON.Scene} scene is obviously the current scene.
  64402. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64403. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64404. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64405. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64406. */
  64407. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64408. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64409. if (invertY === void 0) { invertY = false; }
  64410. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64411. if (settings === void 0) { settings = {
  64412. autoPlay: true,
  64413. loop: true,
  64414. autoUpdateTexture: true,
  64415. }; }
  64416. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64417. _this._stillImageCaptured = false;
  64418. _this._createInternalTexture = function () {
  64419. if (_this._texture != null) {
  64420. return;
  64421. }
  64422. if (!_this._engine.needPOTTextures ||
  64423. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64424. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64425. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64426. }
  64427. else {
  64428. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64429. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64430. _this._generateMipMaps = false;
  64431. }
  64432. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64433. if (!_this.video.autoplay) {
  64434. var oldHandler_1 = _this.video.onplaying;
  64435. _this.video.onplaying = function () {
  64436. _this.video.onplaying = oldHandler_1;
  64437. _this._texture.isReady = true;
  64438. _this._updateInternalTexture();
  64439. _this.video.pause();
  64440. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64441. _this.onLoadObservable.notifyObservers(_this);
  64442. }
  64443. };
  64444. _this.video.play();
  64445. }
  64446. else {
  64447. _this._texture.isReady = true;
  64448. _this._updateInternalTexture();
  64449. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64450. _this.onLoadObservable.notifyObservers(_this);
  64451. }
  64452. }
  64453. };
  64454. _this.reset = function () {
  64455. if (_this._texture == null) {
  64456. return;
  64457. }
  64458. _this._texture.dispose();
  64459. _this._texture = null;
  64460. };
  64461. _this._updateInternalTexture = function (e) {
  64462. if (_this._texture == null || !_this._texture.isReady) {
  64463. return;
  64464. }
  64465. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64466. return;
  64467. }
  64468. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64469. };
  64470. _this._engine = _this.getScene().getEngine();
  64471. _this._generateMipMaps = generateMipMaps;
  64472. _this._samplingMode = samplingMode;
  64473. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64474. _this.name = name || _this._getName(src);
  64475. _this.video = _this._getVideo(src);
  64476. if (settings.autoPlay !== undefined) {
  64477. _this.video.autoplay = settings.autoPlay;
  64478. }
  64479. if (settings.loop !== undefined) {
  64480. _this.video.loop = settings.loop;
  64481. }
  64482. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64483. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64484. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64485. _this.video.addEventListener("emptied", _this.reset);
  64486. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64487. _this._createInternalTexture();
  64488. }
  64489. return _this;
  64490. }
  64491. VideoTexture.prototype._getName = function (src) {
  64492. if (src instanceof HTMLVideoElement) {
  64493. return src.currentSrc;
  64494. }
  64495. if (typeof src === "object") {
  64496. return src.toString();
  64497. }
  64498. return src;
  64499. };
  64500. ;
  64501. VideoTexture.prototype._getVideo = function (src) {
  64502. if (src instanceof HTMLVideoElement) {
  64503. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64504. return src;
  64505. }
  64506. var video = document.createElement("video");
  64507. if (typeof src === "string") {
  64508. BABYLON.Tools.SetCorsBehavior(src, video);
  64509. video.src = src;
  64510. }
  64511. else {
  64512. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64513. src.forEach(function (url) {
  64514. var source = document.createElement("source");
  64515. source.src = url;
  64516. video.appendChild(source);
  64517. });
  64518. }
  64519. return video;
  64520. };
  64521. ;
  64522. /**
  64523. * Internal method to initiate `update`.
  64524. */
  64525. VideoTexture.prototype._rebuild = function () {
  64526. this.update();
  64527. };
  64528. /**
  64529. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  64530. */
  64531. VideoTexture.prototype.update = function () {
  64532. if (!this.autoUpdateTexture) {
  64533. // Expecting user to call `updateTexture` manually
  64534. return;
  64535. }
  64536. this.updateTexture(true);
  64537. };
  64538. /**
  64539. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64540. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64541. */
  64542. VideoTexture.prototype.updateTexture = function (isVisible) {
  64543. if (!isVisible) {
  64544. return;
  64545. }
  64546. if (this.video.paused && this._stillImageCaptured) {
  64547. return;
  64548. }
  64549. this._stillImageCaptured = true;
  64550. this._updateInternalTexture();
  64551. };
  64552. /**
  64553. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64554. * @param url New url.
  64555. */
  64556. VideoTexture.prototype.updateURL = function (url) {
  64557. this.video.src = url;
  64558. };
  64559. VideoTexture.prototype.dispose = function () {
  64560. _super.prototype.dispose.call(this);
  64561. this.video.removeEventListener("canplay", this._createInternalTexture);
  64562. this.video.removeEventListener("paused", this._updateInternalTexture);
  64563. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64564. this.video.removeEventListener("emptied", this.reset);
  64565. this.video.pause();
  64566. };
  64567. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64568. var video = document.createElement("video");
  64569. var constraintsDeviceId;
  64570. if (constraints && constraints.deviceId) {
  64571. constraintsDeviceId = {
  64572. exact: constraints.deviceId,
  64573. };
  64574. }
  64575. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64576. if (navigator.mediaDevices) {
  64577. navigator.mediaDevices.getUserMedia({ video: constraints })
  64578. .then(function (stream) {
  64579. if (video.mozSrcObject !== undefined) {
  64580. // hack for Firefox < 19
  64581. video.mozSrcObject = stream;
  64582. }
  64583. else {
  64584. video.srcObject = stream;
  64585. }
  64586. var onPlaying = function () {
  64587. if (onReady) {
  64588. onReady(new VideoTexture("video", video, scene, true, true));
  64589. }
  64590. video.removeEventListener("playing", onPlaying);
  64591. };
  64592. video.addEventListener("playing", onPlaying);
  64593. video.play();
  64594. })
  64595. .catch(function (err) {
  64596. BABYLON.Tools.Error(err.name);
  64597. });
  64598. }
  64599. else {
  64600. navigator.getUserMedia =
  64601. navigator.getUserMedia ||
  64602. navigator.webkitGetUserMedia ||
  64603. navigator.mozGetUserMedia ||
  64604. navigator.msGetUserMedia;
  64605. if (navigator.getUserMedia) {
  64606. navigator.getUserMedia({
  64607. video: {
  64608. deviceId: constraintsDeviceId,
  64609. width: {
  64610. min: (constraints && constraints.minWidth) || 256,
  64611. max: (constraints && constraints.maxWidth) || 640,
  64612. },
  64613. height: {
  64614. min: (constraints && constraints.minHeight) || 256,
  64615. max: (constraints && constraints.maxHeight) || 480,
  64616. },
  64617. },
  64618. }, function (stream) {
  64619. if (video.mozSrcObject !== undefined) {
  64620. // hack for Firefox < 19
  64621. video.mozSrcObject = stream;
  64622. }
  64623. else {
  64624. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64625. }
  64626. video.play();
  64627. if (onReady) {
  64628. onReady(new VideoTexture("video", video, scene, true, true));
  64629. }
  64630. }, function (e) {
  64631. BABYLON.Tools.Error(e.name);
  64632. });
  64633. }
  64634. }
  64635. };
  64636. return VideoTexture;
  64637. }(BABYLON.Texture));
  64638. BABYLON.VideoTexture = VideoTexture;
  64639. })(BABYLON || (BABYLON = {}));
  64640. //# sourceMappingURL=babylon.videoTexture.js.map
  64641. var BABYLON;
  64642. (function (BABYLON) {
  64643. var RawTexture = /** @class */ (function (_super) {
  64644. __extends(RawTexture, _super);
  64645. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64646. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64647. if (invertY === void 0) { invertY = false; }
  64648. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64649. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64650. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64651. _this.format = format;
  64652. _this._engine = scene.getEngine();
  64653. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64654. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64655. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64656. return _this;
  64657. }
  64658. RawTexture.prototype.update = function (data) {
  64659. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64660. };
  64661. // Statics
  64662. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64663. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64664. if (invertY === void 0) { invertY = false; }
  64665. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64666. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64667. };
  64668. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64669. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64670. if (invertY === void 0) { invertY = false; }
  64671. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64672. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64673. };
  64674. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64675. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64676. if (invertY === void 0) { invertY = false; }
  64677. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64678. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64679. };
  64680. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64681. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64682. if (invertY === void 0) { invertY = false; }
  64683. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64684. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64685. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64686. };
  64687. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64688. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64689. if (invertY === void 0) { invertY = false; }
  64690. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64691. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64692. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64693. };
  64694. return RawTexture;
  64695. }(BABYLON.Texture));
  64696. BABYLON.RawTexture = RawTexture;
  64697. })(BABYLON || (BABYLON = {}));
  64698. //# sourceMappingURL=babylon.rawTexture.js.map
  64699. var BABYLON;
  64700. (function (BABYLON) {
  64701. /**
  64702. * Class used to store 3D textures containing user data
  64703. */
  64704. var RawTexture3D = /** @class */ (function (_super) {
  64705. __extends(RawTexture3D, _super);
  64706. /**
  64707. * Create a new RawTexture3D
  64708. * @param data defines the data of the texture
  64709. * @param width defines the width of the texture
  64710. * @param height defines the height of the texture
  64711. * @param depth defines the depth of the texture
  64712. * @param format defines the texture format to use
  64713. * @param scene defines the hosting scene
  64714. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64715. * @param invertY defines if texture must be stored with Y axis inverted
  64716. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64717. */
  64718. function RawTexture3D(data, width, height, depth,
  64719. /** Gets or sets the texture format to use*/
  64720. format, scene, generateMipMaps, invertY, samplingMode) {
  64721. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64722. if (invertY === void 0) { invertY = false; }
  64723. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64724. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64725. _this.format = format;
  64726. _this._engine = scene.getEngine();
  64727. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  64728. _this.is3D = true;
  64729. return _this;
  64730. }
  64731. /**
  64732. * Update the texture with new data
  64733. * @param data defines the data to store in the texture
  64734. */
  64735. RawTexture3D.prototype.update = function (data) {
  64736. if (!this._texture) {
  64737. return;
  64738. }
  64739. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  64740. };
  64741. return RawTexture3D;
  64742. }(BABYLON.Texture));
  64743. BABYLON.RawTexture3D = RawTexture3D;
  64744. })(BABYLON || (BABYLON = {}));
  64745. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64746. var BABYLON;
  64747. (function (BABYLON) {
  64748. /**
  64749. * PostProcess can be used to apply a shader to a texture after it has been rendered
  64750. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64751. */
  64752. var PostProcess = /** @class */ (function () {
  64753. /**
  64754. * Creates a new instance PostProcess
  64755. * @param name The name of the PostProcess.
  64756. * @param fragmentUrl The url of the fragment shader to be used.
  64757. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  64758. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  64759. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  64760. * @param camera The camera to apply the render pass to.
  64761. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64762. * @param engine The engine which the post process will be applied. (default: current engine)
  64763. * @param reusable If the post process can be reused on the same frame. (default: false)
  64764. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  64765. * @param textureType Type of textures used when performing the post process. (default: 0)
  64766. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  64767. * @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
  64768. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  64769. */
  64770. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  64771. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  64772. if (defines === void 0) { defines = null; }
  64773. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64774. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  64775. if (blockCompilation === void 0) { blockCompilation = false; }
  64776. this.name = name;
  64777. /**
  64778. * Width of the texture to apply the post process on
  64779. */
  64780. this.width = -1;
  64781. /**
  64782. * Height of the texture to apply the post process on
  64783. */
  64784. this.height = -1;
  64785. /**
  64786. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  64787. */
  64788. this._outputTexture = null;
  64789. /**
  64790. * If the buffer needs to be cleared before applying the post process. (default: true)
  64791. * Should be set to false if shader will overwrite all previous pixels.
  64792. */
  64793. this.autoClear = true;
  64794. /**
  64795. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  64796. */
  64797. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  64798. /**
  64799. * Animations to be used for the post processing
  64800. */
  64801. this.animations = new Array();
  64802. /**
  64803. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  64804. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  64805. */
  64806. this.enablePixelPerfectMode = false;
  64807. /**
  64808. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  64809. */
  64810. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  64811. /**
  64812. * Force textures to be a power of two (default: false)
  64813. */
  64814. this.alwaysForcePOT = false;
  64815. /**
  64816. * Number of sample textures (default: 1)
  64817. */
  64818. this.samples = 1;
  64819. /**
  64820. * Modify the scale of the post process to be the same as the viewport (default: false)
  64821. */
  64822. this.adaptScaleToCurrentViewport = false;
  64823. this._reusable = false;
  64824. /**
  64825. * Smart array of input and output textures for the post process.
  64826. */
  64827. this._textures = new BABYLON.SmartArray(2);
  64828. /**
  64829. * The index in _textures that corresponds to the output texture.
  64830. */
  64831. this._currentRenderTextureInd = 0;
  64832. this._scaleRatio = new BABYLON.Vector2(1, 1);
  64833. this._texelSize = BABYLON.Vector2.Zero();
  64834. // Events
  64835. /**
  64836. * An event triggered when the postprocess is activated.
  64837. */
  64838. this.onActivateObservable = new BABYLON.Observable();
  64839. /**
  64840. * An event triggered when the postprocess changes its size.
  64841. */
  64842. this.onSizeChangedObservable = new BABYLON.Observable();
  64843. /**
  64844. * An event triggered when the postprocess applies its effect.
  64845. */
  64846. this.onApplyObservable = new BABYLON.Observable();
  64847. /**
  64848. * An event triggered before rendering the postprocess
  64849. */
  64850. this.onBeforeRenderObservable = new BABYLON.Observable();
  64851. /**
  64852. * An event triggered after rendering the postprocess
  64853. */
  64854. this.onAfterRenderObservable = new BABYLON.Observable();
  64855. if (camera != null) {
  64856. this._camera = camera;
  64857. this._scene = camera.getScene();
  64858. camera.attachPostProcess(this);
  64859. this._engine = this._scene.getEngine();
  64860. this._scene.postProcesses.push(this);
  64861. }
  64862. else if (engine) {
  64863. this._engine = engine;
  64864. this._engine.postProcesses.push(this);
  64865. }
  64866. this._options = options;
  64867. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  64868. this._reusable = reusable || false;
  64869. this._textureType = textureType;
  64870. this._samplers = samplers || [];
  64871. this._samplers.push("textureSampler");
  64872. this._fragmentUrl = fragmentUrl;
  64873. this._vertexUrl = vertexUrl;
  64874. this._parameters = parameters || [];
  64875. this._parameters.push("scale");
  64876. this._indexParameters = indexParameters;
  64877. if (!blockCompilation) {
  64878. this.updateEffect(defines);
  64879. }
  64880. }
  64881. Object.defineProperty(PostProcess.prototype, "onActivate", {
  64882. /**
  64883. * A function that is added to the onActivateObservable
  64884. */
  64885. set: function (callback) {
  64886. if (this._onActivateObserver) {
  64887. this.onActivateObservable.remove(this._onActivateObserver);
  64888. }
  64889. if (callback) {
  64890. this._onActivateObserver = this.onActivateObservable.add(callback);
  64891. }
  64892. },
  64893. enumerable: true,
  64894. configurable: true
  64895. });
  64896. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  64897. /**
  64898. * A function that is added to the onSizeChangedObservable
  64899. */
  64900. set: function (callback) {
  64901. if (this._onSizeChangedObserver) {
  64902. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  64903. }
  64904. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  64905. },
  64906. enumerable: true,
  64907. configurable: true
  64908. });
  64909. Object.defineProperty(PostProcess.prototype, "onApply", {
  64910. /**
  64911. * A function that is added to the onApplyObservable
  64912. */
  64913. set: function (callback) {
  64914. if (this._onApplyObserver) {
  64915. this.onApplyObservable.remove(this._onApplyObserver);
  64916. }
  64917. this._onApplyObserver = this.onApplyObservable.add(callback);
  64918. },
  64919. enumerable: true,
  64920. configurable: true
  64921. });
  64922. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  64923. /**
  64924. * A function that is added to the onBeforeRenderObservable
  64925. */
  64926. set: function (callback) {
  64927. if (this._onBeforeRenderObserver) {
  64928. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  64929. }
  64930. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  64931. },
  64932. enumerable: true,
  64933. configurable: true
  64934. });
  64935. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  64936. /**
  64937. * A function that is added to the onAfterRenderObservable
  64938. */
  64939. set: function (callback) {
  64940. if (this._onAfterRenderObserver) {
  64941. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  64942. }
  64943. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  64944. },
  64945. enumerable: true,
  64946. configurable: true
  64947. });
  64948. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  64949. /**
  64950. * 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
  64951. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  64952. */
  64953. get: function () {
  64954. return this._textures.data[this._currentRenderTextureInd];
  64955. },
  64956. set: function (value) {
  64957. this._forcedOutputTexture = value;
  64958. },
  64959. enumerable: true,
  64960. configurable: true
  64961. });
  64962. /**
  64963. * Gets the camera which post process is applied to.
  64964. * @returns The camera the post process is applied to.
  64965. */
  64966. PostProcess.prototype.getCamera = function () {
  64967. return this._camera;
  64968. };
  64969. Object.defineProperty(PostProcess.prototype, "texelSize", {
  64970. /**
  64971. * Gets the texel size of the postprocess.
  64972. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  64973. */
  64974. get: function () {
  64975. if (this._shareOutputWithPostProcess) {
  64976. return this._shareOutputWithPostProcess.texelSize;
  64977. }
  64978. if (this._forcedOutputTexture) {
  64979. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  64980. }
  64981. return this._texelSize;
  64982. },
  64983. enumerable: true,
  64984. configurable: true
  64985. });
  64986. /**
  64987. * Gets the engine which this post process belongs to.
  64988. * @returns The engine the post process was enabled with.
  64989. */
  64990. PostProcess.prototype.getEngine = function () {
  64991. return this._engine;
  64992. };
  64993. /**
  64994. * The effect that is created when initializing the post process.
  64995. * @returns The created effect corrisponding the the postprocess.
  64996. */
  64997. PostProcess.prototype.getEffect = function () {
  64998. return this._effect;
  64999. };
  65000. /**
  65001. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65002. * @param postProcess The post process to share the output with.
  65003. * @returns This post process.
  65004. */
  65005. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65006. this._disposeTextures();
  65007. this._shareOutputWithPostProcess = postProcess;
  65008. return this;
  65009. };
  65010. /**
  65011. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65012. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65013. */
  65014. PostProcess.prototype.useOwnOutput = function () {
  65015. if (this._textures.length == 0) {
  65016. this._textures = new BABYLON.SmartArray(2);
  65017. }
  65018. this._shareOutputWithPostProcess = null;
  65019. };
  65020. /**
  65021. * Updates the effect with the current post process compile time values and recompiles the shader.
  65022. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65023. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65024. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65025. * @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
  65026. * @param onCompiled Called when the shader has been compiled.
  65027. * @param onError Called if there is an error when compiling a shader.
  65028. */
  65029. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65030. if (defines === void 0) { defines = null; }
  65031. if (uniforms === void 0) { uniforms = null; }
  65032. if (samplers === void 0) { samplers = null; }
  65033. 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);
  65034. };
  65035. /**
  65036. * The post process is reusable if it can be used multiple times within one frame.
  65037. * @returns If the post process is reusable
  65038. */
  65039. PostProcess.prototype.isReusable = function () {
  65040. return this._reusable;
  65041. };
  65042. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65043. PostProcess.prototype.markTextureDirty = function () {
  65044. this.width = -1;
  65045. };
  65046. /**
  65047. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65048. * 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.
  65049. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65050. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65051. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65052. * @returns The target texture that was bound to be written to.
  65053. */
  65054. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65055. var _this = this;
  65056. if (sourceTexture === void 0) { sourceTexture = null; }
  65057. camera = camera || this._camera;
  65058. var scene = camera.getScene();
  65059. var engine = scene.getEngine();
  65060. var maxSize = engine.getCaps().maxTextureSize;
  65061. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65062. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65063. // 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
  65064. var webVRCamera = camera.parent;
  65065. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65066. requiredWidth /= 2;
  65067. }
  65068. var desiredWidth = (this._options.width || requiredWidth);
  65069. var desiredHeight = this._options.height || requiredHeight;
  65070. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65071. if (this.adaptScaleToCurrentViewport) {
  65072. var currentViewport = engine.currentViewport;
  65073. if (currentViewport) {
  65074. desiredWidth *= currentViewport.width;
  65075. desiredHeight *= currentViewport.height;
  65076. }
  65077. }
  65078. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65079. if (!this._options.width) {
  65080. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65081. }
  65082. if (!this._options.height) {
  65083. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65084. }
  65085. }
  65086. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65087. if (this._textures.length > 0) {
  65088. for (var i = 0; i < this._textures.length; i++) {
  65089. this._engine._releaseTexture(this._textures.data[i]);
  65090. }
  65091. this._textures.reset();
  65092. }
  65093. this.width = desiredWidth;
  65094. this.height = desiredHeight;
  65095. var textureSize = { width: this.width, height: this.height };
  65096. var textureOptions = {
  65097. generateMipMaps: false,
  65098. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65099. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65100. samplingMode: this.renderTargetSamplingMode,
  65101. type: this._textureType
  65102. };
  65103. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65104. if (this._reusable) {
  65105. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65106. }
  65107. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65108. this.onSizeChangedObservable.notifyObservers(this);
  65109. }
  65110. this._textures.forEach(function (texture) {
  65111. if (texture.samples !== _this.samples) {
  65112. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65113. }
  65114. });
  65115. }
  65116. var target;
  65117. if (this._shareOutputWithPostProcess) {
  65118. target = this._shareOutputWithPostProcess.inputTexture;
  65119. }
  65120. else if (this._forcedOutputTexture) {
  65121. target = this._forcedOutputTexture;
  65122. this.width = this._forcedOutputTexture.width;
  65123. this.height = this._forcedOutputTexture.height;
  65124. }
  65125. else {
  65126. target = this.inputTexture;
  65127. }
  65128. // Bind the input of this post process to be used as the output of the previous post process.
  65129. if (this.enablePixelPerfectMode) {
  65130. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65131. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  65132. }
  65133. else {
  65134. this._scaleRatio.copyFromFloats(1, 1);
  65135. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  65136. }
  65137. this.onActivateObservable.notifyObservers(camera);
  65138. // Clear
  65139. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65140. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65141. }
  65142. if (this._reusable) {
  65143. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65144. }
  65145. return target;
  65146. };
  65147. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65148. /**
  65149. * If the post process is supported.
  65150. */
  65151. get: function () {
  65152. return this._effect.isSupported;
  65153. },
  65154. enumerable: true,
  65155. configurable: true
  65156. });
  65157. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65158. /**
  65159. * The aspect ratio of the output texture.
  65160. */
  65161. get: function () {
  65162. if (this._shareOutputWithPostProcess) {
  65163. return this._shareOutputWithPostProcess.aspectRatio;
  65164. }
  65165. if (this._forcedOutputTexture) {
  65166. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65167. }
  65168. return this.width / this.height;
  65169. },
  65170. enumerable: true,
  65171. configurable: true
  65172. });
  65173. /**
  65174. * Get a value indicating if the post-process is ready to be used
  65175. * @returns true if the post-process is ready (shader is compiled)
  65176. */
  65177. PostProcess.prototype.isReady = function () {
  65178. return this._effect && this._effect.isReady();
  65179. };
  65180. /**
  65181. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65182. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65183. */
  65184. PostProcess.prototype.apply = function () {
  65185. // Check
  65186. if (!this._effect || !this._effect.isReady())
  65187. return null;
  65188. // States
  65189. this._engine.enableEffect(this._effect);
  65190. this._engine.setState(false);
  65191. this._engine.setDepthBuffer(false);
  65192. this._engine.setDepthWrite(false);
  65193. // Alpha
  65194. this._engine.setAlphaMode(this.alphaMode);
  65195. if (this.alphaConstants) {
  65196. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65197. }
  65198. // Bind the output texture of the preivous post process as the input to this post process.
  65199. var source;
  65200. if (this._shareOutputWithPostProcess) {
  65201. source = this._shareOutputWithPostProcess.inputTexture;
  65202. }
  65203. else if (this._forcedOutputTexture) {
  65204. source = this._forcedOutputTexture;
  65205. }
  65206. else {
  65207. source = this.inputTexture;
  65208. }
  65209. this._effect._bindTexture("textureSampler", source);
  65210. // Parameters
  65211. this._effect.setVector2("scale", this._scaleRatio);
  65212. this.onApplyObservable.notifyObservers(this._effect);
  65213. return this._effect;
  65214. };
  65215. PostProcess.prototype._disposeTextures = function () {
  65216. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65217. return;
  65218. }
  65219. if (this._textures.length > 0) {
  65220. for (var i = 0; i < this._textures.length; i++) {
  65221. this._engine._releaseTexture(this._textures.data[i]);
  65222. }
  65223. }
  65224. this._textures.dispose();
  65225. };
  65226. /**
  65227. * Disposes the post process.
  65228. * @param camera The camera to dispose the post process on.
  65229. */
  65230. PostProcess.prototype.dispose = function (camera) {
  65231. camera = camera || this._camera;
  65232. this._disposeTextures();
  65233. if (this._scene) {
  65234. var index_1 = this._scene.postProcesses.indexOf(this);
  65235. if (index_1 !== -1) {
  65236. this._scene.postProcesses.splice(index_1, 1);
  65237. }
  65238. }
  65239. else {
  65240. var index_2 = this._engine.postProcesses.indexOf(this);
  65241. if (index_2 !== -1) {
  65242. this._engine.postProcesses.splice(index_2, 1);
  65243. }
  65244. }
  65245. if (!camera) {
  65246. return;
  65247. }
  65248. camera.detachPostProcess(this);
  65249. var index = camera._postProcesses.indexOf(this);
  65250. if (index === 0 && camera._postProcesses.length > 0) {
  65251. var firstPostProcess = this._camera._getFirstPostProcess();
  65252. if (firstPostProcess) {
  65253. firstPostProcess.markTextureDirty();
  65254. }
  65255. }
  65256. this.onActivateObservable.clear();
  65257. this.onAfterRenderObservable.clear();
  65258. this.onApplyObservable.clear();
  65259. this.onBeforeRenderObservable.clear();
  65260. this.onSizeChangedObservable.clear();
  65261. };
  65262. return PostProcess;
  65263. }());
  65264. BABYLON.PostProcess = PostProcess;
  65265. })(BABYLON || (BABYLON = {}));
  65266. //# sourceMappingURL=babylon.postProcess.js.map
  65267. var BABYLON;
  65268. (function (BABYLON) {
  65269. var PassPostProcess = /** @class */ (function (_super) {
  65270. __extends(PassPostProcess, _super);
  65271. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65272. if (camera === void 0) { camera = null; }
  65273. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65274. if (blockCompilation === void 0) { blockCompilation = false; }
  65275. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65276. }
  65277. return PassPostProcess;
  65278. }(BABYLON.PostProcess));
  65279. BABYLON.PassPostProcess = PassPostProcess;
  65280. })(BABYLON || (BABYLON = {}));
  65281. //# sourceMappingURL=babylon.passPostProcess.js.map
  65282. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65283. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65284. s = arguments[i];
  65285. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65286. t[p] = s[p];
  65287. }
  65288. return t;
  65289. };
  65290. var BABYLON;
  65291. (function (BABYLON) {
  65292. /**
  65293. * Default implementation IShadowGenerator.
  65294. * This is the main object responsible of generating shadows in the framework.
  65295. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65296. */
  65297. var ShadowGenerator = /** @class */ (function () {
  65298. /**
  65299. * Creates a ShadowGenerator object.
  65300. * A ShadowGenerator is the required tool to use the shadows.
  65301. * Each light casting shadows needs to use its own ShadowGenerator.
  65302. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65303. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65304. * @param light The light object generating the shadows.
  65305. * @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.
  65306. */
  65307. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65308. this._bias = 0.00005;
  65309. this._normalBias = 0;
  65310. this._blurBoxOffset = 1;
  65311. this._blurScale = 2;
  65312. this._blurKernel = 1;
  65313. this._useKernelBlur = false;
  65314. this._filter = ShadowGenerator.FILTER_NONE;
  65315. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65316. this._contactHardeningLightSizeUVRatio = 0.1;
  65317. this._darkness = 0;
  65318. this._transparencyShadow = false;
  65319. /**
  65320. * Controls the extent to which the shadows fade out at the edge of the frustum
  65321. * Used only by directionals and spots
  65322. */
  65323. this.frustumEdgeFalloff = 0;
  65324. /**
  65325. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65326. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65327. * It might on the other hand introduce peter panning.
  65328. */
  65329. this.forceBackFacesOnly = false;
  65330. this._lightDirection = BABYLON.Vector3.Zero();
  65331. this._viewMatrix = BABYLON.Matrix.Zero();
  65332. this._projectionMatrix = BABYLON.Matrix.Zero();
  65333. this._transformMatrix = BABYLON.Matrix.Zero();
  65334. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65335. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65336. this._currentFaceIndex = 0;
  65337. this._currentFaceIndexCache = 0;
  65338. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65339. this._mapSize = mapSize;
  65340. this._light = light;
  65341. this._scene = light.getScene();
  65342. light._shadowGenerator = this;
  65343. // Texture type fallback from float to int if not supported.
  65344. var caps = this._scene.getEngine().getCaps();
  65345. if (!useFullFloatFirst) {
  65346. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65347. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65348. }
  65349. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65350. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65351. }
  65352. else {
  65353. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65354. }
  65355. }
  65356. else {
  65357. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65358. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65359. }
  65360. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65361. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65362. }
  65363. else {
  65364. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65365. }
  65366. }
  65367. this._initializeGenerator();
  65368. this._applyFilterValues();
  65369. }
  65370. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65371. /**
  65372. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65373. */
  65374. get: function () {
  65375. return this._bias;
  65376. },
  65377. /**
  65378. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65379. */
  65380. set: function (bias) {
  65381. this._bias = bias;
  65382. },
  65383. enumerable: true,
  65384. configurable: true
  65385. });
  65386. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65387. /**
  65388. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65389. */
  65390. get: function () {
  65391. return this._normalBias;
  65392. },
  65393. /**
  65394. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65395. */
  65396. set: function (normalBias) {
  65397. this._normalBias = normalBias;
  65398. },
  65399. enumerable: true,
  65400. configurable: true
  65401. });
  65402. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65403. /**
  65404. * Gets the blur box offset: offset applied during the blur pass.
  65405. * Only usefull if useKernelBlur = false
  65406. */
  65407. get: function () {
  65408. return this._blurBoxOffset;
  65409. },
  65410. /**
  65411. * Sets the blur box offset: offset applied during the blur pass.
  65412. * Only usefull if useKernelBlur = false
  65413. */
  65414. set: function (value) {
  65415. if (this._blurBoxOffset === value) {
  65416. return;
  65417. }
  65418. this._blurBoxOffset = value;
  65419. this._disposeBlurPostProcesses();
  65420. },
  65421. enumerable: true,
  65422. configurable: true
  65423. });
  65424. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65425. /**
  65426. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65427. * 2 means half of the size.
  65428. */
  65429. get: function () {
  65430. return this._blurScale;
  65431. },
  65432. /**
  65433. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65434. * 2 means half of the size.
  65435. */
  65436. set: function (value) {
  65437. if (this._blurScale === value) {
  65438. return;
  65439. }
  65440. this._blurScale = value;
  65441. this._disposeBlurPostProcesses();
  65442. },
  65443. enumerable: true,
  65444. configurable: true
  65445. });
  65446. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65447. /**
  65448. * Gets the blur kernel: kernel size of the blur pass.
  65449. * Only usefull if useKernelBlur = true
  65450. */
  65451. get: function () {
  65452. return this._blurKernel;
  65453. },
  65454. /**
  65455. * Sets the blur kernel: kernel size of the blur pass.
  65456. * Only usefull if useKernelBlur = true
  65457. */
  65458. set: function (value) {
  65459. if (this._blurKernel === value) {
  65460. return;
  65461. }
  65462. this._blurKernel = value;
  65463. this._disposeBlurPostProcesses();
  65464. },
  65465. enumerable: true,
  65466. configurable: true
  65467. });
  65468. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65469. /**
  65470. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65471. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65472. */
  65473. get: function () {
  65474. return this._useKernelBlur;
  65475. },
  65476. /**
  65477. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65478. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65479. */
  65480. set: function (value) {
  65481. if (this._useKernelBlur === value) {
  65482. return;
  65483. }
  65484. this._useKernelBlur = value;
  65485. this._disposeBlurPostProcesses();
  65486. },
  65487. enumerable: true,
  65488. configurable: true
  65489. });
  65490. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65491. /**
  65492. * Gets the depth scale used in ESM mode.
  65493. */
  65494. get: function () {
  65495. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65496. },
  65497. /**
  65498. * Sets the depth scale used in ESM mode.
  65499. * This can override the scale stored on the light.
  65500. */
  65501. set: function (value) {
  65502. this._depthScale = value;
  65503. },
  65504. enumerable: true,
  65505. configurable: true
  65506. });
  65507. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  65508. /**
  65509. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  65510. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65511. */
  65512. get: function () {
  65513. return this._filter;
  65514. },
  65515. /**
  65516. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  65517. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65518. */
  65519. set: function (value) {
  65520. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  65521. if (this._light.needCube()) {
  65522. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65523. this.useExponentialShadowMap = true;
  65524. return;
  65525. }
  65526. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65527. this.useCloseExponentialShadowMap = true;
  65528. return;
  65529. }
  65530. // PCF on cubemap would also be expensive
  65531. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65532. this.usePoissonSampling = true;
  65533. return;
  65534. }
  65535. }
  65536. // Weblg1 fallback for PCF.
  65537. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65538. if (this._scene.getEngine().webGLVersion === 1) {
  65539. this.usePoissonSampling = true;
  65540. return;
  65541. }
  65542. }
  65543. if (this._filter === value) {
  65544. return;
  65545. }
  65546. this._filter = value;
  65547. this._disposeBlurPostProcesses();
  65548. this._applyFilterValues();
  65549. this._light._markMeshesAsLightDirty();
  65550. },
  65551. enumerable: true,
  65552. configurable: true
  65553. });
  65554. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  65555. /**
  65556. * Gets if the current filter is set to Poisson Sampling.
  65557. */
  65558. get: function () {
  65559. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  65560. },
  65561. /**
  65562. * Sets the current filter to Poisson Sampling.
  65563. */
  65564. set: function (value) {
  65565. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  65566. return;
  65567. }
  65568. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65569. },
  65570. enumerable: true,
  65571. configurable: true
  65572. });
  65573. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65574. /**
  65575. * Gets if the current filter is set to VSM.
  65576. * DEPRECATED. Should use useExponentialShadowMap instead.
  65577. */
  65578. get: function () {
  65579. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65580. return this.useExponentialShadowMap;
  65581. },
  65582. /**
  65583. * Sets the current filter is to VSM.
  65584. * DEPRECATED. Should use useExponentialShadowMap instead.
  65585. */
  65586. set: function (value) {
  65587. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65588. this.useExponentialShadowMap = value;
  65589. },
  65590. enumerable: true,
  65591. configurable: true
  65592. });
  65593. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65594. /**
  65595. * Gets if the current filter is set to blurred VSM.
  65596. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65597. */
  65598. get: function () {
  65599. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65600. return this.useBlurExponentialShadowMap;
  65601. },
  65602. /**
  65603. * Sets the current filter is to blurred VSM.
  65604. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65605. */
  65606. set: function (value) {
  65607. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65608. this.useBlurExponentialShadowMap = value;
  65609. },
  65610. enumerable: true,
  65611. configurable: true
  65612. });
  65613. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65614. /**
  65615. * Gets if the current filter is set to ESM.
  65616. */
  65617. get: function () {
  65618. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65619. },
  65620. /**
  65621. * Sets the current filter is to ESM.
  65622. */
  65623. set: function (value) {
  65624. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65625. return;
  65626. }
  65627. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65628. },
  65629. enumerable: true,
  65630. configurable: true
  65631. });
  65632. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  65633. /**
  65634. * Gets if the current filter is set to filtered ESM.
  65635. */
  65636. get: function () {
  65637. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  65638. },
  65639. /**
  65640. * Gets if the current filter is set to filtered ESM.
  65641. */
  65642. set: function (value) {
  65643. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65644. return;
  65645. }
  65646. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65647. },
  65648. enumerable: true,
  65649. configurable: true
  65650. });
  65651. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  65652. /**
  65653. * Gets if the current filter is set to "close ESM" (using the inverse of the
  65654. * exponential to prevent steep falloff artifacts).
  65655. */
  65656. get: function () {
  65657. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  65658. },
  65659. /**
  65660. * Sets the current filter to "close ESM" (using the inverse of the
  65661. * exponential to prevent steep falloff artifacts).
  65662. */
  65663. set: function (value) {
  65664. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  65665. return;
  65666. }
  65667. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65668. },
  65669. enumerable: true,
  65670. configurable: true
  65671. });
  65672. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  65673. /**
  65674. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  65675. * exponential to prevent steep falloff artifacts).
  65676. */
  65677. get: function () {
  65678. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  65679. },
  65680. /**
  65681. * Sets the current filter to filtered "close ESM" (using the inverse of the
  65682. * exponential to prevent steep falloff artifacts).
  65683. */
  65684. set: function (value) {
  65685. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65686. return;
  65687. }
  65688. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65689. },
  65690. enumerable: true,
  65691. configurable: true
  65692. });
  65693. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  65694. /**
  65695. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  65696. */
  65697. get: function () {
  65698. return this.filter === ShadowGenerator.FILTER_PCF;
  65699. },
  65700. /**
  65701. * Sets the current filter to "PCF" (percentage closer filtering).
  65702. */
  65703. set: function (value) {
  65704. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  65705. return;
  65706. }
  65707. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  65708. },
  65709. enumerable: true,
  65710. configurable: true
  65711. });
  65712. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  65713. /**
  65714. * Gets the PCF or PCSS Quality.
  65715. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65716. */
  65717. get: function () {
  65718. return this._filteringQuality;
  65719. },
  65720. /**
  65721. * Sets the PCF or PCSS Quality.
  65722. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65723. */
  65724. set: function (filteringQuality) {
  65725. this._filteringQuality = filteringQuality;
  65726. },
  65727. enumerable: true,
  65728. configurable: true
  65729. });
  65730. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  65731. /**
  65732. * Gets if the current filter is set to "PCSS" (contact hardening).
  65733. */
  65734. get: function () {
  65735. return this.filter === ShadowGenerator.FILTER_PCSS;
  65736. },
  65737. /**
  65738. * Sets the current filter to "PCSS" (contact hardening).
  65739. */
  65740. set: function (value) {
  65741. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  65742. return;
  65743. }
  65744. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  65745. },
  65746. enumerable: true,
  65747. configurable: true
  65748. });
  65749. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  65750. /**
  65751. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65752. * Using a ratio helps keeping shape stability independently of the map size.
  65753. *
  65754. * It does not account for the light projection as it was having too much
  65755. * instability during the light setup or during light position changes.
  65756. *
  65757. * Only valid if useContactHardeningShadow is true.
  65758. */
  65759. get: function () {
  65760. return this._contactHardeningLightSizeUVRatio;
  65761. },
  65762. /**
  65763. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65764. * Using a ratio helps keeping shape stability independently of the map size.
  65765. *
  65766. * It does not account for the light projection as it was having too much
  65767. * instability during the light setup or during light position changes.
  65768. *
  65769. * Only valid if useContactHardeningShadow is true.
  65770. */
  65771. set: function (contactHardeningLightSizeUVRatio) {
  65772. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  65773. },
  65774. enumerable: true,
  65775. configurable: true
  65776. });
  65777. /**
  65778. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  65779. * 0 means strongest and 1 would means no shadow.
  65780. * @returns the darkness.
  65781. */
  65782. ShadowGenerator.prototype.getDarkness = function () {
  65783. return this._darkness;
  65784. };
  65785. /**
  65786. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  65787. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  65788. * @returns the shadow generator allowing fluent coding.
  65789. */
  65790. ShadowGenerator.prototype.setDarkness = function (darkness) {
  65791. if (darkness >= 1.0)
  65792. this._darkness = 1.0;
  65793. else if (darkness <= 0.0)
  65794. this._darkness = 0.0;
  65795. else
  65796. this._darkness = darkness;
  65797. return this;
  65798. };
  65799. /**
  65800. * Sets the ability to have transparent shadow (boolean).
  65801. * @param transparent True if transparent else False
  65802. * @returns the shadow generator allowing fluent coding
  65803. */
  65804. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  65805. this._transparencyShadow = transparent;
  65806. return this;
  65807. };
  65808. /**
  65809. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  65810. * @returns The render target texture if present otherwise, null
  65811. */
  65812. ShadowGenerator.prototype.getShadowMap = function () {
  65813. return this._shadowMap;
  65814. };
  65815. /**
  65816. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  65817. * @returns The render target texture if the shadow map is present otherwise, null
  65818. */
  65819. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  65820. if (this._shadowMap2) {
  65821. return this._shadowMap2;
  65822. }
  65823. return this._shadowMap;
  65824. };
  65825. /**
  65826. * Helper function to add a mesh and its descendants to the list of shadow casters.
  65827. * @param mesh Mesh to add
  65828. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  65829. * @returns the Shadow Generator itself
  65830. */
  65831. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  65832. if (includeDescendants === void 0) { includeDescendants = true; }
  65833. if (!this._shadowMap) {
  65834. return this;
  65835. }
  65836. if (!this._shadowMap.renderList) {
  65837. this._shadowMap.renderList = [];
  65838. }
  65839. this._shadowMap.renderList.push(mesh);
  65840. if (includeDescendants) {
  65841. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  65842. }
  65843. return this;
  65844. var _a;
  65845. };
  65846. /**
  65847. * Helper function to remove a mesh and its descendants from the list of shadow casters
  65848. * @param mesh Mesh to remove
  65849. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  65850. * @returns the Shadow Generator itself
  65851. */
  65852. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  65853. if (includeDescendants === void 0) { includeDescendants = true; }
  65854. if (!this._shadowMap || !this._shadowMap.renderList) {
  65855. return this;
  65856. }
  65857. var index = this._shadowMap.renderList.indexOf(mesh);
  65858. if (index !== -1) {
  65859. this._shadowMap.renderList.splice(index, 1);
  65860. }
  65861. if (includeDescendants) {
  65862. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  65863. var child = _a[_i];
  65864. this.removeShadowCaster(child);
  65865. }
  65866. }
  65867. return this;
  65868. };
  65869. /**
  65870. * Returns the associated light object.
  65871. * @returns the light generating the shadow
  65872. */
  65873. ShadowGenerator.prototype.getLight = function () {
  65874. return this._light;
  65875. };
  65876. ShadowGenerator.prototype._initializeGenerator = function () {
  65877. this._light._markMeshesAsLightDirty();
  65878. this._initializeShadowMap();
  65879. };
  65880. ShadowGenerator.prototype._initializeShadowMap = function () {
  65881. var _this = this;
  65882. // Render target
  65883. var engine = this._scene.getEngine();
  65884. if (engine.webGLVersion > 1) {
  65885. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  65886. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  65887. }
  65888. else {
  65889. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  65890. }
  65891. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65892. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65893. this._shadowMap.anisotropicFilteringLevel = 1;
  65894. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65895. this._shadowMap.renderParticles = false;
  65896. this._shadowMap.ignoreCameraViewport = true;
  65897. // Record Face Index before render.
  65898. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  65899. _this._currentFaceIndex = faceIndex;
  65900. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65901. engine.setColorWrite(false);
  65902. }
  65903. });
  65904. // Custom render function.
  65905. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  65906. // Blur if required afer render.
  65907. this._shadowMap.onAfterUnbindObservable.add(function () {
  65908. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65909. engine.setColorWrite(true);
  65910. }
  65911. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  65912. return;
  65913. }
  65914. var shadowMap = _this.getShadowMapForRendering();
  65915. if (shadowMap) {
  65916. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  65917. }
  65918. });
  65919. // Clear according to the chosen filter.
  65920. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  65921. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  65922. this._shadowMap.onClearObservable.add(function (engine) {
  65923. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65924. engine.clear(clearOne, false, true, false);
  65925. }
  65926. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  65927. engine.clear(clearZero, true, true, false);
  65928. }
  65929. else {
  65930. engine.clear(clearOne, true, true, false);
  65931. }
  65932. });
  65933. };
  65934. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  65935. var _this = this;
  65936. var engine = this._scene.getEngine();
  65937. var targetSize = this._mapSize / this.blurScale;
  65938. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  65939. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  65940. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65941. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65942. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65943. }
  65944. if (this.useKernelBlur) {
  65945. 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);
  65946. this._kernelBlurXPostprocess.width = targetSize;
  65947. this._kernelBlurXPostprocess.height = targetSize;
  65948. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  65949. effect.setTexture("textureSampler", _this._shadowMap);
  65950. });
  65951. 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);
  65952. this._kernelBlurXPostprocess.autoClear = false;
  65953. this._kernelBlurYPostprocess.autoClear = false;
  65954. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65955. this._kernelBlurXPostprocess.packedFloat = true;
  65956. this._kernelBlurYPostprocess.packedFloat = true;
  65957. }
  65958. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  65959. }
  65960. else {
  65961. 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);
  65962. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  65963. effect.setFloat2("screenSize", targetSize, targetSize);
  65964. effect.setTexture("textureSampler", _this._shadowMap);
  65965. });
  65966. this._boxBlurPostprocess.autoClear = false;
  65967. this._blurPostProcesses = [this._boxBlurPostprocess];
  65968. }
  65969. };
  65970. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65971. var index;
  65972. var engine = this._scene.getEngine();
  65973. if (depthOnlySubMeshes.length) {
  65974. engine.setColorWrite(false);
  65975. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65976. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  65977. }
  65978. engine.setColorWrite(true);
  65979. }
  65980. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65981. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  65982. }
  65983. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65984. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  65985. }
  65986. if (this._transparencyShadow) {
  65987. for (index = 0; index < transparentSubMeshes.length; index++) {
  65988. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  65989. }
  65990. }
  65991. };
  65992. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  65993. var _this = this;
  65994. var mesh = subMesh.getRenderingMesh();
  65995. var scene = this._scene;
  65996. var engine = scene.getEngine();
  65997. var material = subMesh.getMaterial();
  65998. if (!material) {
  65999. return;
  66000. }
  66001. // Culling
  66002. engine.setState(material.backFaceCulling);
  66003. // Managing instances
  66004. var batch = mesh._getInstancesRenderList(subMesh._id);
  66005. if (batch.mustReturn) {
  66006. return;
  66007. }
  66008. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66009. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66010. engine.enableEffect(this._effect);
  66011. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66012. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66013. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66014. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66015. this._effect.setVector3("lightData", this._cachedDirection);
  66016. }
  66017. else {
  66018. this._effect.setVector3("lightData", this._cachedPosition);
  66019. }
  66020. if (scene.activeCamera) {
  66021. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66022. }
  66023. // Alpha test
  66024. if (material && material.needAlphaTesting()) {
  66025. var alphaTexture = material.getAlphaTestTexture();
  66026. if (alphaTexture) {
  66027. this._effect.setTexture("diffuseSampler", alphaTexture);
  66028. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66029. }
  66030. }
  66031. // Bones
  66032. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66033. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66034. }
  66035. // Morph targets
  66036. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66037. if (this.forceBackFacesOnly) {
  66038. engine.setState(true, 0, false, true);
  66039. }
  66040. // Draw
  66041. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66042. if (this.forceBackFacesOnly) {
  66043. engine.setState(true, 0, false, false);
  66044. }
  66045. }
  66046. else {
  66047. // Need to reset refresh rate of the shadowMap
  66048. if (this._shadowMap) {
  66049. this._shadowMap.resetRefreshCounter();
  66050. }
  66051. }
  66052. };
  66053. ShadowGenerator.prototype._applyFilterValues = function () {
  66054. if (!this._shadowMap) {
  66055. return;
  66056. }
  66057. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66058. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66059. }
  66060. else {
  66061. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66062. }
  66063. };
  66064. /**
  66065. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66066. * @param onCompiled Callback triggered at the and of the effects compilation
  66067. * @param options Sets of optional options forcing the compilation with different modes
  66068. */
  66069. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66070. var _this = this;
  66071. var localOptions = __assign({ useInstances: false }, options);
  66072. var shadowMap = this.getShadowMap();
  66073. if (!shadowMap) {
  66074. if (onCompiled) {
  66075. onCompiled(this);
  66076. }
  66077. return;
  66078. }
  66079. var renderList = shadowMap.renderList;
  66080. if (!renderList) {
  66081. if (onCompiled) {
  66082. onCompiled(this);
  66083. }
  66084. return;
  66085. }
  66086. var subMeshes = new Array();
  66087. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66088. var mesh = renderList_1[_i];
  66089. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66090. }
  66091. if (subMeshes.length === 0) {
  66092. if (onCompiled) {
  66093. onCompiled(this);
  66094. }
  66095. return;
  66096. }
  66097. var currentIndex = 0;
  66098. var checkReady = function () {
  66099. if (!_this._scene || !_this._scene.getEngine()) {
  66100. return;
  66101. }
  66102. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66103. currentIndex++;
  66104. if (currentIndex >= subMeshes.length) {
  66105. if (onCompiled) {
  66106. onCompiled(_this);
  66107. }
  66108. return;
  66109. }
  66110. }
  66111. setTimeout(checkReady, 16);
  66112. };
  66113. checkReady();
  66114. };
  66115. /**
  66116. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66117. * @param options Sets of optional options forcing the compilation with different modes
  66118. * @returns A promise that resolves when the compilation completes
  66119. */
  66120. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66121. var _this = this;
  66122. return new Promise(function (resolve) {
  66123. _this.forceCompilation(function () {
  66124. resolve();
  66125. }, options);
  66126. });
  66127. };
  66128. /**
  66129. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66130. * @param subMesh The submesh we want to render in the shadow map
  66131. * @param useInstances Defines wether will draw in the map using instances
  66132. * @returns true if ready otherwise, false
  66133. */
  66134. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66135. var defines = [];
  66136. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66137. defines.push("#define FLOAT");
  66138. }
  66139. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66140. defines.push("#define ESM");
  66141. }
  66142. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66143. defines.push("#define DEPTHTEXTURE");
  66144. }
  66145. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66146. var mesh = subMesh.getMesh();
  66147. var material = subMesh.getMaterial();
  66148. // Normal bias.
  66149. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66150. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66151. defines.push("#define NORMAL");
  66152. if (mesh.nonUniformScaling) {
  66153. defines.push("#define NONUNIFORMSCALING");
  66154. }
  66155. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66156. defines.push("#define DIRECTIONINLIGHTDATA");
  66157. }
  66158. }
  66159. // Alpha test
  66160. if (material && material.needAlphaTesting()) {
  66161. var alphaTexture = material.getAlphaTestTexture();
  66162. if (alphaTexture) {
  66163. defines.push("#define ALPHATEST");
  66164. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66165. attribs.push(BABYLON.VertexBuffer.UVKind);
  66166. defines.push("#define UV1");
  66167. }
  66168. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66169. if (alphaTexture.coordinatesIndex === 1) {
  66170. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66171. defines.push("#define UV2");
  66172. }
  66173. }
  66174. }
  66175. }
  66176. // Bones
  66177. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66178. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66179. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66180. if (mesh.numBoneInfluencers > 4) {
  66181. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66182. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66183. }
  66184. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66185. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66186. }
  66187. else {
  66188. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66189. }
  66190. // Morph targets
  66191. var manager = mesh.morphTargetManager;
  66192. var morphInfluencers = 0;
  66193. if (manager) {
  66194. if (manager.numInfluencers > 0) {
  66195. defines.push("#define MORPHTARGETS");
  66196. morphInfluencers = manager.numInfluencers;
  66197. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66198. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66199. }
  66200. }
  66201. // Instances
  66202. if (useInstances) {
  66203. defines.push("#define INSTANCES");
  66204. attribs.push("world0");
  66205. attribs.push("world1");
  66206. attribs.push("world2");
  66207. attribs.push("world3");
  66208. }
  66209. // Get correct effect
  66210. var join = defines.join("\n");
  66211. if (this._cachedDefines !== join) {
  66212. this._cachedDefines = join;
  66213. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66214. }
  66215. if (!this._effect.isReady()) {
  66216. return false;
  66217. }
  66218. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66219. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66220. this._initializeBlurRTTAndPostProcesses();
  66221. }
  66222. }
  66223. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66224. return false;
  66225. }
  66226. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66227. return false;
  66228. }
  66229. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66230. return false;
  66231. }
  66232. return true;
  66233. };
  66234. /**
  66235. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66236. * @param defines Defines of the material we want to update
  66237. * @param lightIndex Index of the light in the enabled light list of the material
  66238. */
  66239. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66240. var scene = this._scene;
  66241. var light = this._light;
  66242. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66243. return;
  66244. }
  66245. defines["SHADOW" + lightIndex] = true;
  66246. if (this.useContactHardeningShadow) {
  66247. defines["SHADOWPCSS" + lightIndex] = true;
  66248. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66249. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66250. }
  66251. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66252. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66253. }
  66254. // else default to high.
  66255. }
  66256. if (this.usePercentageCloserFiltering) {
  66257. defines["SHADOWPCF" + lightIndex] = true;
  66258. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66259. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66260. }
  66261. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66262. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66263. }
  66264. // else default to high.
  66265. }
  66266. else if (this.usePoissonSampling) {
  66267. defines["SHADOWPOISSON" + lightIndex] = true;
  66268. }
  66269. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66270. defines["SHADOWESM" + lightIndex] = true;
  66271. }
  66272. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66273. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66274. }
  66275. if (light.needCube()) {
  66276. defines["SHADOWCUBE" + lightIndex] = true;
  66277. }
  66278. };
  66279. /**
  66280. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66281. * defined in the generator but impacting the effect).
  66282. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66283. * @param effect The effect we are binfing the information for
  66284. */
  66285. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66286. var light = this._light;
  66287. var scene = this._scene;
  66288. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66289. return;
  66290. }
  66291. var camera = scene.activeCamera;
  66292. if (!camera) {
  66293. return;
  66294. }
  66295. var shadowMap = this.getShadowMap();
  66296. if (!shadowMap) {
  66297. return;
  66298. }
  66299. if (!light.needCube()) {
  66300. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66301. }
  66302. // Only PCF uses depth stencil texture.
  66303. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66304. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66305. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66306. }
  66307. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66308. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66309. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66310. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66311. }
  66312. else {
  66313. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66314. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66315. }
  66316. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66317. };
  66318. /**
  66319. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66320. * (eq to shadow prjection matrix * light transform matrix)
  66321. * @returns The transform matrix used to create the shadow map
  66322. */
  66323. ShadowGenerator.prototype.getTransformMatrix = function () {
  66324. var scene = this._scene;
  66325. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66326. return this._transformMatrix;
  66327. }
  66328. this._currentRenderID = scene.getRenderId();
  66329. this._currentFaceIndexCache = this._currentFaceIndex;
  66330. var lightPosition = this._light.position;
  66331. if (this._light.computeTransformedInformation()) {
  66332. lightPosition = this._light.transformedPosition;
  66333. }
  66334. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66335. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66336. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66337. }
  66338. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66339. this._cachedPosition.copyFrom(lightPosition);
  66340. this._cachedDirection.copyFrom(this._lightDirection);
  66341. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66342. var shadowMap = this.getShadowMap();
  66343. if (shadowMap) {
  66344. var renderList = shadowMap.renderList;
  66345. if (renderList) {
  66346. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66347. }
  66348. }
  66349. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66350. }
  66351. return this._transformMatrix;
  66352. };
  66353. /**
  66354. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66355. * Cube and 2D textures for instance.
  66356. */
  66357. ShadowGenerator.prototype.recreateShadowMap = function () {
  66358. var shadowMap = this._shadowMap;
  66359. if (!shadowMap) {
  66360. return;
  66361. }
  66362. // Track render list.
  66363. var renderList = shadowMap.renderList;
  66364. // Clean up existing data.
  66365. this._disposeRTTandPostProcesses();
  66366. // Reinitializes.
  66367. this._initializeGenerator();
  66368. // Reaffect the filter to ensure a correct fallback if necessary.
  66369. this.filter = this.filter;
  66370. // Reaffect the filter.
  66371. this._applyFilterValues();
  66372. // Reaffect Render List.
  66373. this._shadowMap.renderList = renderList;
  66374. };
  66375. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66376. if (this._shadowMap2) {
  66377. this._shadowMap2.dispose();
  66378. this._shadowMap2 = null;
  66379. }
  66380. if (this._boxBlurPostprocess) {
  66381. this._boxBlurPostprocess.dispose();
  66382. this._boxBlurPostprocess = null;
  66383. }
  66384. if (this._kernelBlurXPostprocess) {
  66385. this._kernelBlurXPostprocess.dispose();
  66386. this._kernelBlurXPostprocess = null;
  66387. }
  66388. if (this._kernelBlurYPostprocess) {
  66389. this._kernelBlurYPostprocess.dispose();
  66390. this._kernelBlurYPostprocess = null;
  66391. }
  66392. this._blurPostProcesses = [];
  66393. };
  66394. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66395. if (this._shadowMap) {
  66396. this._shadowMap.dispose();
  66397. this._shadowMap = null;
  66398. }
  66399. this._disposeBlurPostProcesses();
  66400. };
  66401. /**
  66402. * Disposes the ShadowGenerator.
  66403. * Returns nothing.
  66404. */
  66405. ShadowGenerator.prototype.dispose = function () {
  66406. this._disposeRTTandPostProcesses();
  66407. if (this._light) {
  66408. this._light._shadowGenerator = null;
  66409. this._light._markMeshesAsLightDirty();
  66410. }
  66411. };
  66412. /**
  66413. * Serializes the shadow generator setup to a json object.
  66414. * @returns The serialized JSON object
  66415. */
  66416. ShadowGenerator.prototype.serialize = function () {
  66417. var serializationObject = {};
  66418. var shadowMap = this.getShadowMap();
  66419. if (!shadowMap) {
  66420. return serializationObject;
  66421. }
  66422. serializationObject.lightId = this._light.id;
  66423. serializationObject.mapSize = shadowMap.getRenderSize();
  66424. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66425. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66426. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66427. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66428. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66429. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66430. serializationObject.depthScale = this.depthScale;
  66431. serializationObject.darkness = this.getDarkness();
  66432. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66433. serializationObject.blurKernel = this.blurKernel;
  66434. serializationObject.blurScale = this.blurScale;
  66435. serializationObject.useKernelBlur = this.useKernelBlur;
  66436. serializationObject.transparencyShadow = this._transparencyShadow;
  66437. serializationObject.bias = this.bias;
  66438. serializationObject.normalBias = this.normalBias;
  66439. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66440. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66441. serializationObject.filteringQuality = this.filteringQuality;
  66442. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66443. serializationObject.renderList = [];
  66444. if (shadowMap.renderList) {
  66445. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66446. var mesh = shadowMap.renderList[meshIndex];
  66447. serializationObject.renderList.push(mesh.id);
  66448. }
  66449. }
  66450. return serializationObject;
  66451. };
  66452. /**
  66453. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66454. * @param parsedShadowGenerator The JSON object to parse
  66455. * @param scene The scene to create the shadow map for
  66456. * @returns The parsed shadow generator
  66457. */
  66458. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66459. //casting to point light, as light is missing the position attr and typescript complains.
  66460. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66461. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66462. var shadowMap = shadowGenerator.getShadowMap();
  66463. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66464. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66465. meshes.forEach(function (mesh) {
  66466. if (!shadowMap) {
  66467. return;
  66468. }
  66469. if (!shadowMap.renderList) {
  66470. shadowMap.renderList = [];
  66471. }
  66472. shadowMap.renderList.push(mesh);
  66473. });
  66474. }
  66475. if (parsedShadowGenerator.usePoissonSampling) {
  66476. shadowGenerator.usePoissonSampling = true;
  66477. }
  66478. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66479. shadowGenerator.useExponentialShadowMap = true;
  66480. }
  66481. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66482. shadowGenerator.useBlurExponentialShadowMap = true;
  66483. }
  66484. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  66485. shadowGenerator.useCloseExponentialShadowMap = true;
  66486. }
  66487. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66488. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66489. }
  66490. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66491. shadowGenerator.usePercentageCloserFiltering = true;
  66492. }
  66493. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66494. shadowGenerator.useContactHardeningShadow = true;
  66495. }
  66496. if (parsedShadowGenerator.filteringQuality) {
  66497. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66498. }
  66499. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66500. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66501. }
  66502. // Backward compat
  66503. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66504. shadowGenerator.useExponentialShadowMap = true;
  66505. }
  66506. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  66507. shadowGenerator.useBlurExponentialShadowMap = true;
  66508. }
  66509. if (parsedShadowGenerator.depthScale) {
  66510. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  66511. }
  66512. if (parsedShadowGenerator.blurScale) {
  66513. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  66514. }
  66515. if (parsedShadowGenerator.blurBoxOffset) {
  66516. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  66517. }
  66518. if (parsedShadowGenerator.useKernelBlur) {
  66519. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  66520. }
  66521. if (parsedShadowGenerator.blurKernel) {
  66522. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  66523. }
  66524. if (parsedShadowGenerator.bias !== undefined) {
  66525. shadowGenerator.bias = parsedShadowGenerator.bias;
  66526. }
  66527. if (parsedShadowGenerator.normalBias !== undefined) {
  66528. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  66529. }
  66530. if (parsedShadowGenerator.darkness) {
  66531. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  66532. }
  66533. if (parsedShadowGenerator.transparencyShadow) {
  66534. shadowGenerator.setTransparencyShadow(true);
  66535. }
  66536. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  66537. return shadowGenerator;
  66538. };
  66539. /**
  66540. * Shadow generator mode None: no filtering applied.
  66541. */
  66542. ShadowGenerator.FILTER_NONE = 0;
  66543. /**
  66544. * Shadow generator mode ESM: Exponential Shadow Mapping.
  66545. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66546. */
  66547. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  66548. /**
  66549. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  66550. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  66551. */
  66552. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  66553. /**
  66554. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  66555. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66556. */
  66557. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  66558. /**
  66559. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  66560. * edge artifacts on steep falloff.
  66561. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66562. */
  66563. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  66564. /**
  66565. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  66566. * edge artifacts on steep falloff.
  66567. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66568. */
  66569. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66570. /**
  66571. * Shadow generator mode PCF: Percentage Closer Filtering
  66572. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66573. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66574. */
  66575. ShadowGenerator.FILTER_PCF = 6;
  66576. /**
  66577. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66578. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66579. * Contact Hardening
  66580. */
  66581. ShadowGenerator.FILTER_PCSS = 7;
  66582. /**
  66583. * Reserved for PCF and PCSS
  66584. * Highest Quality.
  66585. *
  66586. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66587. *
  66588. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66589. */
  66590. ShadowGenerator.QUALITY_HIGH = 0;
  66591. /**
  66592. * Reserved for PCF and PCSS
  66593. * Good tradeoff for quality/perf cross devices
  66594. *
  66595. * Execute PCF on a 3*3 kernel.
  66596. *
  66597. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66598. */
  66599. ShadowGenerator.QUALITY_MEDIUM = 1;
  66600. /**
  66601. * Reserved for PCF and PCSS
  66602. * The lowest quality but the fastest.
  66603. *
  66604. * Execute PCF on a 1*1 kernel.
  66605. *
  66606. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66607. */
  66608. ShadowGenerator.QUALITY_LOW = 2;
  66609. return ShadowGenerator;
  66610. }());
  66611. BABYLON.ShadowGenerator = ShadowGenerator;
  66612. })(BABYLON || (BABYLON = {}));
  66613. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66614. var BABYLON;
  66615. (function (BABYLON) {
  66616. var DefaultLoadingScreen = /** @class */ (function () {
  66617. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66618. if (_loadingText === void 0) { _loadingText = ""; }
  66619. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66620. var _this = this;
  66621. this._renderingCanvas = _renderingCanvas;
  66622. this._loadingText = _loadingText;
  66623. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  66624. // Resize
  66625. this._resizeLoadingUI = function () {
  66626. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  66627. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  66628. if (!_this._loadingDiv) {
  66629. return;
  66630. }
  66631. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  66632. _this._loadingDiv.style.left = canvasRect.left + "px";
  66633. _this._loadingDiv.style.top = canvasRect.top + "px";
  66634. _this._loadingDiv.style.width = canvasRect.width + "px";
  66635. _this._loadingDiv.style.height = canvasRect.height + "px";
  66636. };
  66637. }
  66638. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  66639. if (this._loadingDiv) {
  66640. // Do not add a loading screen if there is already one
  66641. return;
  66642. }
  66643. this._loadingDiv = document.createElement("div");
  66644. this._loadingDiv.id = "babylonjsLoadingDiv";
  66645. this._loadingDiv.style.opacity = "0";
  66646. this._loadingDiv.style.transition = "opacity 1.5s ease";
  66647. this._loadingDiv.style.pointerEvents = "none";
  66648. // Loading text
  66649. this._loadingTextDiv = document.createElement("div");
  66650. this._loadingTextDiv.style.position = "absolute";
  66651. this._loadingTextDiv.style.left = "0";
  66652. this._loadingTextDiv.style.top = "50%";
  66653. this._loadingTextDiv.style.marginTop = "80px";
  66654. this._loadingTextDiv.style.width = "100%";
  66655. this._loadingTextDiv.style.height = "20px";
  66656. this._loadingTextDiv.style.fontFamily = "Arial";
  66657. this._loadingTextDiv.style.fontSize = "14px";
  66658. this._loadingTextDiv.style.color = "white";
  66659. this._loadingTextDiv.style.textAlign = "center";
  66660. this._loadingTextDiv.innerHTML = "Loading";
  66661. this._loadingDiv.appendChild(this._loadingTextDiv);
  66662. //set the predefined text
  66663. this._loadingTextDiv.innerHTML = this._loadingText;
  66664. // Generating keyframes
  66665. var style = document.createElement('style');
  66666. style.type = 'text/css';
  66667. 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 }";
  66668. style.innerHTML = keyFrames;
  66669. document.getElementsByTagName('head')[0].appendChild(style);
  66670. // Loading img
  66671. var imgBack = new Image();
  66672. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAYq0lEQVR4Xu2dCZRcVZnHScAJUZSwjSOIbAJmEAZwQCCMoAInYRGIg8AwegQx7AFzUBBmzAFlE4EAwxz2GRk2w7AnAURZBiEOZgyEQDAQAjmEJqTpNd3V1V3Vmd+/6utKV7/1vnpVXd2p/zn3vOV+27vfu/fd/W3QQAPrBZqbm7fJZrN79vf3T+/r67uf4wO9vb37WXQDIwWtra0Tenp6voQTv5XP56/BkfcR3iLk1g6B7hEeI+zP5V+ZiAbqBZ2dnZ8lV+6Gg87CobfhpOc4byf0FjwYE9DneBkWcXrM2tmzNzTxDdQKJPyETCazI46YgiMuI9zJuXJltuChFIHsP/PSfIfTjU19A2mira1tcxy3ey6XO5vEnkV4kes11XBmENDVj97XOT2O03FmWgMuoNLzGRJva8IUnPkzjjcT/kLoKCZzfQB7XiX8M2G8md7AUJgzJ+Z6e88gZ1xGuj3HsY17PcVkrG9gp7CUF/F8PUvxqdZDrFq1ahNVfKjwTCYxZuDE2wjKlc2WViMePM+HPNsFPOdf22OPblD5OZQHvphnV65cjTMzxaQY3eA5V9OO/hmnm1lSjE7woFsQbiXki4++foHnXkW4mLC1JUl947333tsMY3emqfB9jtPJlXN5U0+bOXPmWCPxgOccSy4+AfqPio+9/oFnbyatbqVE28GSZfjQ1NT0KQzaHMcdyPfyaNoE12HcvdxT29K3Fkv8A2vWrPmcifAFZNtD91yRY+SBZ+9UsMtEgD+jTpeenp6JXI6xpKkuUDqRcA6Kr0Wpens+InQTnIpV6Fdi+BQT64ulS5eOIzefD62na7CeoGcnLCM8ykt5OWlzcPv772/BS/w3nP+K+xU11+DvQe5dcrQlTfWAwbNMb8XA8AyGX80xtLlA6TAJuteMbVhhia1v5VMcr+LWMeoZ4xiYw7q6urbhHbgG+paCkIRQehHu4pO3O5fVydEomF5Ulx548JfVD2wqfKE2I3R3ob/f2GoC1DWhdz7HG3i5j2pvb9+Z24m6HvVZQtYsZFWcowlzePEP4jJdR/OQhxTVpAs9NMXxmZxuZKo8IG4s+v8R2tUFphSBTBWzH+OAFwn/gS3TuN55xYoVqfc6dXd3fwHZ1xFaTX0iyGbwjJqXXAammxP00EXx6UMGEx7ram7+vKnzBZ/87Xiwp40tEdDTgYwlHG/CmadSjO7L+XiialOZAej7POFG2VK0Khngl6Pn8/LL0YEtlFh4n8oDAqvaAYH8tzH2iNDm1IIFn8Ax50G7xtgCAU07CfAG4RHOz+vLZL7e0dGxlYlKHaj8BHo25xgrsfV5wrYH4KmouxV+ZZDnCUdwmXxMGgFvFUVWD+jQuOot6rI0tb4gcfaG9v+MrcAn+wj38gL8C7cObmlp2ZRjOkWYD6ypuAf6zjFHLSJ0c/6YQ813DM/yZXgehreiVgP8cvSfsOeExYsXuzs6n8v9j8mqBRZQmdjXVPuira1NHSpn8UDf4Xu0vd2uCtDzacJOlDDf5ng94X8JTWarB8R1EK7ju7udiYgEz/v3pLFKm4oHUHhh3iZdfshpaEYpA4pvKLLXBujLYKRq71XLhUHg27z12rW9B6L/QhLrWWxRH7nzeDK8awi/5HRTEx0K6MZQ694LHk0DqrgfADkreIYz1q5c+UlTEQzesIuMryrggYQWjNL3RGO7p2tuFMeqjaOidgzyCz1yJMTJ6L6d66WEVCcHIO/dQkI75Chs2g97Hoc3jRz9Lge1ED5l4r0gckqRPB0gTw34t1B+h3IqxZkmrn2SULUa7ezZszdE5xfR9130Xsm5ilrnHrmkQOcKvrkncxqrIiY6wlewbw7BOUfDo/b84zzvj9C7J7eCS0NrUiRKCPjUE7ScMBdlF/B2HqBi0ERXBcuXL99YnQz9fX2ah3Up4UnsWGEmDRuUhoTn+Z5PfvbZZ2N/fuCZRJgnfhNVBu73EZoIKt7l0L2UBsYeDZg016nb5EUCWuXQewinUtTuyq2aTStF14a8SD+VDQVj6hDYxjuXf4Hjl83sSMCmTp8j4FtoMuRQ5dAZcii3kk/0s2bBhxIcBxjxUlib1hWInEDO/6qKV+y4geO5HAMntEE/pq+nZyo0ywsG1SmwL4Orf+0yqGCfmvR73LAn9lAeBjQTEhkA+1h49a08iRflcq4H5iuXFU9cz4lqihC/LXS/NZa6Bc+pz5gql5ub6VXD2tZWTSPeyS7XgeLhXrMnEhj6MSHSwaIhFGZH8oA/JzzFeexvJbRN2HW03moT6cEChx6w4QY2rurn85JWrxsiCy0FwjcIqos8w7GZNPulkawDEbFHlaBtjzODEDrVztuKXMmADPWA3RaljyJeNdKq98ilAez8iJdyGqfO31V4NoV/EvyaCqR54V2EshE5Lqcb+TrkstkTLD4WKB4PNNZQ8P05HAelMXNSPWChC8JsYvwthJo0jSoF6fIqjjqe08Aat+LIkd+AVjn09zxbZFqK3tjXAUbXUaWDjTUSyN4J45YZX2Igo4cEOVfFson2ALIxSjR0jog5YNgpfNHM90BxIjDyWIB8Z2NfB01HISJ20wPaw4w1FlavXq1v8aPGXhFw9JNRFTDItifU/RwwpfmKxYsDK180kU4x0lhAXvOSJUs+bezlIDL2N4xi4GpjK4MGCuzUA+SPxzn3m4iKgKyV2DCV08DeMWg0B+zHHOt2DpjS3Mz1BfFOM25C5ZH4LxldJBB0g7GVARkaXgv8VsKqZtIMPpN9RUnJgRzU5Wfp22vifcG3+2vQvmdsdQXsX2pm+oKX+GYjjQXkPWqsXshpRhcJ0RpbGShSHiSuheP37ZYHsGusVHOrU1lMxkO9od4eE+8LlSzQqfetpnPAooBN/2Um+gISp89MkF8K4G3RrMJYoOhbYGxlQEGhSOGogfoLwipExGtUZVVBYIVAluaAaUpuWA+YujlPF22Ra/iBLYEOsV6tV4w0FiitfmLsXiBMU0NiAVrfsp77Zd8MHPgbDoHtva6uLs1jiv1piAKy5tCG+4KJ9wVO/p6RDzvy+b5rzSwP9Okh/WKPERiCWzfk4K8bUSTiOljAyCdx5DZG4gE8W5Dov+NYUfsV/j50fUC4dmXIQDh0qQ6PVgJsOcLM8oA410Ggvo6Ojr81di+g2TKuQOiyJOKWxlpCJpM5zUjKAL3awTsamQfEbYhjtDGKa5tPsyn/wAuiURftlBO56h6aunEwCMxxvV1d+2Fr7Jce2vAu5LUtLeoGi/19gtbToCaR97BoD6BvUs+WkXqgbw6OuhC6wH5l4rRGaCFOvYnjYbyxnpcsCvDVhYOxo6+zszNwSNHVTtJEmSiwzlMAQmNPwIPW42Dds2hfEK/5WJo0Fth+5VNxFHSlkoTzFRh/N3wnq0OGWxXtdoO8enFwaI4jsyidYgNZTxhrMEjEJ4w+En65ESWRXZ7Q4K/COqDAPlhka87WedB8KawmngTIHREOJs5pMiRp+p/GGgxL1FiA9hxjK6G1tVVdhJGAV15+cPXq1f7dahVC20Wg4miCp0uTe3Xh4Hwu93rY1B7SR/t7xQbP5R1FGgpy8IlKe+MJhZ9Aa7u5jPm+pGLX2BMDOZ+hDXgQiXIJ5xoXHZg96anEEFcvOTi0SMUXS4w0FijSTzTWYEA3hkTSEtDI2qw6RoytDLA6jctCvzKqJ8oPFOO7kAhnYe9cZGiWiZ/N9ezguWaSL4h3TUfvKJIfoN0I4sjigYSdZyxlcDVMgEczEY41ER6oZFBOh2Yqegf2zYoziFC3DuZZrjSTPLDtMlxaNPmPP/54W2OPxksrVozP5fLPGr8vEOpbxJCr3jQSJyDvGRNRhv7iHh8vE5LMpKznHBz4zSTOaXwe+mXGGh9tbWvVQf+iyfCAON/ZlTj4v43ECfB94Le4CuMrWVpTtw7O9fZOM5M8oD7xVSOLBdLuNWN1g7bgJUF8+4qpBjf7Te9M6hD4tBDc0289Wh2MHbuaSR7gsHOMLBaQ9W/G6o5MJrNDPu9dcYdQ33Yc95I6OFV5hnp2cGCliDingX5KU+9MShd0dmqta/k8J4zwnV2JsuuNxAnI83VwNpO52kiSoC4djA255cuXBzYPycGzjTQWkPdNY00OfRcQVLafRnd39ySLLsG1i20AyPZ3cDb7AyNJgnp1cOhUHUhcFiL045v9jTUa8Gjlm29fsQQhb3DzJLUEhC+oiK7EISPOwapoEh+7JQJti5YfGXs0YNC62ouC1h9lsrlToClsjc/RM7uSe0kd3EmlzTO/Kqk8Q106mM/Yw2aOB9jnOg6sWTHxJ9FraSJMy6nGz7RbZUDYmN7e3BnQ5Gisez7u3J9c0JwA6Pb0aCFvNObgwKk6NoU59uJwaJ8y1viAT4vCtEFXYO8SFQGtCZpllyXQtNqL+4lmZ/BN/5qJKQFZozEHe9JtAGSaw4wsFnie4JmUQcjleh8yZq0Fnmq3y0D02IzPMgnonYqYIfA4pC+TcXrgIahLB+PEb5s5HrjaR0b7kbHGB0pK7TDO1/T39x1lUZGAPlUH0xTbz+KSoC4dDDx2DQCHzTCaWOB5zjbW+KCSpW0IS0BIJmy6zWCk7WDuxZ4r5oO6dHB7e/sBZo4H2OfUsYOv9jHW+ECJdkAtA/c6MpmMd+XaEKj7km9M4F5TEfBzSKovDLKG1cHobw+b6EDa3WOksYBPAhevBUJMxl8GJTRhFyMLBKSJFn5ls9nvmogS0DfaHOzb3h8AcUuNNBLQNiWa0gRv4MwMMyBwCqxAfCIH82JdYSJKQN+ocjA5NHD2I/e1aj/23iPyhbG6A+bAgXsZoUEII/UAkkQORu71JqIE7o22HBw4VaelpWU74mPPDc/39d1trO5Qb4vJ8QXxbwat06WofcTInMCzeToAtN4VXUn/l1AXDkan9tDSfmL6C81BZooHxDkN9CMveLFZFFAWWZtDwVta3G0sJcAbe3bmYEiniShBXabcL+wflQDD5mD0yKlvk0b/Tk33AG5F7idG+/ibRe54oEl1nLG6A+ZYe1jyAIuG/u2LB3MazxwAfL5vJFGJinxQUwcju6c/n3+FNPm5JhJyy2k/sQTp5nm+2HBJCGi1X1WpwzuBoQXAN+IcjDz8mdePKi/WhH1uxd7GcCjIVBcWpUYDfZ0VbclEJSr2akMBhVrdX6j+Jx3DpSh7vKB8CIiqKwcrcXGqdr05k3RKbU9ryTQVkUB3aHMrEshw7kGCXiv8xxG0h6Uzent6Fpn6MhA17A6GT/3yTxNO1coJbgWur3JFf1fXNuTes5AZe18xXobFHJKv04JZc3O7CtIcgGL9KW03u3QCfL4D4b292dhrpoYgsYOhEz4kaOuHqXKqiagYiN9QnUlyKgX84JUYsQFP9GKzMFRSe8XJb9upE9Dn62CK/KQT75wdTLz+NXgPNdrDuYzeUd0ByN4Wp07n+EdCRZuTY1/ymZQDwIjQye9pA32xdw6IiUgHc639mN8kzCLRjkxzQRzitUpkZ8LZBP1CILUd55EVvdgsCrzJl5i8mgCja+Zgjst4Pq3DUnMmtSWqyNIuQruRU3+CbO08n+pvBAZAjf1IU5kcGJc0YRMBfVV3MPd2RN4+YbvYukI/3sSpe+LUmbw0ryG/6ts1oSLeYrMw6C0xeaFAGc+Wq3hbfeRk582b55lrzf3UHJwWkD0Wp+6BQ3+BfXEXw6UCdHX4TVB0BoJi9Y1Cp59XbUWN8HW7lRjLli3zbINE+1hNiCRI1cGakIhT99ani/A6z1z1nDoUqNQfbO40kyqDfrCBwMg3E5rsCy+8sFlHR8dEnFzRTq/I8hQ9NFFOtGhXVOxgFeUqfknUK7Ctpjl1ANKJ/vmUkvrdwRZmWjpA4J9MTyja2toKY8TQa/ufxP/Whdd5c5cQJHIwfBsTvkKiaqd6/fRyOHKqavdL0H+V2sxmWvrQCAeKItfmQlNyDG/8SVwnetMHyxmA7lm0K2I7GFrlVBW/V6FPP9GqeU4V0Kt2+O2yhctUN6AJBEWD9ngMnessJxh5AfCoQe+8q+xQOYLuWbQrQh2MXP1XYh8S9DKC2sI1z6kCatW3/RCZ6Vj9fNPMqx2wQVNJQlcNEl/mGG5pv48bi7HxMVSOoHsW7QqPg5GlvnJtk6/B9+HMqYUfaXE6rampqWy4dVhgi8FfLprnBXEex+i/wCSkNiSNDSpUxxt7Ccj2nQQYAwUHc9yE3HEotuifDklnfFYMdGNC/lWCxotDf4PvB/jHZTs71c+f2n+ryqCPPcb5/pKdGrTvbH2MUjH4ByOLBDpON9YSFi5cuI1FOwFbbyTox5T6y+iwFL8CqvWvwVtolWgSv/N4sXbl5ZP3r8hRLT50d56KgYJDCYXVhYOhtqqReKDdZuGJtSQSOk8f67x581SspvH3lpoBe9Vefbg/lzveaXmnAf6tEDMNGRp3LnV3ch29o10lQIf+bOKZc+XnmMGARF2EK4vUwQiSw33n7ZlqDWwcaK9Ob29vd26vwj+OT8m3kKFxdd9tlILSJ1Wo8Y8RZT/YiKOY4le5P3SGZJAc7telg7FroL16Jc/n/a1cBBCxsSblwT8LOfofcCh4AQ4x1uoCXZtgVKnYDXLMUECnPSQD29VBcrhfVw7GHrVXb6WylGg0SvUZcrr+YPYuwWVfaE9ltmpA2Q6EQq2UY+yigzf2oqCH4v4MIysD94fdwdig9uqDnB4T5/d+gwHPGNVFcOopyJiPLOfmGTwa0Ek8qS8RKDKORLFWH95utwbDd94SRqqN/Cv4PDXbTFfXfUZWBvRUPJCRBJiIqfnnccy0Dz74wHkWoypY2D4ZGU8gK+kKjQKQ8RcTW1uQI2fmc7nH7LIMFEW+sw6xdyN4CgvNByNIDjp+ZyRVhzlV7dVLaZc7t1cRoW0w9of/No6ptbuRdZupqC3QPZY33HchMkbJiRPssgyaHkN82XaJXPtOJuN+JRuixQI6Cu1VXiZtJehcFGpeNPyXI6cqPWTIvsxU1R7o912akevre4OHfTHot3fEfRbD3y8+Qu0djO5Ce5UXNGl7dTt4z0RGqnOuhgLZgmcPk2FHrrd3jgwkAVQ58e1ioxjcHeMLPWQcq+5gZKm9+hJHjXo5z4xQBQsxxyDjEfir+nNq5GfQo/nYh6f9e4NUgGEFx3DEzvw1nPrOhSJ+kh6GUBUHw6//Kmls96dJ2qv6FxNF9z8g405kVLVXDfkaiFAd4JIkttYUGFpyDOf91Ch/YVEe8DA/gORpuywDfLNMjBOQt4qEupbTPTX4YeJig+/qrnoxkfMeIdH2UHGBfP0H6kFepElc1rY5lBQYXZbzuO7BWYH7b3V3d/+TX1FEG/JSExEJdOi7qsnrx3DuNM8Zdg2NqnN/BjK0EXlVhxORr56wP6Lv/DT+X1FzYLynaOWe2s1TjCQW4An9t6Jk4hBVdH6YpB9YNXoS+SRk/JaQZHd5J2CnesLuyGaze3KZ2hTemoNcpO+uB3pAQuzvC7SeJSfc0258Wo97aX9PT+TmMEMB73jsO0wJzXnVx4llL7pe5kWaFtSqGHHgu6rpPr5jsdx+hyI59G+hA4C25GDO1V69mbf/77h0+lZpzZX44B+Ye1X1cWKz92pKrYlcjtzc6gfN+ufhApd/ErcwTvuTRNI0m4c4Tg77u6gfbCHdTuQcrRFaRKiFU7Xl1O/RqX9RObevRxR43gmEBYUn9wEJIMeF/jk0yVKTta2tE0jg43kx1OatWifEYKDrHYKGDnfkMrU1xHUPaoh7k8i+030EvoV3c6i4aTCoc/9+9NVkFgh6BmZFaig08he3oxYkwBEkQGCzg7gfG6kzaDvuSyLfgIyqt1cF6SAspoS4iJf3c9xaf3JrGEgUzZcOGgvO4agzjTQUkI9V5z4851MuLhBvUUp1gR7tjXEHL+shXFZnduNIBomi6T73FVLLByQePu4N3CxMbVxyzfeQUTYZrdpA3yvoPVf/1jdTGggC6aXx0ieLSecFcWoj72vkhU4IcswU7gVORksb6FHnufbouJ4Xbv+gf1g0EADav9uSeO9YenpA3IfURFVZ0gqEms1rRg0qCzM4TuYy1T061jt0dXXpX0xJ96FMDXIqQXtJ3tSfze6OaY0KU1ogfTUgUJMK0lBIL06dS/F/LJeRe0k2kAAk7BgSWN2GVW/aCOjRuPCbBHVGBG6J3ECKIN3VlfjroguqA+RrMsFvCNqisf5mRox2qPlB4s8vuiMdIE/fVjVvLlRnhKlqYLig7QIpOiva40PAqR2E22neJFrN10AVgWMOIDgPuMOjmRFa+HVaR0fHliaugXoEOe80nBWrZg2dZkZoYffuaW5u1kCVkadmbT70AGdqJodWOhxHqP2eFg1UDvsLatnSFq41M+KKnp6eXbhsdB2OdGiCeX8+/2ecqgnmk/VXNYtqYLSAnNposzpjgw3+H/belpVa8J7TAAAAAElFTkSuQmCC";
  66673. imgBack.style.position = "absolute";
  66674. imgBack.style.left = "50%";
  66675. imgBack.style.top = "50%";
  66676. imgBack.style.marginLeft = "-60px";
  66677. imgBack.style.marginTop = "-60px";
  66678. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  66679. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  66680. imgBack.style.transformOrigin = "50% 50%";
  66681. imgBack.style.webkitTransformOrigin = "50% 50%";
  66682. this._loadingDiv.appendChild(imgBack);
  66683. this._resizeLoadingUI();
  66684. window.addEventListener("resize", this._resizeLoadingUI);
  66685. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66686. document.body.appendChild(this._loadingDiv);
  66687. this._loadingDiv.style.opacity = "1";
  66688. };
  66689. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  66690. var _this = this;
  66691. if (!this._loadingDiv) {
  66692. return;
  66693. }
  66694. var onTransitionEnd = function () {
  66695. if (!_this._loadingDiv) {
  66696. return;
  66697. }
  66698. document.body.removeChild(_this._loadingDiv);
  66699. window.removeEventListener("resize", _this._resizeLoadingUI);
  66700. _this._loadingDiv = null;
  66701. };
  66702. this._loadingDiv.style.opacity = "0";
  66703. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  66704. };
  66705. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  66706. set: function (text) {
  66707. this._loadingText = text;
  66708. if (this._loadingTextDiv) {
  66709. this._loadingTextDiv.innerHTML = this._loadingText;
  66710. }
  66711. },
  66712. enumerable: true,
  66713. configurable: true
  66714. });
  66715. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  66716. get: function () {
  66717. return this._loadingDivBackgroundColor;
  66718. },
  66719. set: function (color) {
  66720. this._loadingDivBackgroundColor = color;
  66721. if (!this._loadingDiv) {
  66722. return;
  66723. }
  66724. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66725. },
  66726. enumerable: true,
  66727. configurable: true
  66728. });
  66729. return DefaultLoadingScreen;
  66730. }());
  66731. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  66732. })(BABYLON || (BABYLON = {}));
  66733. //# sourceMappingURL=babylon.loadingScreen.js.map
  66734. var BABYLON;
  66735. (function (BABYLON) {
  66736. var SceneLoaderProgressEvent = /** @class */ (function () {
  66737. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  66738. this.lengthComputable = lengthComputable;
  66739. this.loaded = loaded;
  66740. this.total = total;
  66741. }
  66742. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  66743. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  66744. };
  66745. return SceneLoaderProgressEvent;
  66746. }());
  66747. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  66748. var SceneLoader = /** @class */ (function () {
  66749. function SceneLoader() {
  66750. }
  66751. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  66752. get: function () {
  66753. return 0;
  66754. },
  66755. enumerable: true,
  66756. configurable: true
  66757. });
  66758. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  66759. get: function () {
  66760. return 1;
  66761. },
  66762. enumerable: true,
  66763. configurable: true
  66764. });
  66765. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  66766. get: function () {
  66767. return 2;
  66768. },
  66769. enumerable: true,
  66770. configurable: true
  66771. });
  66772. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  66773. get: function () {
  66774. return 3;
  66775. },
  66776. enumerable: true,
  66777. configurable: true
  66778. });
  66779. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  66780. get: function () {
  66781. return SceneLoader._ForceFullSceneLoadingForIncremental;
  66782. },
  66783. set: function (value) {
  66784. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  66785. },
  66786. enumerable: true,
  66787. configurable: true
  66788. });
  66789. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  66790. get: function () {
  66791. return SceneLoader._ShowLoadingScreen;
  66792. },
  66793. set: function (value) {
  66794. SceneLoader._ShowLoadingScreen = value;
  66795. },
  66796. enumerable: true,
  66797. configurable: true
  66798. });
  66799. Object.defineProperty(SceneLoader, "loggingLevel", {
  66800. get: function () {
  66801. return SceneLoader._loggingLevel;
  66802. },
  66803. set: function (value) {
  66804. SceneLoader._loggingLevel = value;
  66805. },
  66806. enumerable: true,
  66807. configurable: true
  66808. });
  66809. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  66810. get: function () {
  66811. return SceneLoader._CleanBoneMatrixWeights;
  66812. },
  66813. set: function (value) {
  66814. SceneLoader._CleanBoneMatrixWeights = value;
  66815. },
  66816. enumerable: true,
  66817. configurable: true
  66818. });
  66819. SceneLoader._getDefaultPlugin = function () {
  66820. return SceneLoader._registeredPlugins[".babylon"];
  66821. };
  66822. SceneLoader._getPluginForExtension = function (extension) {
  66823. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  66824. if (registeredPlugin) {
  66825. return registeredPlugin;
  66826. }
  66827. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  66828. return SceneLoader._getDefaultPlugin();
  66829. };
  66830. SceneLoader._getPluginForDirectLoad = function (data) {
  66831. for (var extension in SceneLoader._registeredPlugins) {
  66832. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  66833. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  66834. return SceneLoader._registeredPlugins[extension];
  66835. }
  66836. }
  66837. return SceneLoader._getDefaultPlugin();
  66838. };
  66839. SceneLoader._getPluginForFilename = function (sceneFilename) {
  66840. if (sceneFilename.name) {
  66841. sceneFilename = sceneFilename.name;
  66842. }
  66843. var queryStringPosition = sceneFilename.indexOf("?");
  66844. if (queryStringPosition !== -1) {
  66845. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  66846. }
  66847. var dotPosition = sceneFilename.lastIndexOf(".");
  66848. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  66849. return SceneLoader._getPluginForExtension(extension);
  66850. };
  66851. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  66852. SceneLoader._getDirectLoad = function (sceneFilename) {
  66853. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  66854. return sceneFilename.substr(5);
  66855. }
  66856. return null;
  66857. };
  66858. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  66859. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  66860. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  66861. var plugin;
  66862. if (registeredPlugin.plugin.createPlugin) {
  66863. plugin = registeredPlugin.plugin.createPlugin();
  66864. }
  66865. else {
  66866. plugin = registeredPlugin.plugin;
  66867. }
  66868. var useArrayBuffer = registeredPlugin.isBinary;
  66869. var database;
  66870. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  66871. var dataCallback = function (data, responseURL) {
  66872. if (scene.isDisposed) {
  66873. onError("Scene has been disposed");
  66874. return;
  66875. }
  66876. scene.database = database;
  66877. onSuccess(plugin, data, responseURL);
  66878. };
  66879. var request = null;
  66880. var pluginDisposed = false;
  66881. var onDisposeObservable = plugin.onDisposeObservable;
  66882. if (onDisposeObservable) {
  66883. onDisposeObservable.add(function () {
  66884. pluginDisposed = true;
  66885. if (request) {
  66886. request.abort();
  66887. request = null;
  66888. }
  66889. onDispose();
  66890. });
  66891. }
  66892. var manifestChecked = function () {
  66893. if (pluginDisposed) {
  66894. return;
  66895. }
  66896. var url = rootUrl + sceneFilename;
  66897. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  66898. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  66899. } : undefined, database, useArrayBuffer, function (request, exception) {
  66900. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  66901. });
  66902. };
  66903. if (directLoad) {
  66904. dataCallback(directLoad);
  66905. return plugin;
  66906. }
  66907. if (rootUrl.indexOf("file:") === -1) {
  66908. var engine = scene.getEngine();
  66909. var canUseOfflineSupport = engine.enableOfflineSupport;
  66910. if (canUseOfflineSupport) {
  66911. // Also check for exceptions
  66912. var exceptionFound = false;
  66913. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  66914. var regex = _a[_i];
  66915. if (regex.test(rootUrl + sceneFilename)) {
  66916. exceptionFound = true;
  66917. break;
  66918. }
  66919. }
  66920. canUseOfflineSupport = !exceptionFound;
  66921. }
  66922. if (canUseOfflineSupport) {
  66923. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  66924. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  66925. }
  66926. else {
  66927. manifestChecked();
  66928. }
  66929. }
  66930. // Loading file from disk via input file or drag'n'drop
  66931. else {
  66932. var fileOrString = sceneFilename;
  66933. if (fileOrString.name) { // File
  66934. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  66935. }
  66936. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  66937. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  66938. }
  66939. else {
  66940. onError("Unable to find file named " + sceneFilename);
  66941. }
  66942. }
  66943. return plugin;
  66944. };
  66945. // Public functions
  66946. SceneLoader.GetPluginForExtension = function (extension) {
  66947. return SceneLoader._getPluginForExtension(extension).plugin;
  66948. };
  66949. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  66950. return !!SceneLoader._registeredPlugins[extension];
  66951. };
  66952. SceneLoader.RegisterPlugin = function (plugin) {
  66953. if (typeof plugin.extensions === "string") {
  66954. var extension = plugin.extensions;
  66955. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66956. plugin: plugin,
  66957. isBinary: false
  66958. };
  66959. }
  66960. else {
  66961. var extensions = plugin.extensions;
  66962. Object.keys(extensions).forEach(function (extension) {
  66963. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66964. plugin: plugin,
  66965. isBinary: extensions[extension].isBinary
  66966. };
  66967. });
  66968. }
  66969. };
  66970. /**
  66971. * Import meshes into a scene
  66972. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66973. * @param rootUrl a string that defines the root url for scene and resources
  66974. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66975. * @param scene the instance of BABYLON.Scene to append to
  66976. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  66977. * @param onProgress a callback with a progress event for each file being loaded
  66978. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66979. * @param pluginExtension the extension used to determine the plugin
  66980. * @returns The loaded plugin
  66981. */
  66982. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66983. if (onSuccess === void 0) { onSuccess = null; }
  66984. if (onProgress === void 0) { onProgress = null; }
  66985. if (onError === void 0) { onError = null; }
  66986. if (pluginExtension === void 0) { pluginExtension = null; }
  66987. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66988. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66989. return null;
  66990. }
  66991. var loadingToken = {};
  66992. scene._addPendingData(loadingToken);
  66993. var disposeHandler = function () {
  66994. scene._removePendingData(loadingToken);
  66995. };
  66996. var errorHandler = function (message, exception) {
  66997. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  66998. if (onError) {
  66999. onError(scene, errorMessage, exception);
  67000. }
  67001. else {
  67002. BABYLON.Tools.Error(errorMessage);
  67003. // should the exception be thrown?
  67004. }
  67005. disposeHandler();
  67006. };
  67007. var progressHandler = onProgress ? function (event) {
  67008. try {
  67009. onProgress(event);
  67010. }
  67011. catch (e) {
  67012. errorHandler("Error in onProgress callback", e);
  67013. }
  67014. } : undefined;
  67015. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67016. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67017. if (onSuccess) {
  67018. try {
  67019. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67020. }
  67021. catch (e) {
  67022. errorHandler("Error in onSuccess callback", e);
  67023. }
  67024. }
  67025. scene._removePendingData(loadingToken);
  67026. };
  67027. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67028. if (plugin.rewriteRootURL) {
  67029. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67030. }
  67031. if (sceneFilename === "") {
  67032. if (sceneFilename === "") {
  67033. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67034. }
  67035. }
  67036. if (plugin.importMesh) {
  67037. var syncedPlugin = plugin;
  67038. var meshes = new Array();
  67039. var particleSystems = new Array();
  67040. var skeletons = new Array();
  67041. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67042. return;
  67043. }
  67044. scene.loadingPluginName = plugin.name;
  67045. successHandler(meshes, particleSystems, skeletons, []);
  67046. }
  67047. else {
  67048. var asyncedPlugin = plugin;
  67049. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67050. scene.loadingPluginName = plugin.name;
  67051. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67052. }).catch(function (error) {
  67053. errorHandler(error.message, error);
  67054. });
  67055. }
  67056. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67057. };
  67058. /**
  67059. * Import meshes into a scene
  67060. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67061. * @param rootUrl a string that defines the root url for scene and resources
  67062. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67063. * @param scene the instance of BABYLON.Scene to append to
  67064. * @param onProgress a callback with a progress event for each file being loaded
  67065. * @param pluginExtension the extension used to determine the plugin
  67066. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67067. */
  67068. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67069. if (onProgress === void 0) { onProgress = null; }
  67070. if (pluginExtension === void 0) { pluginExtension = null; }
  67071. return new Promise(function (resolve, reject) {
  67072. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67073. resolve({
  67074. meshes: meshes,
  67075. particleSystems: particleSystems,
  67076. skeletons: skeletons,
  67077. animationGroups: animationGroups
  67078. });
  67079. }, onProgress, function (scene, message, exception) {
  67080. reject(exception || new Error(message));
  67081. });
  67082. });
  67083. };
  67084. /**
  67085. * Load a scene
  67086. * @param rootUrl a string that defines the root url for scene and resources
  67087. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67088. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67089. * @param onSuccess a callback with the scene when import succeeds
  67090. * @param onProgress a callback with a progress event for each file being loaded
  67091. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67092. * @param pluginExtension the extension used to determine the plugin
  67093. * @returns The loaded plugin
  67094. */
  67095. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67096. if (onSuccess === void 0) { onSuccess = null; }
  67097. if (onProgress === void 0) { onProgress = null; }
  67098. if (onError === void 0) { onError = null; }
  67099. if (pluginExtension === void 0) { pluginExtension = null; }
  67100. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67101. };
  67102. /**
  67103. * Load a scene
  67104. * @param rootUrl a string that defines the root url for scene and resources
  67105. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67106. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67107. * @param onProgress a callback with a progress event for each file being loaded
  67108. * @param pluginExtension the extension used to determine the plugin
  67109. * @returns The loaded scene
  67110. */
  67111. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67112. if (onProgress === void 0) { onProgress = null; }
  67113. if (pluginExtension === void 0) { pluginExtension = null; }
  67114. return new Promise(function (resolve, reject) {
  67115. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67116. resolve(scene);
  67117. }, onProgress, function (scene, message, exception) {
  67118. reject(exception || new Error(message));
  67119. }, pluginExtension);
  67120. });
  67121. };
  67122. /**
  67123. * Append a scene
  67124. * @param rootUrl a string that defines the root url for scene and resources
  67125. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67126. * @param scene is the instance of BABYLON.Scene to append to
  67127. * @param onSuccess a callback with the scene when import succeeds
  67128. * @param onProgress a callback with a progress event for each file being loaded
  67129. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67130. * @param pluginExtension the extension used to determine the plugin
  67131. * @returns The loaded plugin
  67132. */
  67133. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67134. if (onSuccess === void 0) { onSuccess = null; }
  67135. if (onProgress === void 0) { onProgress = null; }
  67136. if (onError === void 0) { onError = null; }
  67137. if (pluginExtension === void 0) { pluginExtension = null; }
  67138. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67139. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67140. return null;
  67141. }
  67142. if (SceneLoader.ShowLoadingScreen) {
  67143. scene.getEngine().displayLoadingUI();
  67144. }
  67145. var loadingToken = {};
  67146. scene._addPendingData(loadingToken);
  67147. var disposeHandler = function () {
  67148. scene._removePendingData(loadingToken);
  67149. scene.getEngine().hideLoadingUI();
  67150. };
  67151. var errorHandler = function (message, exception) {
  67152. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67153. if (onError) {
  67154. onError(scene, errorMessage, exception);
  67155. }
  67156. else {
  67157. BABYLON.Tools.Error(errorMessage);
  67158. // should the exception be thrown?
  67159. }
  67160. disposeHandler();
  67161. };
  67162. var progressHandler = onProgress ? function (event) {
  67163. try {
  67164. onProgress(event);
  67165. }
  67166. catch (e) {
  67167. errorHandler("Error in onProgress callback", e);
  67168. }
  67169. } : undefined;
  67170. var successHandler = function () {
  67171. if (onSuccess) {
  67172. try {
  67173. onSuccess(scene);
  67174. }
  67175. catch (e) {
  67176. errorHandler("Error in onSuccess callback", e);
  67177. }
  67178. }
  67179. scene._removePendingData(loadingToken);
  67180. };
  67181. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67182. if (sceneFilename === "") {
  67183. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67184. }
  67185. if (plugin.load) {
  67186. var syncedPlugin = plugin;
  67187. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67188. return;
  67189. }
  67190. scene.loadingPluginName = plugin.name;
  67191. successHandler();
  67192. }
  67193. else {
  67194. var asyncedPlugin = plugin;
  67195. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67196. scene.loadingPluginName = plugin.name;
  67197. successHandler();
  67198. }).catch(function (error) {
  67199. errorHandler(error.message, error);
  67200. });
  67201. }
  67202. if (SceneLoader.ShowLoadingScreen) {
  67203. scene.executeWhenReady(function () {
  67204. scene.getEngine().hideLoadingUI();
  67205. });
  67206. }
  67207. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67208. };
  67209. /**
  67210. * Append a scene
  67211. * @param rootUrl a string that defines the root url for scene and resources
  67212. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67213. * @param scene is the instance of BABYLON.Scene to append to
  67214. * @param onProgress a callback with a progress event for each file being loaded
  67215. * @param pluginExtension the extension used to determine the plugin
  67216. * @returns The given scene
  67217. */
  67218. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67219. if (onProgress === void 0) { onProgress = null; }
  67220. if (pluginExtension === void 0) { pluginExtension = null; }
  67221. return new Promise(function (resolve, reject) {
  67222. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67223. resolve(scene);
  67224. }, onProgress, function (scene, message, exception) {
  67225. reject(exception || new Error(message));
  67226. }, pluginExtension);
  67227. });
  67228. };
  67229. /**
  67230. * Load a scene into an asset container
  67231. * @param rootUrl a string that defines the root url for scene and resources
  67232. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67233. * @param scene is the instance of BABYLON.Scene to append to
  67234. * @param onSuccess a callback with the scene when import succeeds
  67235. * @param onProgress a callback with a progress event for each file being loaded
  67236. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67237. * @param pluginExtension the extension used to determine the plugin
  67238. * @returns The loaded plugin
  67239. */
  67240. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67241. if (onSuccess === void 0) { onSuccess = null; }
  67242. if (onProgress === void 0) { onProgress = null; }
  67243. if (onError === void 0) { onError = null; }
  67244. if (pluginExtension === void 0) { pluginExtension = null; }
  67245. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67246. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67247. return null;
  67248. }
  67249. var loadingToken = {};
  67250. scene._addPendingData(loadingToken);
  67251. var disposeHandler = function () {
  67252. scene._removePendingData(loadingToken);
  67253. };
  67254. var errorHandler = function (message, exception) {
  67255. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67256. if (onError) {
  67257. onError(scene, errorMessage, exception);
  67258. }
  67259. else {
  67260. BABYLON.Tools.Error(errorMessage);
  67261. // should the exception be thrown?
  67262. }
  67263. disposeHandler();
  67264. };
  67265. var progressHandler = onProgress ? function (event) {
  67266. try {
  67267. onProgress(event);
  67268. }
  67269. catch (e) {
  67270. errorHandler("Error in onProgress callback", e);
  67271. }
  67272. } : undefined;
  67273. var successHandler = function (assets) {
  67274. if (onSuccess) {
  67275. try {
  67276. onSuccess(assets);
  67277. }
  67278. catch (e) {
  67279. errorHandler("Error in onSuccess callback", e);
  67280. }
  67281. }
  67282. scene._removePendingData(loadingToken);
  67283. };
  67284. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67285. if (plugin.loadAssetContainer) {
  67286. var syncedPlugin = plugin;
  67287. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67288. if (!assetContainer) {
  67289. return;
  67290. }
  67291. scene.loadingPluginName = plugin.name;
  67292. successHandler(assetContainer);
  67293. }
  67294. else if (plugin.loadAssetContainerAsync) {
  67295. var asyncedPlugin = plugin;
  67296. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67297. scene.loadingPluginName = plugin.name;
  67298. successHandler(assetContainer);
  67299. }).catch(function (error) {
  67300. errorHandler(error.message, error);
  67301. });
  67302. }
  67303. else {
  67304. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67305. }
  67306. if (SceneLoader.ShowLoadingScreen) {
  67307. scene.executeWhenReady(function () {
  67308. scene.getEngine().hideLoadingUI();
  67309. });
  67310. }
  67311. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67312. };
  67313. /**
  67314. * Load a scene into an asset container
  67315. * @param rootUrl a string that defines the root url for scene and resources
  67316. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67317. * @param scene is the instance of BABYLON.Scene to append to
  67318. * @param onProgress a callback with a progress event for each file being loaded
  67319. * @param pluginExtension the extension used to determine the plugin
  67320. * @returns The loaded asset container
  67321. */
  67322. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67323. if (onProgress === void 0) { onProgress = null; }
  67324. if (pluginExtension === void 0) { pluginExtension = null; }
  67325. return new Promise(function (resolve, reject) {
  67326. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67327. resolve(assetContainer);
  67328. }, onProgress, function (scene, message, exception) {
  67329. reject(exception || new Error(message));
  67330. }, pluginExtension);
  67331. });
  67332. };
  67333. // Flags
  67334. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67335. SceneLoader._ShowLoadingScreen = true;
  67336. SceneLoader._CleanBoneMatrixWeights = false;
  67337. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67338. // Members
  67339. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67340. SceneLoader._registeredPlugins = {};
  67341. return SceneLoader;
  67342. }());
  67343. BABYLON.SceneLoader = SceneLoader;
  67344. ;
  67345. })(BABYLON || (BABYLON = {}));
  67346. //# sourceMappingURL=babylon.sceneLoader.js.map
  67347. var BABYLON;
  67348. (function (BABYLON) {
  67349. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67350. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67351. var parsedMaterial = parsedData.materials[index];
  67352. if (parsedMaterial.id === id) {
  67353. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67354. }
  67355. }
  67356. return null;
  67357. };
  67358. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67359. for (var i in names) {
  67360. if (mesh.name === names[i]) {
  67361. hierarchyIds.push(mesh.id);
  67362. return true;
  67363. }
  67364. }
  67365. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67366. hierarchyIds.push(mesh.id);
  67367. return true;
  67368. }
  67369. return false;
  67370. };
  67371. var logOperation = function (operation, producer) {
  67372. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67373. };
  67374. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67375. if (addToScene === void 0) { addToScene = false; }
  67376. var container = new BABYLON.AssetContainer(scene);
  67377. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67378. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67379. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67380. // and avoid problems with multiple concurrent .babylon loads.
  67381. var log = "importScene has failed JSON parse";
  67382. try {
  67383. var parsedData = JSON.parse(data);
  67384. log = "";
  67385. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67386. var index;
  67387. var cache;
  67388. // Lights
  67389. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67390. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67391. var parsedLight = parsedData.lights[index];
  67392. var light = BABYLON.Light.Parse(parsedLight, scene);
  67393. if (light) {
  67394. container.lights.push(light);
  67395. log += (index === 0 ? "\n\tLights:" : "");
  67396. log += "\n\t\t" + light.toString(fullDetails);
  67397. }
  67398. }
  67399. }
  67400. // Animations
  67401. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67402. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67403. var parsedAnimation = parsedData.animations[index];
  67404. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67405. scene.animations.push(animation);
  67406. container.animations.push(animation);
  67407. log += (index === 0 ? "\n\tAnimations:" : "");
  67408. log += "\n\t\t" + animation.toString(fullDetails);
  67409. }
  67410. }
  67411. // Materials
  67412. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67413. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67414. var parsedMaterial = parsedData.materials[index];
  67415. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67416. container.materials.push(mat);
  67417. log += (index === 0 ? "\n\tMaterials:" : "");
  67418. log += "\n\t\t" + mat.toString(fullDetails);
  67419. }
  67420. }
  67421. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67422. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67423. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67424. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67425. container.multiMaterials.push(mmat);
  67426. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67427. log += "\n\t\t" + mmat.toString(fullDetails);
  67428. }
  67429. }
  67430. // Morph targets
  67431. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67432. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67433. var managerData = _a[_i];
  67434. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67435. }
  67436. }
  67437. // Skeletons
  67438. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67439. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67440. var parsedSkeleton = parsedData.skeletons[index];
  67441. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67442. container.skeletons.push(skeleton);
  67443. log += (index === 0 ? "\n\tSkeletons:" : "");
  67444. log += "\n\t\t" + skeleton.toString(fullDetails);
  67445. }
  67446. }
  67447. // Geometries
  67448. var geometries = parsedData.geometries;
  67449. if (geometries !== undefined && geometries !== null) {
  67450. var addedGeometry = new Array();
  67451. // Boxes
  67452. var boxes = geometries.boxes;
  67453. if (boxes !== undefined && boxes !== null) {
  67454. for (index = 0, cache = boxes.length; index < cache; index++) {
  67455. var parsedBox = boxes[index];
  67456. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67457. }
  67458. }
  67459. // Spheres
  67460. var spheres = geometries.spheres;
  67461. if (spheres !== undefined && spheres !== null) {
  67462. for (index = 0, cache = spheres.length; index < cache; index++) {
  67463. var parsedSphere = spheres[index];
  67464. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67465. }
  67466. }
  67467. // Cylinders
  67468. var cylinders = geometries.cylinders;
  67469. if (cylinders !== undefined && cylinders !== null) {
  67470. for (index = 0, cache = cylinders.length; index < cache; index++) {
  67471. var parsedCylinder = cylinders[index];
  67472. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  67473. }
  67474. }
  67475. // Toruses
  67476. var toruses = geometries.toruses;
  67477. if (toruses !== undefined && toruses !== null) {
  67478. for (index = 0, cache = toruses.length; index < cache; index++) {
  67479. var parsedTorus = toruses[index];
  67480. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  67481. }
  67482. }
  67483. // Grounds
  67484. var grounds = geometries.grounds;
  67485. if (grounds !== undefined && grounds !== null) {
  67486. for (index = 0, cache = grounds.length; index < cache; index++) {
  67487. var parsedGround = grounds[index];
  67488. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  67489. }
  67490. }
  67491. // Planes
  67492. var planes = geometries.planes;
  67493. if (planes !== undefined && planes !== null) {
  67494. for (index = 0, cache = planes.length; index < cache; index++) {
  67495. var parsedPlane = planes[index];
  67496. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  67497. }
  67498. }
  67499. // TorusKnots
  67500. var torusKnots = geometries.torusKnots;
  67501. if (torusKnots !== undefined && torusKnots !== null) {
  67502. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  67503. var parsedTorusKnot = torusKnots[index];
  67504. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  67505. }
  67506. }
  67507. // VertexData
  67508. var vertexData = geometries.vertexData;
  67509. if (vertexData !== undefined && vertexData !== null) {
  67510. for (index = 0, cache = vertexData.length; index < cache; index++) {
  67511. var parsedVertexData = vertexData[index];
  67512. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  67513. }
  67514. }
  67515. addedGeometry.forEach(function (g) {
  67516. if (g) {
  67517. container.geometries.push(g);
  67518. }
  67519. });
  67520. }
  67521. // Transform nodes
  67522. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  67523. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  67524. var parsedTransformNode = parsedData.transformNodes[index];
  67525. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  67526. container.transformNodes.push(node);
  67527. }
  67528. }
  67529. // Meshes
  67530. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67531. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67532. var parsedMesh = parsedData.meshes[index];
  67533. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67534. container.meshes.push(mesh);
  67535. log += (index === 0 ? "\n\tMeshes:" : "");
  67536. log += "\n\t\t" + mesh.toString(fullDetails);
  67537. }
  67538. }
  67539. // Cameras
  67540. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  67541. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  67542. var parsedCamera = parsedData.cameras[index];
  67543. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  67544. container.cameras.push(camera);
  67545. log += (index === 0 ? "\n\tCameras:" : "");
  67546. log += "\n\t\t" + camera.toString(fullDetails);
  67547. }
  67548. }
  67549. // Browsing all the graph to connect the dots
  67550. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  67551. var camera = scene.cameras[index];
  67552. if (camera._waitingParentId) {
  67553. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  67554. camera._waitingParentId = null;
  67555. }
  67556. }
  67557. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67558. var light_1 = scene.lights[index];
  67559. if (light_1 && light_1._waitingParentId) {
  67560. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  67561. light_1._waitingParentId = null;
  67562. }
  67563. }
  67564. // Sounds
  67565. // TODO: add sound
  67566. var loadedSounds = [];
  67567. var loadedSound;
  67568. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67569. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67570. var parsedSound = parsedData.sounds[index];
  67571. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67572. if (!parsedSound.url)
  67573. parsedSound.url = parsedSound.name;
  67574. if (!loadedSounds[parsedSound.url]) {
  67575. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67576. loadedSounds[parsedSound.url] = loadedSound;
  67577. container.sounds.push(loadedSound);
  67578. }
  67579. else {
  67580. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67581. }
  67582. }
  67583. else {
  67584. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67585. }
  67586. }
  67587. }
  67588. loadedSounds = [];
  67589. // Connect parents & children and parse actions
  67590. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  67591. var transformNode = scene.transformNodes[index];
  67592. if (transformNode._waitingParentId) {
  67593. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  67594. transformNode._waitingParentId = null;
  67595. }
  67596. }
  67597. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67598. var mesh = scene.meshes[index];
  67599. if (mesh._waitingParentId) {
  67600. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  67601. mesh._waitingParentId = null;
  67602. }
  67603. if (mesh._waitingActions) {
  67604. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  67605. mesh._waitingActions = null;
  67606. }
  67607. }
  67608. // freeze world matrix application
  67609. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67610. var currentMesh = scene.meshes[index];
  67611. if (currentMesh._waitingFreezeWorldMatrix) {
  67612. currentMesh.freezeWorldMatrix();
  67613. currentMesh._waitingFreezeWorldMatrix = null;
  67614. }
  67615. else {
  67616. currentMesh.computeWorldMatrix(true);
  67617. }
  67618. }
  67619. // Particles Systems
  67620. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67621. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67622. var parsedParticleSystem = parsedData.particleSystems[index];
  67623. if (parsedParticleSystem.activeParticleCount) {
  67624. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67625. container.particleSystems.push(ps);
  67626. }
  67627. else {
  67628. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67629. container.particleSystems.push(ps);
  67630. }
  67631. }
  67632. }
  67633. // Lens flares
  67634. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  67635. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  67636. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  67637. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  67638. container.lensFlareSystems.push(lf);
  67639. }
  67640. }
  67641. // Shadows
  67642. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  67643. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  67644. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  67645. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  67646. container.shadowGenerators.push(sg);
  67647. }
  67648. }
  67649. // Lights exclusions / inclusions
  67650. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67651. var light_2 = scene.lights[index];
  67652. // Excluded check
  67653. if (light_2._excludedMeshesIds.length > 0) {
  67654. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  67655. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  67656. if (excludedMesh) {
  67657. light_2.excludedMeshes.push(excludedMesh);
  67658. }
  67659. }
  67660. light_2._excludedMeshesIds = [];
  67661. }
  67662. // Included check
  67663. if (light_2._includedOnlyMeshesIds.length > 0) {
  67664. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  67665. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  67666. if (includedOnlyMesh) {
  67667. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  67668. }
  67669. }
  67670. light_2._includedOnlyMeshesIds = [];
  67671. }
  67672. }
  67673. // Effect layers
  67674. if (parsedData.effectLayers) {
  67675. for (index = 0; index < parsedData.effectLayers.length; index++) {
  67676. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  67677. container.effectLayers.push(effectLayer);
  67678. }
  67679. }
  67680. // Actions (scene)
  67681. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  67682. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  67683. }
  67684. if (!addToScene) {
  67685. container.removeAllFromScene();
  67686. }
  67687. }
  67688. catch (err) {
  67689. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  67690. if (onError) {
  67691. onError(msg, err);
  67692. }
  67693. else {
  67694. BABYLON.Tools.Log(msg);
  67695. throw err;
  67696. }
  67697. }
  67698. finally {
  67699. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67700. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67701. }
  67702. }
  67703. return container;
  67704. };
  67705. BABYLON.SceneLoader.RegisterPlugin({
  67706. name: "babylon.js",
  67707. extensions: ".babylon",
  67708. canDirectLoad: function (data) {
  67709. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  67710. return true;
  67711. }
  67712. return false;
  67713. },
  67714. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  67715. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67716. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67717. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67718. // and avoid problems with multiple concurrent .babylon loads.
  67719. var log = "importMesh has failed JSON parse";
  67720. try {
  67721. var parsedData = JSON.parse(data);
  67722. log = "";
  67723. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67724. if (!meshesNames) {
  67725. meshesNames = null;
  67726. }
  67727. else if (!Array.isArray(meshesNames)) {
  67728. meshesNames = [meshesNames];
  67729. }
  67730. var hierarchyIds = new Array();
  67731. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67732. var loadedSkeletonsIds = [];
  67733. var loadedMaterialsIds = [];
  67734. var index;
  67735. var cache;
  67736. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67737. var parsedMesh = parsedData.meshes[index];
  67738. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  67739. if (meshesNames !== null) {
  67740. // Remove found mesh name from list.
  67741. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  67742. }
  67743. //Geometry?
  67744. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  67745. //does the file contain geometries?
  67746. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  67747. //find the correct geometry and add it to the scene
  67748. var found = false;
  67749. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  67750. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  67751. return;
  67752. }
  67753. else {
  67754. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  67755. if (parsedGeometryData.id === parsedMesh.geometryId) {
  67756. switch (geometryType) {
  67757. case "boxes":
  67758. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  67759. break;
  67760. case "spheres":
  67761. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  67762. break;
  67763. case "cylinders":
  67764. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  67765. break;
  67766. case "toruses":
  67767. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  67768. break;
  67769. case "grounds":
  67770. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  67771. break;
  67772. case "planes":
  67773. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  67774. break;
  67775. case "torusKnots":
  67776. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  67777. break;
  67778. case "vertexData":
  67779. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  67780. break;
  67781. }
  67782. found = true;
  67783. }
  67784. });
  67785. }
  67786. });
  67787. if (found === false) {
  67788. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  67789. }
  67790. }
  67791. }
  67792. // Material ?
  67793. if (parsedMesh.materialId) {
  67794. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  67795. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67796. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  67797. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  67798. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  67799. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  67800. var subMatId = parsedMultiMaterial.materials[matIndex];
  67801. loadedMaterialsIds.push(subMatId);
  67802. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  67803. if (mat) {
  67804. log += "\n\tMaterial " + mat.toString(fullDetails);
  67805. }
  67806. }
  67807. loadedMaterialsIds.push(parsedMultiMaterial.id);
  67808. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67809. if (mmat) {
  67810. materialFound = true;
  67811. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  67812. }
  67813. break;
  67814. }
  67815. }
  67816. }
  67817. if (materialFound === false) {
  67818. loadedMaterialsIds.push(parsedMesh.materialId);
  67819. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  67820. if (!mat) {
  67821. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  67822. }
  67823. else {
  67824. log += "\n\tMaterial " + mat.toString(fullDetails);
  67825. }
  67826. }
  67827. }
  67828. // Skeleton ?
  67829. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67830. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  67831. if (skeletonAlreadyLoaded === false) {
  67832. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  67833. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  67834. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  67835. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67836. skeletons.push(skeleton);
  67837. loadedSkeletonsIds.push(parsedSkeleton.id);
  67838. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  67839. }
  67840. }
  67841. }
  67842. }
  67843. // Morph targets ?
  67844. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67845. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67846. var managerData = _a[_i];
  67847. BABYLON.MorphTargetManager.Parse(managerData, scene);
  67848. }
  67849. }
  67850. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67851. meshes.push(mesh);
  67852. log += "\n\tMesh " + mesh.toString(fullDetails);
  67853. }
  67854. }
  67855. // Connecting parents
  67856. var currentMesh;
  67857. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67858. currentMesh = scene.meshes[index];
  67859. if (currentMesh._waitingParentId) {
  67860. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  67861. currentMesh._waitingParentId = null;
  67862. }
  67863. }
  67864. // freeze and compute world matrix application
  67865. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67866. currentMesh = scene.meshes[index];
  67867. if (currentMesh._waitingFreezeWorldMatrix) {
  67868. currentMesh.freezeWorldMatrix();
  67869. currentMesh._waitingFreezeWorldMatrix = null;
  67870. }
  67871. else {
  67872. currentMesh.computeWorldMatrix(true);
  67873. }
  67874. }
  67875. }
  67876. // Particles
  67877. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67878. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67879. var parsedParticleSystem = parsedData.particleSystems[index];
  67880. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  67881. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  67882. }
  67883. }
  67884. }
  67885. return true;
  67886. }
  67887. catch (err) {
  67888. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  67889. if (onError) {
  67890. onError(msg, err);
  67891. }
  67892. else {
  67893. BABYLON.Tools.Log(msg);
  67894. throw err;
  67895. }
  67896. }
  67897. finally {
  67898. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67899. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67900. }
  67901. }
  67902. return false;
  67903. },
  67904. load: function (scene, data, rootUrl, onError) {
  67905. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67906. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67907. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67908. // and avoid problems with multiple concurrent .babylon loads.
  67909. var log = "importScene has failed JSON parse";
  67910. try {
  67911. var parsedData = JSON.parse(data);
  67912. log = "";
  67913. // Scene
  67914. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  67915. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  67916. }
  67917. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  67918. scene.autoClear = parsedData.autoClear;
  67919. }
  67920. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  67921. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  67922. }
  67923. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  67924. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  67925. }
  67926. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  67927. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  67928. }
  67929. // Fog
  67930. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  67931. scene.fogMode = parsedData.fogMode;
  67932. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  67933. scene.fogStart = parsedData.fogStart;
  67934. scene.fogEnd = parsedData.fogEnd;
  67935. scene.fogDensity = parsedData.fogDensity;
  67936. log += "\tFog mode for scene: ";
  67937. switch (scene.fogMode) {
  67938. // getters not compiling, so using hardcoded
  67939. case 1:
  67940. log += "exp\n";
  67941. break;
  67942. case 2:
  67943. log += "exp2\n";
  67944. break;
  67945. case 3:
  67946. log += "linear\n";
  67947. break;
  67948. }
  67949. }
  67950. //Physics
  67951. if (parsedData.physicsEnabled) {
  67952. var physicsPlugin;
  67953. if (parsedData.physicsEngine === "cannon") {
  67954. physicsPlugin = new BABYLON.CannonJSPlugin();
  67955. }
  67956. else if (parsedData.physicsEngine === "oimo") {
  67957. physicsPlugin = new BABYLON.OimoJSPlugin();
  67958. }
  67959. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  67960. //else - default engine, which is currently oimo
  67961. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  67962. scene.enablePhysics(physicsGravity, physicsPlugin);
  67963. }
  67964. // Metadata
  67965. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  67966. scene.metadata = parsedData.metadata;
  67967. }
  67968. //collisions, if defined. otherwise, default is true
  67969. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  67970. scene.collisionsEnabled = parsedData.collisionsEnabled;
  67971. }
  67972. scene.workerCollisions = !!parsedData.workerCollisions;
  67973. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  67974. if (!container) {
  67975. return false;
  67976. }
  67977. if (parsedData.autoAnimate) {
  67978. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  67979. }
  67980. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  67981. scene.setActiveCameraByID(parsedData.activeCameraID);
  67982. }
  67983. // Environment texture
  67984. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  67985. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  67986. if (parsedData.createDefaultSkybox === true) {
  67987. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  67988. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  67989. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  67990. }
  67991. }
  67992. // Finish
  67993. return true;
  67994. }
  67995. catch (err) {
  67996. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  67997. if (onError) {
  67998. onError(msg, err);
  67999. }
  68000. else {
  68001. BABYLON.Tools.Log(msg);
  68002. throw err;
  68003. }
  68004. }
  68005. finally {
  68006. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68007. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68008. }
  68009. }
  68010. return false;
  68011. },
  68012. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68013. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68014. return container;
  68015. }
  68016. });
  68017. })(BABYLON || (BABYLON = {}));
  68018. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68019. var BABYLON;
  68020. (function (BABYLON) {
  68021. var FilesInput = /** @class */ (function () {
  68022. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68023. this.onProcessFileCallback = function () { return true; };
  68024. this._engine = engine;
  68025. this._currentScene = scene;
  68026. this._sceneLoadedCallback = sceneLoadedCallback;
  68027. this._progressCallback = progressCallback;
  68028. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68029. this._textureLoadingCallback = textureLoadingCallback;
  68030. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68031. this._onReloadCallback = onReloadCallback;
  68032. this._errorCallback = errorCallback;
  68033. }
  68034. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68035. var _this = this;
  68036. if (elementToMonitor) {
  68037. this._elementToMonitor = elementToMonitor;
  68038. this._dragEnterHandler = function (e) { _this.drag(e); };
  68039. this._dragOverHandler = function (e) { _this.drag(e); };
  68040. this._dropHandler = function (e) { _this.drop(e); };
  68041. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68042. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68043. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68044. }
  68045. };
  68046. FilesInput.prototype.dispose = function () {
  68047. if (!this._elementToMonitor) {
  68048. return;
  68049. }
  68050. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68051. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68052. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68053. };
  68054. FilesInput.prototype.renderFunction = function () {
  68055. if (this._additionalRenderLoopLogicCallback) {
  68056. this._additionalRenderLoopLogicCallback();
  68057. }
  68058. if (this._currentScene) {
  68059. if (this._textureLoadingCallback) {
  68060. var remaining = this._currentScene.getWaitingItemsCount();
  68061. if (remaining > 0) {
  68062. this._textureLoadingCallback(remaining);
  68063. }
  68064. }
  68065. this._currentScene.render();
  68066. }
  68067. };
  68068. FilesInput.prototype.drag = function (e) {
  68069. e.stopPropagation();
  68070. e.preventDefault();
  68071. };
  68072. FilesInput.prototype.drop = function (eventDrop) {
  68073. eventDrop.stopPropagation();
  68074. eventDrop.preventDefault();
  68075. this.loadFiles(eventDrop);
  68076. };
  68077. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68078. var _this = this;
  68079. var reader = folder.createReader();
  68080. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68081. reader.readEntries(function (entries) {
  68082. remaining.count += entries.length;
  68083. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68084. var entry = entries_1[_i];
  68085. if (entry.isFile) {
  68086. entry.file(function (file) {
  68087. file.correctName = relativePath + file.name;
  68088. files.push(file);
  68089. if (--remaining.count === 0) {
  68090. callback();
  68091. }
  68092. });
  68093. }
  68094. else if (entry.isDirectory) {
  68095. _this._traverseFolder(entry, files, remaining, callback);
  68096. }
  68097. }
  68098. if (--remaining.count) {
  68099. callback();
  68100. }
  68101. });
  68102. };
  68103. FilesInput.prototype._processFiles = function (files) {
  68104. for (var i = 0; i < files.length; i++) {
  68105. var name = files[i].correctName.toLowerCase();
  68106. var extension = name.split('.').pop();
  68107. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68108. continue;
  68109. }
  68110. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68111. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68112. this._sceneFileToLoad = files[i];
  68113. }
  68114. else {
  68115. FilesInput.FilesToLoad[name] = files[i];
  68116. }
  68117. }
  68118. };
  68119. FilesInput.prototype.loadFiles = function (event) {
  68120. var _this = this;
  68121. if (this._startingProcessingFilesCallback)
  68122. this._startingProcessingFilesCallback();
  68123. // Handling data transfer via drag'n'drop
  68124. if (event && event.dataTransfer && event.dataTransfer.files) {
  68125. this._filesToLoad = event.dataTransfer.files;
  68126. }
  68127. // Handling files from input files
  68128. if (event && event.target && event.target.files) {
  68129. this._filesToLoad = event.target.files;
  68130. }
  68131. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68132. var files_1 = new Array();
  68133. var folders = [];
  68134. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68135. for (var i = 0; i < this._filesToLoad.length; i++) {
  68136. var fileToLoad = this._filesToLoad[i];
  68137. var name_1 = fileToLoad.name.toLowerCase();
  68138. var entry = void 0;
  68139. fileToLoad.correctName = name_1;
  68140. if (items) {
  68141. var item = items[i];
  68142. if (item.getAsEntry) {
  68143. entry = item.getAsEntry();
  68144. }
  68145. else if (item.webkitGetAsEntry) {
  68146. entry = item.webkitGetAsEntry();
  68147. }
  68148. }
  68149. if (!entry) {
  68150. files_1.push(fileToLoad);
  68151. }
  68152. else {
  68153. if (entry.isDirectory) {
  68154. folders.push(entry);
  68155. }
  68156. else {
  68157. files_1.push(fileToLoad);
  68158. }
  68159. }
  68160. }
  68161. if (folders.length === 0) {
  68162. this._processFiles(files_1);
  68163. this._processReload();
  68164. }
  68165. else {
  68166. var remaining = { count: folders.length };
  68167. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68168. var folder = folders_1[_i];
  68169. this._traverseFolder(folder, files_1, remaining, function () {
  68170. _this._processFiles(files_1);
  68171. if (remaining.count === 0) {
  68172. _this._processReload();
  68173. }
  68174. });
  68175. }
  68176. }
  68177. }
  68178. };
  68179. FilesInput.prototype._processReload = function () {
  68180. if (this._onReloadCallback) {
  68181. this._onReloadCallback(this._sceneFileToLoad);
  68182. }
  68183. else {
  68184. this.reload();
  68185. }
  68186. };
  68187. FilesInput.prototype.reload = function () {
  68188. var _this = this;
  68189. // If a scene file has been provided
  68190. if (this._sceneFileToLoad) {
  68191. if (this._currentScene) {
  68192. if (BABYLON.Tools.errorsCount > 0) {
  68193. BABYLON.Tools.ClearLogCache();
  68194. }
  68195. this._engine.stopRenderLoop();
  68196. this._currentScene.dispose();
  68197. }
  68198. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68199. if (_this._progressCallback) {
  68200. _this._progressCallback(progress);
  68201. }
  68202. }).then(function (scene) {
  68203. _this._currentScene = scene;
  68204. if (_this._sceneLoadedCallback) {
  68205. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68206. }
  68207. // Wait for textures and shaders to be ready
  68208. _this._currentScene.executeWhenReady(function () {
  68209. _this._engine.runRenderLoop(function () {
  68210. _this.renderFunction();
  68211. });
  68212. });
  68213. }).catch(function (error) {
  68214. if (_this._errorCallback) {
  68215. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68216. }
  68217. });
  68218. }
  68219. else {
  68220. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68221. }
  68222. };
  68223. FilesInput.FilesToLoad = {};
  68224. return FilesInput;
  68225. }());
  68226. BABYLON.FilesInput = FilesInput;
  68227. })(BABYLON || (BABYLON = {}));
  68228. //# sourceMappingURL=babylon.filesInput.js.map
  68229. var BABYLON;
  68230. (function (BABYLON) {
  68231. /**
  68232. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68233. * The underlying implementation relies on an associative array to ensure the best performances.
  68234. * The value can be anything including 'null' but except 'undefined'
  68235. */
  68236. var StringDictionary = /** @class */ (function () {
  68237. function StringDictionary() {
  68238. this._count = 0;
  68239. this._data = {};
  68240. }
  68241. /**
  68242. * This will clear this dictionary and copy the content from the 'source' one.
  68243. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68244. * @param source the dictionary to take the content from and copy to this dictionary
  68245. */
  68246. StringDictionary.prototype.copyFrom = function (source) {
  68247. var _this = this;
  68248. this.clear();
  68249. source.forEach(function (t, v) { return _this.add(t, v); });
  68250. };
  68251. /**
  68252. * Get a value based from its key
  68253. * @param key the given key to get the matching value from
  68254. * @return the value if found, otherwise undefined is returned
  68255. */
  68256. StringDictionary.prototype.get = function (key) {
  68257. var val = this._data[key];
  68258. if (val !== undefined) {
  68259. return val;
  68260. }
  68261. return undefined;
  68262. };
  68263. /**
  68264. * Get a value from its key or add it if it doesn't exist.
  68265. * This method will ensure you that a given key/data will be present in the dictionary.
  68266. * @param key the given key to get the matching value from
  68267. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68268. * The factory will only be invoked if there's no data for the given key.
  68269. * @return the value corresponding to the key.
  68270. */
  68271. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68272. var val = this.get(key);
  68273. if (val !== undefined) {
  68274. return val;
  68275. }
  68276. val = factory(key);
  68277. if (val) {
  68278. this.add(key, val);
  68279. }
  68280. return val;
  68281. };
  68282. /**
  68283. * Get a value from its key if present in the dictionary otherwise add it
  68284. * @param key the key to get the value from
  68285. * @param val if there's no such key/value pair in the dictionary add it with this value
  68286. * @return the value corresponding to the key
  68287. */
  68288. StringDictionary.prototype.getOrAdd = function (key, val) {
  68289. var curVal = this.get(key);
  68290. if (curVal !== undefined) {
  68291. return curVal;
  68292. }
  68293. this.add(key, val);
  68294. return val;
  68295. };
  68296. /**
  68297. * Check if there's a given key in the dictionary
  68298. * @param key the key to check for
  68299. * @return true if the key is present, false otherwise
  68300. */
  68301. StringDictionary.prototype.contains = function (key) {
  68302. return this._data[key] !== undefined;
  68303. };
  68304. /**
  68305. * Add a new key and its corresponding value
  68306. * @param key the key to add
  68307. * @param value the value corresponding to the key
  68308. * @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
  68309. */
  68310. StringDictionary.prototype.add = function (key, value) {
  68311. if (this._data[key] !== undefined) {
  68312. return false;
  68313. }
  68314. this._data[key] = value;
  68315. ++this._count;
  68316. return true;
  68317. };
  68318. StringDictionary.prototype.set = function (key, value) {
  68319. if (this._data[key] === undefined) {
  68320. return false;
  68321. }
  68322. this._data[key] = value;
  68323. return true;
  68324. };
  68325. /**
  68326. * Get the element of the given key and remove it from the dictionary
  68327. * @param key
  68328. */
  68329. StringDictionary.prototype.getAndRemove = function (key) {
  68330. var val = this.get(key);
  68331. if (val !== undefined) {
  68332. delete this._data[key];
  68333. --this._count;
  68334. return val;
  68335. }
  68336. return null;
  68337. };
  68338. /**
  68339. * Remove a key/value from the dictionary.
  68340. * @param key the key to remove
  68341. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68342. */
  68343. StringDictionary.prototype.remove = function (key) {
  68344. if (this.contains(key)) {
  68345. delete this._data[key];
  68346. --this._count;
  68347. return true;
  68348. }
  68349. return false;
  68350. };
  68351. /**
  68352. * Clear the whole content of the dictionary
  68353. */
  68354. StringDictionary.prototype.clear = function () {
  68355. this._data = {};
  68356. this._count = 0;
  68357. };
  68358. Object.defineProperty(StringDictionary.prototype, "count", {
  68359. get: function () {
  68360. return this._count;
  68361. },
  68362. enumerable: true,
  68363. configurable: true
  68364. });
  68365. /**
  68366. * Execute a callback on each key/val of the dictionary.
  68367. * Note that you can remove any element in this dictionary in the callback implementation
  68368. * @param callback the callback to execute on a given key/value pair
  68369. */
  68370. StringDictionary.prototype.forEach = function (callback) {
  68371. for (var cur in this._data) {
  68372. var val = this._data[cur];
  68373. callback(cur, val);
  68374. }
  68375. };
  68376. /**
  68377. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68378. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68379. * Note that you can remove any element in this dictionary in the callback implementation
  68380. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68381. */
  68382. StringDictionary.prototype.first = function (callback) {
  68383. for (var cur in this._data) {
  68384. var val = this._data[cur];
  68385. var res = callback(cur, val);
  68386. if (res) {
  68387. return res;
  68388. }
  68389. }
  68390. return null;
  68391. };
  68392. return StringDictionary;
  68393. }());
  68394. BABYLON.StringDictionary = StringDictionary;
  68395. })(BABYLON || (BABYLON = {}));
  68396. //# sourceMappingURL=babylon.stringDictionary.js.map
  68397. var BABYLON;
  68398. (function (BABYLON) {
  68399. var Tags = /** @class */ (function () {
  68400. function Tags() {
  68401. }
  68402. Tags.EnableFor = function (obj) {
  68403. obj._tags = obj._tags || {};
  68404. obj.hasTags = function () {
  68405. return Tags.HasTags(obj);
  68406. };
  68407. obj.addTags = function (tagsString) {
  68408. return Tags.AddTagsTo(obj, tagsString);
  68409. };
  68410. obj.removeTags = function (tagsString) {
  68411. return Tags.RemoveTagsFrom(obj, tagsString);
  68412. };
  68413. obj.matchesTagsQuery = function (tagsQuery) {
  68414. return Tags.MatchesQuery(obj, tagsQuery);
  68415. };
  68416. };
  68417. Tags.DisableFor = function (obj) {
  68418. delete obj._tags;
  68419. delete obj.hasTags;
  68420. delete obj.addTags;
  68421. delete obj.removeTags;
  68422. delete obj.matchesTagsQuery;
  68423. };
  68424. Tags.HasTags = function (obj) {
  68425. if (!obj._tags) {
  68426. return false;
  68427. }
  68428. return !BABYLON.Tools.IsEmpty(obj._tags);
  68429. };
  68430. Tags.GetTags = function (obj, asString) {
  68431. if (asString === void 0) { asString = true; }
  68432. if (!obj._tags) {
  68433. return null;
  68434. }
  68435. if (asString) {
  68436. var tagsArray = [];
  68437. for (var tag in obj._tags) {
  68438. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68439. tagsArray.push(tag);
  68440. }
  68441. }
  68442. return tagsArray.join(" ");
  68443. }
  68444. else {
  68445. return obj._tags;
  68446. }
  68447. };
  68448. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68449. // a tag cannot start with '||', '&&', and '!'
  68450. // it cannot contain whitespaces
  68451. Tags.AddTagsTo = function (obj, tagsString) {
  68452. if (!tagsString) {
  68453. return;
  68454. }
  68455. if (typeof tagsString !== "string") {
  68456. return;
  68457. }
  68458. var tags = tagsString.split(" ");
  68459. tags.forEach(function (tag, index, array) {
  68460. Tags._AddTagTo(obj, tag);
  68461. });
  68462. };
  68463. Tags._AddTagTo = function (obj, tag) {
  68464. tag = tag.trim();
  68465. if (tag === "" || tag === "true" || tag === "false") {
  68466. return;
  68467. }
  68468. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  68469. return;
  68470. }
  68471. Tags.EnableFor(obj);
  68472. obj._tags[tag] = true;
  68473. };
  68474. Tags.RemoveTagsFrom = function (obj, tagsString) {
  68475. if (!Tags.HasTags(obj)) {
  68476. return;
  68477. }
  68478. var tags = tagsString.split(" ");
  68479. for (var t in tags) {
  68480. Tags._RemoveTagFrom(obj, tags[t]);
  68481. }
  68482. };
  68483. Tags._RemoveTagFrom = function (obj, tag) {
  68484. delete obj._tags[tag];
  68485. };
  68486. Tags.MatchesQuery = function (obj, tagsQuery) {
  68487. if (tagsQuery === undefined) {
  68488. return true;
  68489. }
  68490. if (tagsQuery === "") {
  68491. return Tags.HasTags(obj);
  68492. }
  68493. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  68494. };
  68495. return Tags;
  68496. }());
  68497. BABYLON.Tags = Tags;
  68498. })(BABYLON || (BABYLON = {}));
  68499. //# sourceMappingURL=babylon.tags.js.map
  68500. var BABYLON;
  68501. (function (BABYLON) {
  68502. /**
  68503. * Class used to evalaute queries containing `and` and `or` operators
  68504. */
  68505. var AndOrNotEvaluator = /** @class */ (function () {
  68506. function AndOrNotEvaluator() {
  68507. }
  68508. /**
  68509. * Evaluate a query
  68510. * @param query defines the query to evaluate
  68511. * @param evaluateCallback defines the callback used to filter result
  68512. * @returns true if the query matches
  68513. */
  68514. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  68515. if (!query.match(/\([^\(\)]*\)/g)) {
  68516. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  68517. }
  68518. else {
  68519. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  68520. // remove parenthesis
  68521. r = r.slice(1, r.length - 1);
  68522. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  68523. });
  68524. }
  68525. if (query === "true") {
  68526. return true;
  68527. }
  68528. if (query === "false") {
  68529. return false;
  68530. }
  68531. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  68532. };
  68533. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  68534. evaluateCallback = evaluateCallback || (function (r) {
  68535. return r === "true" ? true : false;
  68536. });
  68537. var result;
  68538. var or = parenthesisContent.split("||");
  68539. for (var i in or) {
  68540. if (or.hasOwnProperty(i)) {
  68541. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  68542. var and = ori.split("&&");
  68543. if (and.length > 1) {
  68544. for (var j = 0; j < and.length; ++j) {
  68545. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  68546. if (andj !== "true" && andj !== "false") {
  68547. if (andj[0] === "!") {
  68548. result = !evaluateCallback(andj.substring(1));
  68549. }
  68550. else {
  68551. result = evaluateCallback(andj);
  68552. }
  68553. }
  68554. else {
  68555. result = andj === "true" ? true : false;
  68556. }
  68557. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  68558. ori = "false";
  68559. break;
  68560. }
  68561. }
  68562. }
  68563. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  68564. result = true;
  68565. break;
  68566. }
  68567. // result equals false (or undefined)
  68568. if (ori !== "true" && ori !== "false") {
  68569. if (ori[0] === "!") {
  68570. result = !evaluateCallback(ori.substring(1));
  68571. }
  68572. else {
  68573. result = evaluateCallback(ori);
  68574. }
  68575. }
  68576. else {
  68577. result = ori === "true" ? true : false;
  68578. }
  68579. }
  68580. }
  68581. // the whole parenthesis scope is replaced by 'true' or 'false'
  68582. return result ? "true" : "false";
  68583. };
  68584. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  68585. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  68586. // remove whitespaces
  68587. r = r.replace(/[\s]/g, function () { return ""; });
  68588. return r.length % 2 ? "!" : "";
  68589. });
  68590. booleanString = booleanString.trim();
  68591. if (booleanString === "!true") {
  68592. booleanString = "false";
  68593. }
  68594. else if (booleanString === "!false") {
  68595. booleanString = "true";
  68596. }
  68597. return booleanString;
  68598. };
  68599. return AndOrNotEvaluator;
  68600. }());
  68601. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  68602. })(BABYLON || (BABYLON = {}));
  68603. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  68604. var BABYLON;
  68605. (function (BABYLON) {
  68606. /**
  68607. * Class used to enable access to IndexedDB
  68608. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  68609. */
  68610. var Database = /** @class */ (function () {
  68611. /**
  68612. * Creates a new Database
  68613. * @param urlToScene defines the url to load the scene
  68614. * @param callbackManifestChecked defines the callback to use when manifest is checked
  68615. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  68616. */
  68617. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  68618. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  68619. var _this = this;
  68620. // Handling various flavors of prefixed version of IndexedDB
  68621. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  68622. this.callbackManifestChecked = callbackManifestChecked;
  68623. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  68624. this.db = null;
  68625. this._enableSceneOffline = false;
  68626. this._enableTexturesOffline = false;
  68627. this.manifestVersionFound = 0;
  68628. this.mustUpdateRessources = false;
  68629. this.hasReachedQuota = false;
  68630. if (!Database.IDBStorageEnabled) {
  68631. this.callbackManifestChecked(true);
  68632. }
  68633. else {
  68634. if (disableManifestCheck) {
  68635. this._enableSceneOffline = true;
  68636. this._enableTexturesOffline = true;
  68637. this.manifestVersionFound = 1;
  68638. BABYLON.Tools.SetImmediate(function () {
  68639. _this.callbackManifestChecked(true);
  68640. });
  68641. }
  68642. else {
  68643. this._checkManifestFile();
  68644. }
  68645. }
  68646. }
  68647. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  68648. /**
  68649. * Gets a boolean indicating if scene must be saved in the database
  68650. */
  68651. get: function () {
  68652. return this._enableSceneOffline;
  68653. },
  68654. enumerable: true,
  68655. configurable: true
  68656. });
  68657. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  68658. /**
  68659. * Gets a boolean indicating if textures must be saved in the database
  68660. */
  68661. get: function () {
  68662. return this._enableTexturesOffline;
  68663. },
  68664. enumerable: true,
  68665. configurable: true
  68666. });
  68667. Database.prototype._checkManifestFile = function () {
  68668. var _this = this;
  68669. var noManifestFile = function () {
  68670. _this._enableSceneOffline = false;
  68671. _this._enableTexturesOffline = false;
  68672. _this.callbackManifestChecked(false);
  68673. };
  68674. var timeStampUsed = false;
  68675. var manifestURL = this.currentSceneUrl + ".manifest";
  68676. var xhr = new XMLHttpRequest();
  68677. if (navigator.onLine) {
  68678. // Adding a timestamp to by-pass browsers' cache
  68679. timeStampUsed = true;
  68680. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  68681. }
  68682. xhr.open("GET", manifestURL, true);
  68683. xhr.addEventListener("load", function () {
  68684. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68685. try {
  68686. var manifestFile = JSON.parse(xhr.response);
  68687. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  68688. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  68689. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  68690. _this.manifestVersionFound = manifestFile.version;
  68691. }
  68692. if (_this.callbackManifestChecked) {
  68693. _this.callbackManifestChecked(true);
  68694. }
  68695. }
  68696. catch (ex) {
  68697. noManifestFile();
  68698. }
  68699. }
  68700. else {
  68701. noManifestFile();
  68702. }
  68703. }, false);
  68704. xhr.addEventListener("error", function (event) {
  68705. if (timeStampUsed) {
  68706. timeStampUsed = false;
  68707. // Let's retry without the timeStamp
  68708. // It could fail when coupled with HTML5 Offline API
  68709. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  68710. xhr.open("GET", retryManifestURL, true);
  68711. xhr.send();
  68712. }
  68713. else {
  68714. noManifestFile();
  68715. }
  68716. }, false);
  68717. try {
  68718. xhr.send();
  68719. }
  68720. catch (ex) {
  68721. BABYLON.Tools.Error("Error on XHR send request.");
  68722. this.callbackManifestChecked(false);
  68723. }
  68724. };
  68725. /**
  68726. * Open the database and make it available
  68727. * @param successCallback defines the callback to call on success
  68728. * @param errorCallback defines the callback to call on error
  68729. */
  68730. Database.prototype.openAsync = function (successCallback, errorCallback) {
  68731. var _this = this;
  68732. var handleError = function () {
  68733. _this.isSupported = false;
  68734. if (errorCallback)
  68735. errorCallback();
  68736. };
  68737. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  68738. // Your browser doesn't support IndexedDB
  68739. this.isSupported = false;
  68740. if (errorCallback)
  68741. errorCallback();
  68742. }
  68743. else {
  68744. // If the DB hasn't been opened or created yet
  68745. if (!this.db) {
  68746. this.hasReachedQuota = false;
  68747. this.isSupported = true;
  68748. var request = this.idbFactory.open("babylonjs", 1);
  68749. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  68750. request.onerror = function (event) {
  68751. handleError();
  68752. };
  68753. // executes when a version change transaction cannot complete due to other active transactions
  68754. request.onblocked = function (event) {
  68755. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  68756. handleError();
  68757. };
  68758. // DB has been opened successfully
  68759. request.onsuccess = function (event) {
  68760. _this.db = request.result;
  68761. successCallback();
  68762. };
  68763. // Initialization of the DB. Creating Scenes & Textures stores
  68764. request.onupgradeneeded = function (event) {
  68765. _this.db = (event.target).result;
  68766. if (_this.db) {
  68767. try {
  68768. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  68769. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  68770. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  68771. }
  68772. catch (ex) {
  68773. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  68774. handleError();
  68775. }
  68776. }
  68777. };
  68778. }
  68779. // DB has already been created and opened
  68780. else {
  68781. if (successCallback)
  68782. successCallback();
  68783. }
  68784. }
  68785. };
  68786. /**
  68787. * Loads an image from the database
  68788. * @param url defines the url to load from
  68789. * @param image defines the target DOM image
  68790. */
  68791. Database.prototype.loadImageFromDB = function (url, image) {
  68792. var _this = this;
  68793. var completeURL = Database._ReturnFullUrlLocation(url);
  68794. var saveAndLoadImage = function () {
  68795. if (!_this.hasReachedQuota && _this.db !== null) {
  68796. // the texture is not yet in the DB, let's try to save it
  68797. _this._saveImageIntoDBAsync(completeURL, image);
  68798. }
  68799. // If the texture is not in the DB and we've reached the DB quota limit
  68800. // let's load it directly from the web
  68801. else {
  68802. image.src = url;
  68803. }
  68804. };
  68805. if (!this.mustUpdateRessources) {
  68806. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  68807. }
  68808. // First time we're download the images or update requested in the manifest file by a version change
  68809. else {
  68810. saveAndLoadImage();
  68811. }
  68812. };
  68813. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  68814. if (this.isSupported && this.db !== null) {
  68815. var texture;
  68816. var transaction = this.db.transaction(["textures"]);
  68817. transaction.onabort = function (event) {
  68818. image.src = url;
  68819. };
  68820. transaction.oncomplete = function (event) {
  68821. var blobTextureURL;
  68822. if (texture) {
  68823. var URL = window.URL || window.webkitURL;
  68824. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  68825. image.onerror = function () {
  68826. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  68827. image.src = url;
  68828. };
  68829. image.src = blobTextureURL;
  68830. }
  68831. else {
  68832. notInDBCallback();
  68833. }
  68834. };
  68835. var getRequest = transaction.objectStore("textures").get(url);
  68836. getRequest.onsuccess = function (event) {
  68837. texture = (event.target).result;
  68838. };
  68839. getRequest.onerror = function (event) {
  68840. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  68841. image.src = url;
  68842. };
  68843. }
  68844. else {
  68845. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68846. image.src = url;
  68847. }
  68848. };
  68849. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  68850. var _this = this;
  68851. if (this.isSupported) {
  68852. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  68853. var generateBlobUrl = function () {
  68854. var blobTextureURL;
  68855. if (blob) {
  68856. var URL = window.URL || window.webkitURL;
  68857. try {
  68858. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  68859. }
  68860. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  68861. catch (ex) {
  68862. blobTextureURL = URL.createObjectURL(blob);
  68863. }
  68864. }
  68865. if (blobTextureURL) {
  68866. image.src = blobTextureURL;
  68867. }
  68868. };
  68869. if (Database.IsUASupportingBlobStorage) { // Create XHR
  68870. var xhr = new XMLHttpRequest(), blob;
  68871. xhr.open("GET", url, true);
  68872. xhr.responseType = "blob";
  68873. xhr.addEventListener("load", function () {
  68874. if (xhr.status === 200 && _this.db) {
  68875. // Blob as response (XHR2)
  68876. blob = xhr.response;
  68877. var transaction = _this.db.transaction(["textures"], "readwrite");
  68878. // the transaction could abort because of a QuotaExceededError error
  68879. transaction.onabort = function (event) {
  68880. try {
  68881. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68882. var srcElement = (event.srcElement || event.target);
  68883. var error = srcElement.error;
  68884. if (error && error.name === "QuotaExceededError") {
  68885. _this.hasReachedQuota = true;
  68886. }
  68887. }
  68888. catch (ex) { }
  68889. generateBlobUrl();
  68890. };
  68891. transaction.oncomplete = function (event) {
  68892. generateBlobUrl();
  68893. };
  68894. var newTexture = { textureUrl: url, data: blob };
  68895. try {
  68896. // Put the blob into the dabase
  68897. var addRequest = transaction.objectStore("textures").put(newTexture);
  68898. addRequest.onsuccess = function (event) {
  68899. };
  68900. addRequest.onerror = function (event) {
  68901. generateBlobUrl();
  68902. };
  68903. }
  68904. catch (ex) {
  68905. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  68906. if (ex.code === 25) {
  68907. Database.IsUASupportingBlobStorage = false;
  68908. }
  68909. image.src = url;
  68910. }
  68911. }
  68912. else {
  68913. image.src = url;
  68914. }
  68915. }, false);
  68916. xhr.addEventListener("error", function (event) {
  68917. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  68918. image.src = url;
  68919. }, false);
  68920. xhr.send();
  68921. }
  68922. else {
  68923. image.src = url;
  68924. }
  68925. }
  68926. else {
  68927. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68928. image.src = url;
  68929. }
  68930. };
  68931. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  68932. var _this = this;
  68933. var updateVersion = function () {
  68934. // the version is not yet in the DB or we need to update it
  68935. _this._saveVersionIntoDBAsync(url, versionLoaded);
  68936. };
  68937. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  68938. };
  68939. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  68940. var _this = this;
  68941. if (this.isSupported && this.db) {
  68942. var version;
  68943. try {
  68944. var transaction = this.db.transaction(["versions"]);
  68945. transaction.oncomplete = function (event) {
  68946. if (version) {
  68947. // If the version in the JSON file is > than the version in DB
  68948. if (_this.manifestVersionFound > version.data) {
  68949. _this.mustUpdateRessources = true;
  68950. updateInDBCallback();
  68951. }
  68952. else {
  68953. callback(version.data);
  68954. }
  68955. }
  68956. // version was not found in DB
  68957. else {
  68958. _this.mustUpdateRessources = true;
  68959. updateInDBCallback();
  68960. }
  68961. };
  68962. transaction.onabort = function (event) {
  68963. callback(-1);
  68964. };
  68965. var getRequest = transaction.objectStore("versions").get(url);
  68966. getRequest.onsuccess = function (event) {
  68967. version = (event.target).result;
  68968. };
  68969. getRequest.onerror = function (event) {
  68970. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  68971. callback(-1);
  68972. };
  68973. }
  68974. catch (ex) {
  68975. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  68976. callback(-1);
  68977. }
  68978. }
  68979. else {
  68980. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68981. callback(-1);
  68982. }
  68983. };
  68984. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  68985. var _this = this;
  68986. if (this.isSupported && !this.hasReachedQuota && this.db) {
  68987. try {
  68988. // Open a transaction to the database
  68989. var transaction = this.db.transaction(["versions"], "readwrite");
  68990. // the transaction could abort because of a QuotaExceededError error
  68991. transaction.onabort = function (event) {
  68992. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68993. var error = event.srcElement['error'];
  68994. if (error && error.name === "QuotaExceededError") {
  68995. _this.hasReachedQuota = true;
  68996. }
  68997. }
  68998. catch (ex) { }
  68999. callback(-1);
  69000. };
  69001. transaction.oncomplete = function (event) {
  69002. callback(_this.manifestVersionFound);
  69003. };
  69004. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69005. // Put the scene into the database
  69006. var addRequest = transaction.objectStore("versions").put(newVersion);
  69007. addRequest.onsuccess = function (event) {
  69008. };
  69009. addRequest.onerror = function (event) {
  69010. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69011. };
  69012. }
  69013. catch (ex) {
  69014. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69015. callback(-1);
  69016. }
  69017. }
  69018. else {
  69019. callback(-1);
  69020. }
  69021. };
  69022. /**
  69023. * Loads a file from database
  69024. * @param url defines the URL to load from
  69025. * @param sceneLoaded defines a callback to call on success
  69026. * @param progressCallBack defines a callback to call when progress changed
  69027. * @param errorCallback defines a callback to call on error
  69028. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69029. */
  69030. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69031. var _this = this;
  69032. var completeUrl = Database._ReturnFullUrlLocation(url);
  69033. var saveAndLoadFile = function () {
  69034. // the scene is not yet in the DB, let's try to save it
  69035. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69036. };
  69037. this._checkVersionFromDB(completeUrl, function (version) {
  69038. if (version !== -1) {
  69039. if (!_this.mustUpdateRessources) {
  69040. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69041. }
  69042. else {
  69043. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69044. }
  69045. }
  69046. else {
  69047. if (errorCallback) {
  69048. errorCallback();
  69049. }
  69050. }
  69051. });
  69052. };
  69053. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69054. if (this.isSupported && this.db) {
  69055. var targetStore;
  69056. if (url.indexOf(".babylon") !== -1) {
  69057. targetStore = "scenes";
  69058. }
  69059. else {
  69060. targetStore = "textures";
  69061. }
  69062. var file;
  69063. var transaction = this.db.transaction([targetStore]);
  69064. transaction.oncomplete = function (event) {
  69065. if (file) {
  69066. callback(file.data);
  69067. }
  69068. // file was not found in DB
  69069. else {
  69070. notInDBCallback();
  69071. }
  69072. };
  69073. transaction.onabort = function (event) {
  69074. notInDBCallback();
  69075. };
  69076. var getRequest = transaction.objectStore(targetStore).get(url);
  69077. getRequest.onsuccess = function (event) {
  69078. file = (event.target).result;
  69079. };
  69080. getRequest.onerror = function (event) {
  69081. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69082. notInDBCallback();
  69083. };
  69084. }
  69085. else {
  69086. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69087. callback();
  69088. }
  69089. };
  69090. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69091. var _this = this;
  69092. if (this.isSupported) {
  69093. var targetStore;
  69094. if (url.indexOf(".babylon") !== -1) {
  69095. targetStore = "scenes";
  69096. }
  69097. else {
  69098. targetStore = "textures";
  69099. }
  69100. // Create XHR
  69101. var xhr = new XMLHttpRequest();
  69102. var fileData;
  69103. xhr.open("GET", url, true);
  69104. if (useArrayBuffer) {
  69105. xhr.responseType = "arraybuffer";
  69106. }
  69107. if (progressCallback) {
  69108. xhr.onprogress = progressCallback;
  69109. }
  69110. xhr.addEventListener("load", function () {
  69111. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69112. // Blob as response (XHR2)
  69113. //fileData = xhr.responseText;
  69114. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69115. if (!_this.hasReachedQuota && _this.db) {
  69116. // Open a transaction to the database
  69117. var transaction = _this.db.transaction([targetStore], "readwrite");
  69118. // the transaction could abort because of a QuotaExceededError error
  69119. transaction.onabort = function (event) {
  69120. try {
  69121. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69122. var error = event.srcElement['error'];
  69123. if (error && error.name === "QuotaExceededError") {
  69124. _this.hasReachedQuota = true;
  69125. }
  69126. }
  69127. catch (ex) { }
  69128. callback(fileData);
  69129. };
  69130. transaction.oncomplete = function (event) {
  69131. callback(fileData);
  69132. };
  69133. var newFile;
  69134. if (targetStore === "scenes") {
  69135. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69136. }
  69137. else {
  69138. newFile = { textureUrl: url, data: fileData };
  69139. }
  69140. try {
  69141. // Put the scene into the database
  69142. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69143. addRequest.onsuccess = function (event) {
  69144. };
  69145. addRequest.onerror = function (event) {
  69146. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69147. };
  69148. }
  69149. catch (ex) {
  69150. callback(fileData);
  69151. }
  69152. }
  69153. else {
  69154. callback(fileData);
  69155. }
  69156. }
  69157. else {
  69158. callback();
  69159. }
  69160. }, false);
  69161. xhr.addEventListener("error", function (event) {
  69162. BABYLON.Tools.Error("error on XHR request.");
  69163. callback();
  69164. }, false);
  69165. xhr.send();
  69166. }
  69167. else {
  69168. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69169. callback();
  69170. }
  69171. };
  69172. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69173. Database.IsUASupportingBlobStorage = true;
  69174. /** Gets a boolean indicating if Database storate is enabled */
  69175. Database.IDBStorageEnabled = true;
  69176. Database._ParseURL = function (url) {
  69177. var a = document.createElement('a');
  69178. a.href = url;
  69179. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69180. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69181. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69182. return absLocation;
  69183. };
  69184. Database._ReturnFullUrlLocation = function (url) {
  69185. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69186. return (Database._ParseURL(window.location.href) + url);
  69187. }
  69188. else {
  69189. return url;
  69190. }
  69191. };
  69192. return Database;
  69193. }());
  69194. BABYLON.Database = Database;
  69195. })(BABYLON || (BABYLON = {}));
  69196. //# sourceMappingURL=babylon.database.js.map
  69197. var BABYLON;
  69198. (function (BABYLON) {
  69199. var FresnelParameters = /** @class */ (function () {
  69200. function FresnelParameters() {
  69201. this._isEnabled = true;
  69202. this.leftColor = BABYLON.Color3.White();
  69203. this.rightColor = BABYLON.Color3.Black();
  69204. this.bias = 0;
  69205. this.power = 1;
  69206. }
  69207. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69208. get: function () {
  69209. return this._isEnabled;
  69210. },
  69211. set: function (value) {
  69212. if (this._isEnabled === value) {
  69213. return;
  69214. }
  69215. this._isEnabled = value;
  69216. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69217. },
  69218. enumerable: true,
  69219. configurable: true
  69220. });
  69221. FresnelParameters.prototype.clone = function () {
  69222. var newFresnelParameters = new FresnelParameters();
  69223. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69224. return newFresnelParameters;
  69225. };
  69226. FresnelParameters.prototype.serialize = function () {
  69227. var serializationObject = {};
  69228. serializationObject.isEnabled = this.isEnabled;
  69229. serializationObject.leftColor = this.leftColor.asArray();
  69230. serializationObject.rightColor = this.rightColor.asArray();
  69231. serializationObject.bias = this.bias;
  69232. serializationObject.power = this.power;
  69233. return serializationObject;
  69234. };
  69235. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69236. var fresnelParameters = new FresnelParameters();
  69237. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69238. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69239. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69240. fresnelParameters.bias = parsedFresnelParameters.bias;
  69241. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69242. return fresnelParameters;
  69243. };
  69244. return FresnelParameters;
  69245. }());
  69246. BABYLON.FresnelParameters = FresnelParameters;
  69247. })(BABYLON || (BABYLON = {}));
  69248. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69249. var BABYLON;
  69250. (function (BABYLON) {
  69251. var MultiMaterial = /** @class */ (function (_super) {
  69252. __extends(MultiMaterial, _super);
  69253. function MultiMaterial(name, scene) {
  69254. var _this = _super.call(this, name, scene, true) || this;
  69255. scene.multiMaterials.push(_this);
  69256. _this.subMaterials = new Array();
  69257. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69258. return _this;
  69259. }
  69260. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69261. get: function () {
  69262. return this._subMaterials;
  69263. },
  69264. set: function (value) {
  69265. this._subMaterials = value;
  69266. this._hookArray(value);
  69267. },
  69268. enumerable: true,
  69269. configurable: true
  69270. });
  69271. MultiMaterial.prototype._hookArray = function (array) {
  69272. var _this = this;
  69273. var oldPush = array.push;
  69274. array.push = function () {
  69275. var items = [];
  69276. for (var _i = 0; _i < arguments.length; _i++) {
  69277. items[_i] = arguments[_i];
  69278. }
  69279. var result = oldPush.apply(array, items);
  69280. _this._markAllSubMeshesAsTexturesDirty();
  69281. return result;
  69282. };
  69283. var oldSplice = array.splice;
  69284. array.splice = function (index, deleteCount) {
  69285. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69286. _this._markAllSubMeshesAsTexturesDirty();
  69287. return deleted;
  69288. };
  69289. };
  69290. // Properties
  69291. MultiMaterial.prototype.getSubMaterial = function (index) {
  69292. if (index < 0 || index >= this.subMaterials.length) {
  69293. return this.getScene().defaultMaterial;
  69294. }
  69295. return this.subMaterials[index];
  69296. };
  69297. MultiMaterial.prototype.getActiveTextures = function () {
  69298. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69299. if (subMaterial) {
  69300. return subMaterial.getActiveTextures();
  69301. }
  69302. else {
  69303. return [];
  69304. }
  69305. }));
  69306. var _a;
  69307. };
  69308. // Methods
  69309. MultiMaterial.prototype.getClassName = function () {
  69310. return "MultiMaterial";
  69311. };
  69312. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69313. for (var index = 0; index < this.subMaterials.length; index++) {
  69314. var subMaterial = this.subMaterials[index];
  69315. if (subMaterial) {
  69316. if (subMaterial.storeEffectOnSubMeshes) {
  69317. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69318. return false;
  69319. }
  69320. continue;
  69321. }
  69322. if (!subMaterial.isReady(mesh)) {
  69323. return false;
  69324. }
  69325. }
  69326. }
  69327. return true;
  69328. };
  69329. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69330. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69331. for (var index = 0; index < this.subMaterials.length; index++) {
  69332. var subMaterial = null;
  69333. var current = this.subMaterials[index];
  69334. if (cloneChildren && current) {
  69335. subMaterial = current.clone(name + "-" + current.name);
  69336. }
  69337. else {
  69338. subMaterial = this.subMaterials[index];
  69339. }
  69340. newMultiMaterial.subMaterials.push(subMaterial);
  69341. }
  69342. return newMultiMaterial;
  69343. };
  69344. MultiMaterial.prototype.serialize = function () {
  69345. var serializationObject = {};
  69346. serializationObject.name = this.name;
  69347. serializationObject.id = this.id;
  69348. if (BABYLON.Tags) {
  69349. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69350. }
  69351. serializationObject.materials = [];
  69352. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69353. var subMat = this.subMaterials[matIndex];
  69354. if (subMat) {
  69355. serializationObject.materials.push(subMat.id);
  69356. }
  69357. else {
  69358. serializationObject.materials.push(null);
  69359. }
  69360. }
  69361. return serializationObject;
  69362. };
  69363. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69364. var scene = this.getScene();
  69365. if (!scene) {
  69366. return;
  69367. }
  69368. var index = scene.multiMaterials.indexOf(this);
  69369. if (index >= 0) {
  69370. scene.multiMaterials.splice(index, 1);
  69371. }
  69372. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69373. };
  69374. return MultiMaterial;
  69375. }(BABYLON.Material));
  69376. BABYLON.MultiMaterial = MultiMaterial;
  69377. })(BABYLON || (BABYLON = {}));
  69378. //# sourceMappingURL=babylon.multiMaterial.js.map
  69379. var BABYLON;
  69380. (function (BABYLON) {
  69381. var FreeCameraTouchInput = /** @class */ (function () {
  69382. function FreeCameraTouchInput() {
  69383. this._offsetX = null;
  69384. this._offsetY = null;
  69385. this._pointerPressed = new Array();
  69386. this.touchAngularSensibility = 200000.0;
  69387. this.touchMoveSensibility = 250.0;
  69388. }
  69389. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69390. var _this = this;
  69391. var previousPosition = null;
  69392. if (this._pointerInput === undefined) {
  69393. this._onLostFocus = function (evt) {
  69394. _this._offsetX = null;
  69395. _this._offsetY = null;
  69396. };
  69397. this._pointerInput = function (p, s) {
  69398. var evt = p.event;
  69399. if (evt.pointerType === "mouse") {
  69400. return;
  69401. }
  69402. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69403. if (!noPreventDefault) {
  69404. evt.preventDefault();
  69405. }
  69406. _this._pointerPressed.push(evt.pointerId);
  69407. if (_this._pointerPressed.length !== 1) {
  69408. return;
  69409. }
  69410. previousPosition = {
  69411. x: evt.clientX,
  69412. y: evt.clientY
  69413. };
  69414. }
  69415. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69416. if (!noPreventDefault) {
  69417. evt.preventDefault();
  69418. }
  69419. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69420. if (index === -1) {
  69421. return;
  69422. }
  69423. _this._pointerPressed.splice(index, 1);
  69424. if (index != 0) {
  69425. return;
  69426. }
  69427. previousPosition = null;
  69428. _this._offsetX = null;
  69429. _this._offsetY = null;
  69430. }
  69431. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  69432. if (!noPreventDefault) {
  69433. evt.preventDefault();
  69434. }
  69435. if (!previousPosition) {
  69436. return;
  69437. }
  69438. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69439. if (index != 0) {
  69440. return;
  69441. }
  69442. _this._offsetX = evt.clientX - previousPosition.x;
  69443. _this._offsetY = -(evt.clientY - previousPosition.y);
  69444. }
  69445. };
  69446. }
  69447. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69448. if (this._onLostFocus) {
  69449. element.addEventListener("blur", this._onLostFocus);
  69450. }
  69451. };
  69452. FreeCameraTouchInput.prototype.detachControl = function (element) {
  69453. if (this._pointerInput && element) {
  69454. if (this._observer) {
  69455. this.camera.getScene().onPointerObservable.remove(this._observer);
  69456. this._observer = null;
  69457. }
  69458. if (this._onLostFocus) {
  69459. element.removeEventListener("blur", this._onLostFocus);
  69460. this._onLostFocus = null;
  69461. }
  69462. this._pointerPressed = [];
  69463. this._offsetX = null;
  69464. this._offsetY = null;
  69465. }
  69466. };
  69467. FreeCameraTouchInput.prototype.checkInputs = function () {
  69468. if (this._offsetX && this._offsetY) {
  69469. var camera = this.camera;
  69470. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  69471. if (this._pointerPressed.length > 1) {
  69472. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  69473. }
  69474. else {
  69475. var speed = camera._computeLocalCameraSpeed();
  69476. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  69477. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  69478. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  69479. }
  69480. }
  69481. };
  69482. FreeCameraTouchInput.prototype.getClassName = function () {
  69483. return "FreeCameraTouchInput";
  69484. };
  69485. FreeCameraTouchInput.prototype.getSimpleName = function () {
  69486. return "touch";
  69487. };
  69488. __decorate([
  69489. BABYLON.serialize()
  69490. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  69491. __decorate([
  69492. BABYLON.serialize()
  69493. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  69494. return FreeCameraTouchInput;
  69495. }());
  69496. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  69497. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  69498. })(BABYLON || (BABYLON = {}));
  69499. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  69500. var BABYLON;
  69501. (function (BABYLON) {
  69502. // We're mainly based on the logic defined into the FreeCamera code
  69503. var TouchCamera = /** @class */ (function (_super) {
  69504. __extends(TouchCamera, _super);
  69505. //-- end properties for backward compatibility for inputs
  69506. function TouchCamera(name, position, scene) {
  69507. var _this = _super.call(this, name, position, scene) || this;
  69508. _this.inputs.addTouch();
  69509. _this._setupInputs();
  69510. return _this;
  69511. }
  69512. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  69513. //-- Begin properties for backward compatibility for inputs
  69514. get: function () {
  69515. var touch = this.inputs.attached["touch"];
  69516. if (touch)
  69517. return touch.touchAngularSensibility;
  69518. return 0;
  69519. },
  69520. set: function (value) {
  69521. var touch = this.inputs.attached["touch"];
  69522. if (touch)
  69523. touch.touchAngularSensibility = value;
  69524. },
  69525. enumerable: true,
  69526. configurable: true
  69527. });
  69528. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  69529. get: function () {
  69530. var touch = this.inputs.attached["touch"];
  69531. if (touch)
  69532. return touch.touchMoveSensibility;
  69533. return 0;
  69534. },
  69535. set: function (value) {
  69536. var touch = this.inputs.attached["touch"];
  69537. if (touch)
  69538. touch.touchMoveSensibility = value;
  69539. },
  69540. enumerable: true,
  69541. configurable: true
  69542. });
  69543. TouchCamera.prototype.getClassName = function () {
  69544. return "TouchCamera";
  69545. };
  69546. TouchCamera.prototype._setupInputs = function () {
  69547. var mouse = this.inputs.attached["mouse"];
  69548. if (mouse) {
  69549. mouse.touchEnabled = false;
  69550. }
  69551. };
  69552. return TouchCamera;
  69553. }(BABYLON.FreeCamera));
  69554. BABYLON.TouchCamera = TouchCamera;
  69555. })(BABYLON || (BABYLON = {}));
  69556. //# sourceMappingURL=babylon.touchCamera.js.map
  69557. var BABYLON;
  69558. (function (BABYLON) {
  69559. var ProceduralTexture = /** @class */ (function (_super) {
  69560. __extends(ProceduralTexture, _super);
  69561. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  69562. if (fallbackTexture === void 0) { fallbackTexture = null; }
  69563. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69564. if (isCube === void 0) { isCube = false; }
  69565. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69566. _this.isCube = isCube;
  69567. _this.isEnabled = true;
  69568. _this._currentRefreshId = -1;
  69569. _this._refreshRate = 1;
  69570. _this._vertexBuffers = {};
  69571. _this._uniforms = new Array();
  69572. _this._samplers = new Array();
  69573. _this._textures = {};
  69574. _this._floats = {};
  69575. _this._floatsArrays = {};
  69576. _this._colors3 = {};
  69577. _this._colors4 = {};
  69578. _this._vectors2 = {};
  69579. _this._vectors3 = {};
  69580. _this._matrices = {};
  69581. _this._fallbackTextureUsed = false;
  69582. scene.proceduralTextures.push(_this);
  69583. _this._engine = scene.getEngine();
  69584. _this.name = name;
  69585. _this.isRenderTarget = true;
  69586. _this._size = size;
  69587. _this._generateMipMaps = generateMipMaps;
  69588. _this.setFragment(fragment);
  69589. _this._fallbackTexture = fallbackTexture;
  69590. if (isCube) {
  69591. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  69592. _this.setFloat("face", 0);
  69593. }
  69594. else {
  69595. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  69596. }
  69597. // VBO
  69598. var vertices = [];
  69599. vertices.push(1, 1);
  69600. vertices.push(-1, 1);
  69601. vertices.push(-1, -1);
  69602. vertices.push(1, -1);
  69603. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69604. _this._createIndexBuffer();
  69605. return _this;
  69606. }
  69607. ProceduralTexture.prototype._createIndexBuffer = function () {
  69608. var engine = this._engine;
  69609. // Indices
  69610. var indices = [];
  69611. indices.push(0);
  69612. indices.push(1);
  69613. indices.push(2);
  69614. indices.push(0);
  69615. indices.push(2);
  69616. indices.push(3);
  69617. this._indexBuffer = engine.createIndexBuffer(indices);
  69618. };
  69619. ProceduralTexture.prototype._rebuild = function () {
  69620. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69621. if (vb) {
  69622. vb._rebuild();
  69623. }
  69624. this._createIndexBuffer();
  69625. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  69626. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  69627. }
  69628. };
  69629. ProceduralTexture.prototype.reset = function () {
  69630. if (this._effect === undefined) {
  69631. return;
  69632. }
  69633. var engine = this._engine;
  69634. engine._releaseEffect(this._effect);
  69635. };
  69636. ProceduralTexture.prototype.isReady = function () {
  69637. var _this = this;
  69638. var engine = this._engine;
  69639. var shaders;
  69640. if (!this._fragment) {
  69641. return false;
  69642. }
  69643. if (this._fallbackTextureUsed) {
  69644. return true;
  69645. }
  69646. if (this._fragment.fragmentElement !== undefined) {
  69647. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  69648. }
  69649. else {
  69650. shaders = { vertex: "procedural", fragment: this._fragment };
  69651. }
  69652. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  69653. _this.releaseInternalTexture();
  69654. if (_this._fallbackTexture) {
  69655. _this._texture = _this._fallbackTexture._texture;
  69656. if (_this._texture) {
  69657. _this._texture.incrementReferences();
  69658. }
  69659. }
  69660. _this._fallbackTextureUsed = true;
  69661. });
  69662. return this._effect.isReady();
  69663. };
  69664. ProceduralTexture.prototype.resetRefreshCounter = function () {
  69665. this._currentRefreshId = -1;
  69666. };
  69667. ProceduralTexture.prototype.setFragment = function (fragment) {
  69668. this._fragment = fragment;
  69669. };
  69670. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  69671. get: function () {
  69672. return this._refreshRate;
  69673. },
  69674. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69675. set: function (value) {
  69676. this._refreshRate = value;
  69677. this.resetRefreshCounter();
  69678. },
  69679. enumerable: true,
  69680. configurable: true
  69681. });
  69682. ProceduralTexture.prototype._shouldRender = function () {
  69683. if (!this.isEnabled || !this.isReady() || !this._texture) {
  69684. return false;
  69685. }
  69686. if (this._fallbackTextureUsed) {
  69687. return false;
  69688. }
  69689. if (this._currentRefreshId === -1) { // At least render once
  69690. this._currentRefreshId = 1;
  69691. return true;
  69692. }
  69693. if (this.refreshRate === this._currentRefreshId) {
  69694. this._currentRefreshId = 1;
  69695. return true;
  69696. }
  69697. this._currentRefreshId++;
  69698. return false;
  69699. };
  69700. ProceduralTexture.prototype.getRenderSize = function () {
  69701. return this._size;
  69702. };
  69703. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  69704. if (this._fallbackTextureUsed) {
  69705. return;
  69706. }
  69707. this.releaseInternalTexture();
  69708. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  69709. };
  69710. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  69711. if (this._uniforms.indexOf(uniformName) === -1) {
  69712. this._uniforms.push(uniformName);
  69713. }
  69714. };
  69715. ProceduralTexture.prototype.setTexture = function (name, texture) {
  69716. if (this._samplers.indexOf(name) === -1) {
  69717. this._samplers.push(name);
  69718. }
  69719. this._textures[name] = texture;
  69720. return this;
  69721. };
  69722. ProceduralTexture.prototype.setFloat = function (name, value) {
  69723. this._checkUniform(name);
  69724. this._floats[name] = value;
  69725. return this;
  69726. };
  69727. ProceduralTexture.prototype.setFloats = function (name, value) {
  69728. this._checkUniform(name);
  69729. this._floatsArrays[name] = value;
  69730. return this;
  69731. };
  69732. ProceduralTexture.prototype.setColor3 = function (name, value) {
  69733. this._checkUniform(name);
  69734. this._colors3[name] = value;
  69735. return this;
  69736. };
  69737. ProceduralTexture.prototype.setColor4 = function (name, value) {
  69738. this._checkUniform(name);
  69739. this._colors4[name] = value;
  69740. return this;
  69741. };
  69742. ProceduralTexture.prototype.setVector2 = function (name, value) {
  69743. this._checkUniform(name);
  69744. this._vectors2[name] = value;
  69745. return this;
  69746. };
  69747. ProceduralTexture.prototype.setVector3 = function (name, value) {
  69748. this._checkUniform(name);
  69749. this._vectors3[name] = value;
  69750. return this;
  69751. };
  69752. ProceduralTexture.prototype.setMatrix = function (name, value) {
  69753. this._checkUniform(name);
  69754. this._matrices[name] = value;
  69755. return this;
  69756. };
  69757. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69758. var scene = this.getScene();
  69759. if (!scene) {
  69760. return;
  69761. }
  69762. var engine = this._engine;
  69763. // Render
  69764. engine.enableEffect(this._effect);
  69765. engine.setState(false);
  69766. // Texture
  69767. for (var name in this._textures) {
  69768. this._effect.setTexture(name, this._textures[name]);
  69769. }
  69770. // Float
  69771. for (name in this._floats) {
  69772. this._effect.setFloat(name, this._floats[name]);
  69773. }
  69774. // Floats
  69775. for (name in this._floatsArrays) {
  69776. this._effect.setArray(name, this._floatsArrays[name]);
  69777. }
  69778. // Color3
  69779. for (name in this._colors3) {
  69780. this._effect.setColor3(name, this._colors3[name]);
  69781. }
  69782. // Color4
  69783. for (name in this._colors4) {
  69784. var color = this._colors4[name];
  69785. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  69786. }
  69787. // Vector2
  69788. for (name in this._vectors2) {
  69789. this._effect.setVector2(name, this._vectors2[name]);
  69790. }
  69791. // Vector3
  69792. for (name in this._vectors3) {
  69793. this._effect.setVector3(name, this._vectors3[name]);
  69794. }
  69795. // Matrix
  69796. for (name in this._matrices) {
  69797. this._effect.setMatrix(name, this._matrices[name]);
  69798. }
  69799. if (!this._texture) {
  69800. return;
  69801. }
  69802. if (this.isCube) {
  69803. for (var face = 0; face < 6; face++) {
  69804. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  69805. // VBOs
  69806. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69807. this._effect.setFloat("face", face);
  69808. // Clear
  69809. engine.clear(scene.clearColor, true, true, true);
  69810. // Draw order
  69811. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69812. // Mipmaps
  69813. if (face === 5) {
  69814. engine.generateMipMapsForCubemap(this._texture);
  69815. }
  69816. }
  69817. }
  69818. else {
  69819. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  69820. // VBOs
  69821. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69822. // Clear
  69823. engine.clear(scene.clearColor, true, true, true);
  69824. // Draw order
  69825. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69826. }
  69827. // Unbind
  69828. engine.unBindFramebuffer(this._texture, this.isCube);
  69829. if (this.onGenerated) {
  69830. this.onGenerated();
  69831. }
  69832. };
  69833. ProceduralTexture.prototype.clone = function () {
  69834. var textureSize = this.getSize();
  69835. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  69836. // Base texture
  69837. newTexture.hasAlpha = this.hasAlpha;
  69838. newTexture.level = this.level;
  69839. // RenderTarget Texture
  69840. newTexture.coordinatesMode = this.coordinatesMode;
  69841. return newTexture;
  69842. };
  69843. ProceduralTexture.prototype.dispose = function () {
  69844. var scene = this.getScene();
  69845. if (!scene) {
  69846. return;
  69847. }
  69848. var index = scene.proceduralTextures.indexOf(this);
  69849. if (index >= 0) {
  69850. scene.proceduralTextures.splice(index, 1);
  69851. }
  69852. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69853. if (vertexBuffer) {
  69854. vertexBuffer.dispose();
  69855. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69856. }
  69857. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  69858. this._indexBuffer = null;
  69859. }
  69860. _super.prototype.dispose.call(this);
  69861. };
  69862. return ProceduralTexture;
  69863. }(BABYLON.Texture));
  69864. BABYLON.ProceduralTexture = ProceduralTexture;
  69865. })(BABYLON || (BABYLON = {}));
  69866. //# sourceMappingURL=babylon.proceduralTexture.js.map
  69867. var BABYLON;
  69868. (function (BABYLON) {
  69869. var CustomProceduralTexture = /** @class */ (function (_super) {
  69870. __extends(CustomProceduralTexture, _super);
  69871. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  69872. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  69873. _this._animate = true;
  69874. _this._time = 0;
  69875. _this._texturePath = texturePath;
  69876. //Try to load json
  69877. _this.loadJson(texturePath);
  69878. _this.refreshRate = 1;
  69879. return _this;
  69880. }
  69881. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  69882. var _this = this;
  69883. var noConfigFile = function () {
  69884. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  69885. try {
  69886. _this.setFragment(_this._texturePath);
  69887. }
  69888. catch (ex) {
  69889. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  69890. }
  69891. };
  69892. var configFileUrl = jsonUrl + "/config.json";
  69893. var xhr = new XMLHttpRequest();
  69894. xhr.open("GET", configFileUrl, true);
  69895. xhr.addEventListener("load", function () {
  69896. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69897. try {
  69898. _this._config = JSON.parse(xhr.response);
  69899. _this.updateShaderUniforms();
  69900. _this.updateTextures();
  69901. _this.setFragment(_this._texturePath + "/custom");
  69902. _this._animate = _this._config.animate;
  69903. _this.refreshRate = _this._config.refreshrate;
  69904. }
  69905. catch (ex) {
  69906. noConfigFile();
  69907. }
  69908. }
  69909. else {
  69910. noConfigFile();
  69911. }
  69912. }, false);
  69913. xhr.addEventListener("error", function () {
  69914. noConfigFile();
  69915. }, false);
  69916. try {
  69917. xhr.send();
  69918. }
  69919. catch (ex) {
  69920. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  69921. }
  69922. };
  69923. CustomProceduralTexture.prototype.isReady = function () {
  69924. if (!_super.prototype.isReady.call(this)) {
  69925. return false;
  69926. }
  69927. for (var name in this._textures) {
  69928. var texture = this._textures[name];
  69929. if (!texture.isReady()) {
  69930. return false;
  69931. }
  69932. }
  69933. return true;
  69934. };
  69935. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69936. var scene = this.getScene();
  69937. if (this._animate && scene) {
  69938. this._time += scene.getAnimationRatio() * 0.03;
  69939. this.updateShaderUniforms();
  69940. }
  69941. _super.prototype.render.call(this, useCameraPostProcess);
  69942. };
  69943. CustomProceduralTexture.prototype.updateTextures = function () {
  69944. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  69945. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  69946. }
  69947. };
  69948. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  69949. if (this._config) {
  69950. for (var j = 0; j < this._config.uniforms.length; j++) {
  69951. var uniform = this._config.uniforms[j];
  69952. switch (uniform.type) {
  69953. case "float":
  69954. this.setFloat(uniform.name, uniform.value);
  69955. break;
  69956. case "color3":
  69957. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  69958. break;
  69959. case "color4":
  69960. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  69961. break;
  69962. case "vector2":
  69963. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  69964. break;
  69965. case "vector3":
  69966. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  69967. break;
  69968. }
  69969. }
  69970. }
  69971. this.setFloat("time", this._time);
  69972. };
  69973. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  69974. get: function () {
  69975. return this._animate;
  69976. },
  69977. set: function (value) {
  69978. this._animate = value;
  69979. },
  69980. enumerable: true,
  69981. configurable: true
  69982. });
  69983. return CustomProceduralTexture;
  69984. }(BABYLON.ProceduralTexture));
  69985. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  69986. })(BABYLON || (BABYLON = {}));
  69987. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  69988. var BABYLON;
  69989. (function (BABYLON) {
  69990. var FreeCameraGamepadInput = /** @class */ (function () {
  69991. function FreeCameraGamepadInput() {
  69992. this.gamepadAngularSensibility = 200;
  69993. this.gamepadMoveSensibility = 40;
  69994. // private members
  69995. this._cameraTransform = BABYLON.Matrix.Identity();
  69996. this._deltaTransform = BABYLON.Vector3.Zero();
  69997. this._vector3 = BABYLON.Vector3.Zero();
  69998. this._vector2 = BABYLON.Vector2.Zero();
  69999. }
  70000. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70001. var _this = this;
  70002. var manager = this.camera.getScene().gamepadManager;
  70003. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70004. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70005. // prioritize XBOX gamepads.
  70006. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70007. _this.gamepad = gamepad;
  70008. }
  70009. }
  70010. });
  70011. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70012. if (_this.gamepad === gamepad) {
  70013. _this.gamepad = null;
  70014. }
  70015. });
  70016. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70017. };
  70018. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70019. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70020. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70021. this.gamepad = null;
  70022. };
  70023. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70024. if (this.gamepad && this.gamepad.leftStick) {
  70025. var camera = this.camera;
  70026. var LSValues = this.gamepad.leftStick;
  70027. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70028. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70029. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70030. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70031. var RSValues = this.gamepad.rightStick;
  70032. if (RSValues) {
  70033. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70034. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70035. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70036. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70037. }
  70038. else {
  70039. RSValues = { x: 0, y: 0 };
  70040. }
  70041. if (!camera.rotationQuaternion) {
  70042. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70043. }
  70044. else {
  70045. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70046. }
  70047. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70048. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70049. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70050. camera.cameraDirection.addInPlace(this._deltaTransform);
  70051. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70052. camera.cameraRotation.addInPlace(this._vector2);
  70053. }
  70054. };
  70055. FreeCameraGamepadInput.prototype.getClassName = function () {
  70056. return "FreeCameraGamepadInput";
  70057. };
  70058. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70059. return "gamepad";
  70060. };
  70061. __decorate([
  70062. BABYLON.serialize()
  70063. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70064. __decorate([
  70065. BABYLON.serialize()
  70066. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70067. return FreeCameraGamepadInput;
  70068. }());
  70069. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70070. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70071. })(BABYLON || (BABYLON = {}));
  70072. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70073. var BABYLON;
  70074. (function (BABYLON) {
  70075. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70076. function ArcRotateCameraGamepadInput() {
  70077. this.gamepadRotationSensibility = 80;
  70078. this.gamepadMoveSensibility = 40;
  70079. }
  70080. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70081. var _this = this;
  70082. var manager = this.camera.getScene().gamepadManager;
  70083. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70084. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70085. // prioritize XBOX gamepads.
  70086. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70087. _this.gamepad = gamepad;
  70088. }
  70089. }
  70090. });
  70091. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70092. if (_this.gamepad === gamepad) {
  70093. _this.gamepad = null;
  70094. }
  70095. });
  70096. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70097. };
  70098. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70099. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70100. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70101. this.gamepad = null;
  70102. };
  70103. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70104. if (this.gamepad) {
  70105. var camera = this.camera;
  70106. var RSValues = this.gamepad.rightStick;
  70107. if (RSValues) {
  70108. if (RSValues.x != 0) {
  70109. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70110. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70111. camera.inertialAlphaOffset += normalizedRX;
  70112. }
  70113. }
  70114. if (RSValues.y != 0) {
  70115. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70116. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70117. camera.inertialBetaOffset += normalizedRY;
  70118. }
  70119. }
  70120. }
  70121. var LSValues = this.gamepad.leftStick;
  70122. if (LSValues && LSValues.y != 0) {
  70123. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70124. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70125. this.camera.inertialRadiusOffset -= normalizedLY;
  70126. }
  70127. }
  70128. }
  70129. };
  70130. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70131. return "ArcRotateCameraGamepadInput";
  70132. };
  70133. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70134. return "gamepad";
  70135. };
  70136. __decorate([
  70137. BABYLON.serialize()
  70138. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70139. __decorate([
  70140. BABYLON.serialize()
  70141. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70142. return ArcRotateCameraGamepadInput;
  70143. }());
  70144. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70145. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70146. })(BABYLON || (BABYLON = {}));
  70147. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70148. var BABYLON;
  70149. (function (BABYLON) {
  70150. var GamepadManager = /** @class */ (function () {
  70151. function GamepadManager(_scene) {
  70152. var _this = this;
  70153. this._scene = _scene;
  70154. this._babylonGamepads = [];
  70155. this._oneGamepadConnected = false;
  70156. this._isMonitoring = false;
  70157. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70158. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70159. this._gamepadEventSupported = false;
  70160. }
  70161. else {
  70162. this._gamepadEventSupported = 'GamepadEvent' in window;
  70163. this._gamepadSupport = (navigator.getGamepads ||
  70164. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70165. }
  70166. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70167. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70168. for (var i in _this._babylonGamepads) {
  70169. var gamepad = _this._babylonGamepads[i];
  70170. if (gamepad && gamepad._isConnected) {
  70171. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70172. }
  70173. }
  70174. });
  70175. this._onGamepadConnectedEvent = function (evt) {
  70176. var gamepad = evt.gamepad;
  70177. if (gamepad.index in _this._babylonGamepads) {
  70178. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70179. return;
  70180. }
  70181. }
  70182. var newGamepad;
  70183. if (_this._babylonGamepads[gamepad.index]) {
  70184. newGamepad = _this._babylonGamepads[gamepad.index];
  70185. newGamepad.browserGamepad = gamepad;
  70186. newGamepad._isConnected = true;
  70187. }
  70188. else {
  70189. newGamepad = _this._addNewGamepad(gamepad);
  70190. }
  70191. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70192. _this._startMonitoringGamepads();
  70193. };
  70194. this._onGamepadDisconnectedEvent = function (evt) {
  70195. var gamepad = evt.gamepad;
  70196. // Remove the gamepad from the list of gamepads to monitor.
  70197. for (var i in _this._babylonGamepads) {
  70198. if (_this._babylonGamepads[i].index === gamepad.index) {
  70199. var disconnectedGamepad = _this._babylonGamepads[i];
  70200. disconnectedGamepad._isConnected = false;
  70201. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70202. break;
  70203. }
  70204. }
  70205. };
  70206. if (this._gamepadSupport) {
  70207. //first add already-connected gamepads
  70208. this._updateGamepadObjects();
  70209. if (this._babylonGamepads.length) {
  70210. this._startMonitoringGamepads();
  70211. }
  70212. // Checking if the gamepad connected event is supported (like in Firefox)
  70213. if (this._gamepadEventSupported) {
  70214. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70215. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70216. }
  70217. else {
  70218. this._startMonitoringGamepads();
  70219. }
  70220. }
  70221. }
  70222. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70223. get: function () {
  70224. return this._babylonGamepads;
  70225. },
  70226. enumerable: true,
  70227. configurable: true
  70228. });
  70229. GamepadManager.prototype.getGamepadByType = function (type) {
  70230. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70231. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70232. var gamepad = _a[_i];
  70233. if (gamepad && gamepad.type === type) {
  70234. return gamepad;
  70235. }
  70236. }
  70237. return null;
  70238. };
  70239. GamepadManager.prototype.dispose = function () {
  70240. if (this._gamepadEventSupported) {
  70241. if (this._onGamepadConnectedEvent) {
  70242. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70243. }
  70244. if (this._onGamepadDisconnectedEvent) {
  70245. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70246. }
  70247. this._onGamepadConnectedEvent = null;
  70248. this._onGamepadDisconnectedEvent = null;
  70249. }
  70250. this._babylonGamepads.forEach(function (gamepad) {
  70251. gamepad.dispose();
  70252. });
  70253. this.onGamepadConnectedObservable.clear();
  70254. this.onGamepadDisconnectedObservable.clear();
  70255. this._oneGamepadConnected = false;
  70256. this._stopMonitoringGamepads();
  70257. this._babylonGamepads = [];
  70258. };
  70259. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70260. if (!this._oneGamepadConnected) {
  70261. this._oneGamepadConnected = true;
  70262. }
  70263. var newGamepad;
  70264. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70265. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70266. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70267. }
  70268. // if pose is supported, use the (WebVR) pose enabled controller
  70269. else if (gamepad.pose) {
  70270. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70271. }
  70272. else {
  70273. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70274. }
  70275. this._babylonGamepads[newGamepad.index] = newGamepad;
  70276. return newGamepad;
  70277. };
  70278. GamepadManager.prototype._startMonitoringGamepads = function () {
  70279. if (!this._isMonitoring) {
  70280. this._isMonitoring = true;
  70281. //back-comp
  70282. if (!this._scene) {
  70283. this._checkGamepadsStatus();
  70284. }
  70285. }
  70286. };
  70287. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70288. this._isMonitoring = false;
  70289. };
  70290. GamepadManager.prototype._checkGamepadsStatus = function () {
  70291. var _this = this;
  70292. // Hack to be compatible Chrome
  70293. this._updateGamepadObjects();
  70294. for (var i in this._babylonGamepads) {
  70295. var gamepad = this._babylonGamepads[i];
  70296. if (!gamepad || !gamepad.isConnected) {
  70297. continue;
  70298. }
  70299. gamepad.update();
  70300. }
  70301. if (this._isMonitoring && !this._scene) {
  70302. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70303. }
  70304. };
  70305. // This function is called only on Chrome, which does not properly support
  70306. // connection/disconnection events and forces you to recopy again the gamepad object
  70307. GamepadManager.prototype._updateGamepadObjects = function () {
  70308. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70309. for (var i = 0; i < gamepads.length; i++) {
  70310. var gamepad = gamepads[i];
  70311. if (gamepad) {
  70312. if (!this._babylonGamepads[gamepad.index]) {
  70313. var newGamepad = this._addNewGamepad(gamepad);
  70314. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70315. }
  70316. else {
  70317. // Forced to copy again this object for Chrome for unknown reason
  70318. this._babylonGamepads[i].browserGamepad = gamepad;
  70319. if (!this._babylonGamepads[i].isConnected) {
  70320. this._babylonGamepads[i]._isConnected = true;
  70321. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70322. }
  70323. }
  70324. }
  70325. }
  70326. };
  70327. return GamepadManager;
  70328. }());
  70329. BABYLON.GamepadManager = GamepadManager;
  70330. })(BABYLON || (BABYLON = {}));
  70331. //# sourceMappingURL=babylon.gamepadManager.js.map
  70332. var BABYLON;
  70333. (function (BABYLON) {
  70334. var StickValues = /** @class */ (function () {
  70335. function StickValues(x, y) {
  70336. this.x = x;
  70337. this.y = y;
  70338. }
  70339. return StickValues;
  70340. }());
  70341. BABYLON.StickValues = StickValues;
  70342. var Gamepad = /** @class */ (function () {
  70343. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70344. if (leftStickX === void 0) { leftStickX = 0; }
  70345. if (leftStickY === void 0) { leftStickY = 1; }
  70346. if (rightStickX === void 0) { rightStickX = 2; }
  70347. if (rightStickY === void 0) { rightStickY = 3; }
  70348. this.id = id;
  70349. this.index = index;
  70350. this.browserGamepad = browserGamepad;
  70351. this._isConnected = true;
  70352. this._invertLeftStickY = false;
  70353. this.type = Gamepad.GAMEPAD;
  70354. this._leftStickAxisX = leftStickX;
  70355. this._leftStickAxisY = leftStickY;
  70356. this._rightStickAxisX = rightStickX;
  70357. this._rightStickAxisY = rightStickY;
  70358. if (this.browserGamepad.axes.length >= 2) {
  70359. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70360. }
  70361. if (this.browserGamepad.axes.length >= 4) {
  70362. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70363. }
  70364. }
  70365. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70366. get: function () {
  70367. return this._isConnected;
  70368. },
  70369. enumerable: true,
  70370. configurable: true
  70371. });
  70372. Gamepad.prototype.onleftstickchanged = function (callback) {
  70373. this._onleftstickchanged = callback;
  70374. };
  70375. Gamepad.prototype.onrightstickchanged = function (callback) {
  70376. this._onrightstickchanged = callback;
  70377. };
  70378. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70379. get: function () {
  70380. return this._leftStick;
  70381. },
  70382. set: function (newValues) {
  70383. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70384. this._onleftstickchanged(newValues);
  70385. }
  70386. this._leftStick = newValues;
  70387. },
  70388. enumerable: true,
  70389. configurable: true
  70390. });
  70391. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70392. get: function () {
  70393. return this._rightStick;
  70394. },
  70395. set: function (newValues) {
  70396. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70397. this._onrightstickchanged(newValues);
  70398. }
  70399. this._rightStick = newValues;
  70400. },
  70401. enumerable: true,
  70402. configurable: true
  70403. });
  70404. Gamepad.prototype.update = function () {
  70405. if (this._leftStick) {
  70406. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70407. if (this._invertLeftStickY) {
  70408. this.leftStick.y *= -1;
  70409. }
  70410. }
  70411. if (this._rightStick) {
  70412. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70413. }
  70414. };
  70415. Gamepad.prototype.dispose = function () {
  70416. };
  70417. Gamepad.GAMEPAD = 0;
  70418. Gamepad.GENERIC = 1;
  70419. Gamepad.XBOX = 2;
  70420. Gamepad.POSE_ENABLED = 3;
  70421. return Gamepad;
  70422. }());
  70423. BABYLON.Gamepad = Gamepad;
  70424. var GenericPad = /** @class */ (function (_super) {
  70425. __extends(GenericPad, _super);
  70426. function GenericPad(id, index, browserGamepad) {
  70427. var _this = _super.call(this, id, index, browserGamepad) || this;
  70428. _this.onButtonDownObservable = new BABYLON.Observable();
  70429. _this.onButtonUpObservable = new BABYLON.Observable();
  70430. _this.type = Gamepad.GENERIC;
  70431. _this._buttons = new Array(browserGamepad.buttons.length);
  70432. return _this;
  70433. }
  70434. GenericPad.prototype.onbuttondown = function (callback) {
  70435. this._onbuttondown = callback;
  70436. };
  70437. GenericPad.prototype.onbuttonup = function (callback) {
  70438. this._onbuttonup = callback;
  70439. };
  70440. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70441. if (newValue !== currentValue) {
  70442. if (newValue === 1) {
  70443. if (this._onbuttondown) {
  70444. this._onbuttondown(buttonIndex);
  70445. }
  70446. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70447. }
  70448. if (newValue === 0) {
  70449. if (this._onbuttonup) {
  70450. this._onbuttonup(buttonIndex);
  70451. }
  70452. this.onButtonUpObservable.notifyObservers(buttonIndex);
  70453. }
  70454. }
  70455. return newValue;
  70456. };
  70457. GenericPad.prototype.update = function () {
  70458. _super.prototype.update.call(this);
  70459. for (var index = 0; index < this._buttons.length; index++) {
  70460. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  70461. }
  70462. };
  70463. GenericPad.prototype.dispose = function () {
  70464. _super.prototype.dispose.call(this);
  70465. this.onButtonDownObservable.clear();
  70466. this.onButtonUpObservable.clear();
  70467. };
  70468. return GenericPad;
  70469. }(Gamepad));
  70470. BABYLON.GenericPad = GenericPad;
  70471. })(BABYLON || (BABYLON = {}));
  70472. //# sourceMappingURL=babylon.gamepad.js.map
  70473. var BABYLON;
  70474. (function (BABYLON) {
  70475. /**
  70476. * Defines supported buttons for XBox360 compatible gamepads
  70477. */
  70478. var Xbox360Button;
  70479. (function (Xbox360Button) {
  70480. /** A */
  70481. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  70482. /** B */
  70483. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  70484. /** X */
  70485. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  70486. /** Y */
  70487. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  70488. /** Start */
  70489. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  70490. /** Back */
  70491. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  70492. /** Left button */
  70493. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  70494. /** Right button */
  70495. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  70496. /** Left stick */
  70497. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  70498. /** Right stick */
  70499. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  70500. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  70501. /** Defines values for XBox360 DPad */
  70502. var Xbox360Dpad;
  70503. (function (Xbox360Dpad) {
  70504. /** Up */
  70505. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  70506. /** Down */
  70507. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  70508. /** Left */
  70509. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  70510. /** Right */
  70511. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  70512. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  70513. /**
  70514. * Defines a XBox360 gamepad
  70515. */
  70516. var Xbox360Pad = /** @class */ (function (_super) {
  70517. __extends(Xbox360Pad, _super);
  70518. /**
  70519. * Creates a new XBox360 gamepad object
  70520. * @param id defines the id of this gamepad
  70521. * @param index defines its index
  70522. * @param gamepad defines the internal HTML gamepad object
  70523. * @param xboxOne defines if it is a XBox One gamepad
  70524. */
  70525. function Xbox360Pad(id, index, gamepad, xboxOne) {
  70526. if (xboxOne === void 0) { xboxOne = false; }
  70527. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  70528. _this._leftTrigger = 0;
  70529. _this._rightTrigger = 0;
  70530. /** Observable raised when a button is pressed */
  70531. _this.onButtonDownObservable = new BABYLON.Observable();
  70532. /** Observable raised when a button is released */
  70533. _this.onButtonUpObservable = new BABYLON.Observable();
  70534. /** Observable raised when a pad is pressed */
  70535. _this.onPadDownObservable = new BABYLON.Observable();
  70536. /** Observable raised when a pad is released */
  70537. _this.onPadUpObservable = new BABYLON.Observable();
  70538. _this._buttonA = 0;
  70539. _this._buttonB = 0;
  70540. _this._buttonX = 0;
  70541. _this._buttonY = 0;
  70542. _this._buttonBack = 0;
  70543. _this._buttonStart = 0;
  70544. _this._buttonLB = 0;
  70545. _this._buttonRB = 0;
  70546. _this._buttonLeftStick = 0;
  70547. _this._buttonRightStick = 0;
  70548. _this._dPadUp = 0;
  70549. _this._dPadDown = 0;
  70550. _this._dPadLeft = 0;
  70551. _this._dPadRight = 0;
  70552. _this._isXboxOnePad = false;
  70553. _this.type = BABYLON.Gamepad.XBOX;
  70554. _this._isXboxOnePad = xboxOne;
  70555. return _this;
  70556. }
  70557. /**
  70558. * Defines the callback to call when left trigger is pressed
  70559. * @param callback defines the callback to use
  70560. */
  70561. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  70562. this._onlefttriggerchanged = callback;
  70563. };
  70564. /**
  70565. * Defines the callback to call when right trigger is pressed
  70566. * @param callback defines the callback to use
  70567. */
  70568. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  70569. this._onrighttriggerchanged = callback;
  70570. };
  70571. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  70572. /**
  70573. * Gets or sets left trigger value
  70574. */
  70575. get: function () {
  70576. return this._leftTrigger;
  70577. },
  70578. set: function (newValue) {
  70579. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  70580. this._onlefttriggerchanged(newValue);
  70581. }
  70582. this._leftTrigger = newValue;
  70583. },
  70584. enumerable: true,
  70585. configurable: true
  70586. });
  70587. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  70588. /**
  70589. * Gets or sets right trigger value
  70590. */
  70591. get: function () {
  70592. return this._rightTrigger;
  70593. },
  70594. set: function (newValue) {
  70595. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  70596. this._onrighttriggerchanged(newValue);
  70597. }
  70598. this._rightTrigger = newValue;
  70599. },
  70600. enumerable: true,
  70601. configurable: true
  70602. });
  70603. /**
  70604. * Defines the callback to call when a button is pressed
  70605. * @param callback defines the callback to use
  70606. */
  70607. Xbox360Pad.prototype.onbuttondown = function (callback) {
  70608. this._onbuttondown = callback;
  70609. };
  70610. /**
  70611. * Defines the callback to call when a button is released
  70612. * @param callback defines the callback to use
  70613. */
  70614. Xbox360Pad.prototype.onbuttonup = function (callback) {
  70615. this._onbuttonup = callback;
  70616. };
  70617. /**
  70618. * Defines the callback to call when a pad is pressed
  70619. * @param callback defines the callback to use
  70620. */
  70621. Xbox360Pad.prototype.ondpaddown = function (callback) {
  70622. this._ondpaddown = callback;
  70623. };
  70624. /**
  70625. * Defines the callback to call when a pad is released
  70626. * @param callback defines the callback to use
  70627. */
  70628. Xbox360Pad.prototype.ondpadup = function (callback) {
  70629. this._ondpadup = callback;
  70630. };
  70631. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  70632. if (newValue !== currentValue) {
  70633. if (newValue === 1) {
  70634. if (this._onbuttondown) {
  70635. this._onbuttondown(buttonType);
  70636. }
  70637. this.onButtonDownObservable.notifyObservers(buttonType);
  70638. }
  70639. if (newValue === 0) {
  70640. if (this._onbuttonup) {
  70641. this._onbuttonup(buttonType);
  70642. }
  70643. this.onButtonUpObservable.notifyObservers(buttonType);
  70644. }
  70645. }
  70646. return newValue;
  70647. };
  70648. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  70649. if (newValue !== currentValue) {
  70650. if (newValue === 1) {
  70651. if (this._ondpaddown) {
  70652. this._ondpaddown(buttonType);
  70653. }
  70654. this.onPadDownObservable.notifyObservers(buttonType);
  70655. }
  70656. if (newValue === 0) {
  70657. if (this._ondpadup) {
  70658. this._ondpadup(buttonType);
  70659. }
  70660. this.onPadUpObservable.notifyObservers(buttonType);
  70661. }
  70662. }
  70663. return newValue;
  70664. };
  70665. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  70666. /** Gets or sets value of A button */
  70667. get: function () {
  70668. return this._buttonA;
  70669. },
  70670. set: function (value) {
  70671. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  70672. },
  70673. enumerable: true,
  70674. configurable: true
  70675. });
  70676. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  70677. /** Gets or sets value of B button */
  70678. get: function () {
  70679. return this._buttonB;
  70680. },
  70681. set: function (value) {
  70682. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  70683. },
  70684. enumerable: true,
  70685. configurable: true
  70686. });
  70687. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  70688. /** Gets or sets value of X button */
  70689. get: function () {
  70690. return this._buttonX;
  70691. },
  70692. set: function (value) {
  70693. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  70694. },
  70695. enumerable: true,
  70696. configurable: true
  70697. });
  70698. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  70699. /** Gets or sets value of Y button */
  70700. get: function () {
  70701. return this._buttonY;
  70702. },
  70703. set: function (value) {
  70704. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  70705. },
  70706. enumerable: true,
  70707. configurable: true
  70708. });
  70709. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  70710. /** Gets or sets value of Start button */
  70711. get: function () {
  70712. return this._buttonStart;
  70713. },
  70714. set: function (value) {
  70715. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  70716. },
  70717. enumerable: true,
  70718. configurable: true
  70719. });
  70720. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  70721. /** Gets or sets value of Back button */
  70722. get: function () {
  70723. return this._buttonBack;
  70724. },
  70725. set: function (value) {
  70726. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  70727. },
  70728. enumerable: true,
  70729. configurable: true
  70730. });
  70731. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  70732. /** Gets or sets value of Left button */
  70733. get: function () {
  70734. return this._buttonLB;
  70735. },
  70736. set: function (value) {
  70737. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  70738. },
  70739. enumerable: true,
  70740. configurable: true
  70741. });
  70742. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  70743. /** Gets or sets value of Right button */
  70744. get: function () {
  70745. return this._buttonRB;
  70746. },
  70747. set: function (value) {
  70748. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  70749. },
  70750. enumerable: true,
  70751. configurable: true
  70752. });
  70753. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  70754. /** Gets or sets value of left stick */
  70755. get: function () {
  70756. return this._buttonLeftStick;
  70757. },
  70758. set: function (value) {
  70759. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  70760. },
  70761. enumerable: true,
  70762. configurable: true
  70763. });
  70764. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  70765. /** Gets or sets value of right stick */
  70766. get: function () {
  70767. return this._buttonRightStick;
  70768. },
  70769. set: function (value) {
  70770. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  70771. },
  70772. enumerable: true,
  70773. configurable: true
  70774. });
  70775. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  70776. /** Gets or sets value of DPad up */
  70777. get: function () {
  70778. return this._dPadUp;
  70779. },
  70780. set: function (value) {
  70781. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  70782. },
  70783. enumerable: true,
  70784. configurable: true
  70785. });
  70786. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  70787. /** Gets or sets value of DPad down */
  70788. get: function () {
  70789. return this._dPadDown;
  70790. },
  70791. set: function (value) {
  70792. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  70793. },
  70794. enumerable: true,
  70795. configurable: true
  70796. });
  70797. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  70798. /** Gets or sets value of DPad left */
  70799. get: function () {
  70800. return this._dPadLeft;
  70801. },
  70802. set: function (value) {
  70803. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  70804. },
  70805. enumerable: true,
  70806. configurable: true
  70807. });
  70808. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  70809. /** Gets or sets value of DPad right */
  70810. get: function () {
  70811. return this._dPadRight;
  70812. },
  70813. set: function (value) {
  70814. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  70815. },
  70816. enumerable: true,
  70817. configurable: true
  70818. });
  70819. /**
  70820. * Force the gamepad to synchronize with device values
  70821. */
  70822. Xbox360Pad.prototype.update = function () {
  70823. _super.prototype.update.call(this);
  70824. if (this._isXboxOnePad) {
  70825. this.buttonA = this.browserGamepad.buttons[0].value;
  70826. this.buttonB = this.browserGamepad.buttons[1].value;
  70827. this.buttonX = this.browserGamepad.buttons[2].value;
  70828. this.buttonY = this.browserGamepad.buttons[3].value;
  70829. this.buttonLB = this.browserGamepad.buttons[4].value;
  70830. this.buttonRB = this.browserGamepad.buttons[5].value;
  70831. this.leftTrigger = this.browserGamepad.axes[2];
  70832. this.rightTrigger = this.browserGamepad.axes[5];
  70833. this.buttonBack = this.browserGamepad.buttons[9].value;
  70834. this.buttonStart = this.browserGamepad.buttons[8].value;
  70835. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  70836. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  70837. this.dPadUp = this.browserGamepad.buttons[11].value;
  70838. this.dPadDown = this.browserGamepad.buttons[12].value;
  70839. this.dPadLeft = this.browserGamepad.buttons[13].value;
  70840. this.dPadRight = this.browserGamepad.buttons[14].value;
  70841. }
  70842. else {
  70843. this.buttonA = this.browserGamepad.buttons[0].value;
  70844. this.buttonB = this.browserGamepad.buttons[1].value;
  70845. this.buttonX = this.browserGamepad.buttons[2].value;
  70846. this.buttonY = this.browserGamepad.buttons[3].value;
  70847. this.buttonLB = this.browserGamepad.buttons[4].value;
  70848. this.buttonRB = this.browserGamepad.buttons[5].value;
  70849. this.leftTrigger = this.browserGamepad.buttons[6].value;
  70850. this.rightTrigger = this.browserGamepad.buttons[7].value;
  70851. this.buttonBack = this.browserGamepad.buttons[8].value;
  70852. this.buttonStart = this.browserGamepad.buttons[9].value;
  70853. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  70854. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  70855. this.dPadUp = this.browserGamepad.buttons[12].value;
  70856. this.dPadDown = this.browserGamepad.buttons[13].value;
  70857. this.dPadLeft = this.browserGamepad.buttons[14].value;
  70858. this.dPadRight = this.browserGamepad.buttons[15].value;
  70859. }
  70860. };
  70861. Xbox360Pad.prototype.dispose = function () {
  70862. _super.prototype.dispose.call(this);
  70863. this.onButtonDownObservable.clear();
  70864. this.onButtonUpObservable.clear();
  70865. this.onPadDownObservable.clear();
  70866. this.onPadUpObservable.clear();
  70867. };
  70868. return Xbox360Pad;
  70869. }(BABYLON.Gamepad));
  70870. BABYLON.Xbox360Pad = Xbox360Pad;
  70871. })(BABYLON || (BABYLON = {}));
  70872. //# sourceMappingURL=babylon.xboxGamepad.js.map
  70873. var BABYLON;
  70874. (function (BABYLON) {
  70875. /**
  70876. * Defines the types of pose enabled controllers that are supported
  70877. */
  70878. var PoseEnabledControllerType;
  70879. (function (PoseEnabledControllerType) {
  70880. /**
  70881. * HTC Vive
  70882. */
  70883. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  70884. /**
  70885. * Oculus Rift
  70886. */
  70887. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  70888. /**
  70889. * Windows mixed reality
  70890. */
  70891. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  70892. /**
  70893. * Samsung gear VR
  70894. */
  70895. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  70896. /**
  70897. * Google Daydream
  70898. */
  70899. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  70900. /**
  70901. * Generic
  70902. */
  70903. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  70904. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  70905. /**
  70906. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70907. */
  70908. var PoseEnabledControllerHelper = /** @class */ (function () {
  70909. function PoseEnabledControllerHelper() {
  70910. }
  70911. /**
  70912. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70913. * @param vrGamepad the gamepad to initialized
  70914. * @returns a vr controller of the type the gamepad identified as
  70915. */
  70916. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  70917. // Oculus Touch
  70918. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  70919. return new BABYLON.OculusTouchController(vrGamepad);
  70920. }
  70921. // Windows Mixed Reality controllers
  70922. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  70923. return new BABYLON.WindowsMotionController(vrGamepad);
  70924. }
  70925. // HTC Vive
  70926. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  70927. return new BABYLON.ViveController(vrGamepad);
  70928. }
  70929. // Samsung/Oculus Gear VR
  70930. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  70931. return new BABYLON.GearVRController(vrGamepad);
  70932. }
  70933. // Google Daydream
  70934. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  70935. return new BABYLON.DaydreamController(vrGamepad);
  70936. }
  70937. // Generic
  70938. else {
  70939. return new BABYLON.GenericController(vrGamepad);
  70940. }
  70941. };
  70942. return PoseEnabledControllerHelper;
  70943. }());
  70944. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  70945. /**
  70946. * Defines the PoseEnabledController object that contains state of a vr capable controller
  70947. */
  70948. var PoseEnabledController = /** @class */ (function (_super) {
  70949. __extends(PoseEnabledController, _super);
  70950. /**
  70951. * Creates a new PoseEnabledController from a gamepad
  70952. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  70953. */
  70954. function PoseEnabledController(browserGamepad) {
  70955. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  70956. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  70957. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  70958. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  70959. /**
  70960. * The device position in babylon space
  70961. */
  70962. _this.devicePosition = BABYLON.Vector3.Zero();
  70963. /**
  70964. * The device rotation in babylon space
  70965. */
  70966. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  70967. /**
  70968. * The scale factor of the device in babylon space
  70969. */
  70970. _this.deviceScaleFactor = 1;
  70971. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  70972. /**
  70973. * Internal, matrix used to convert room space to babylon space
  70974. */
  70975. _this._deviceToWorld = BABYLON.Matrix.Identity();
  70976. /**
  70977. * Node to be used when casting a ray from the controller
  70978. */
  70979. _this._pointingPoseNode = null;
  70980. _this._workingMatrix = BABYLON.Matrix.Identity();
  70981. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  70982. _this.controllerType = PoseEnabledControllerType.GENERIC;
  70983. _this.position = BABYLON.Vector3.Zero();
  70984. _this.rotationQuaternion = new BABYLON.Quaternion();
  70985. _this._calculatedPosition = BABYLON.Vector3.Zero();
  70986. _this._calculatedRotation = new BABYLON.Quaternion();
  70987. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  70988. return _this;
  70989. }
  70990. /**
  70991. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  70992. */
  70993. PoseEnabledController.prototype.update = function () {
  70994. _super.prototype.update.call(this);
  70995. var pose = this.browserGamepad.pose;
  70996. this.updateFromDevice(pose);
  70997. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  70998. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  70999. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71000. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71001. if (this._mesh) {
  71002. this._mesh.position.copyFrom(this.devicePosition);
  71003. if (this._mesh.rotationQuaternion) {
  71004. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71005. }
  71006. }
  71007. };
  71008. /**
  71009. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71010. * @param poseData raw pose fromthe device
  71011. */
  71012. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71013. if (poseData) {
  71014. this.rawPose = poseData;
  71015. if (poseData.position) {
  71016. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71017. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71018. this._deviceRoomPosition.z *= -1;
  71019. }
  71020. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71021. this._calculatedPosition.addInPlace(this.position);
  71022. }
  71023. var pose = this.rawPose;
  71024. if (poseData.orientation && pose.orientation) {
  71025. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71026. if (this._mesh) {
  71027. if (this._mesh.getScene().useRightHandedSystem) {
  71028. this._deviceRoomRotationQuaternion.z *= -1;
  71029. this._deviceRoomRotationQuaternion.w *= -1;
  71030. }
  71031. else {
  71032. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71033. }
  71034. }
  71035. // if the camera is set, rotate to the camera's rotation
  71036. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71037. }
  71038. }
  71039. };
  71040. /**
  71041. * Attaches a mesh to the controller
  71042. * @param mesh the mesh to be attached
  71043. */
  71044. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71045. if (this._mesh) {
  71046. this._mesh.parent = null;
  71047. }
  71048. this._mesh = mesh;
  71049. if (this._poseControlledCamera) {
  71050. this._mesh.parent = this._poseControlledCamera;
  71051. }
  71052. if (!this._mesh.rotationQuaternion) {
  71053. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71054. }
  71055. };
  71056. /**
  71057. * Attaches the controllers mesh to a camera
  71058. * @param camera the camera the mesh should be attached to
  71059. */
  71060. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71061. this._poseControlledCamera = camera;
  71062. if (this._mesh) {
  71063. this._mesh.parent = this._poseControlledCamera;
  71064. }
  71065. };
  71066. /**
  71067. * Disposes of the controller
  71068. */
  71069. PoseEnabledController.prototype.dispose = function () {
  71070. if (this._mesh) {
  71071. this._mesh.dispose();
  71072. }
  71073. this._mesh = null;
  71074. _super.prototype.dispose.call(this);
  71075. };
  71076. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71077. /**
  71078. * The mesh that is attached to the controller
  71079. */
  71080. get: function () {
  71081. return this._mesh;
  71082. },
  71083. enumerable: true,
  71084. configurable: true
  71085. });
  71086. /**
  71087. * Gets the ray of the controller in the direction the controller is pointing
  71088. * @param length the length the resulting ray should be
  71089. * @returns a ray in the direction the controller is pointing
  71090. */
  71091. PoseEnabledController.prototype.getForwardRay = function (length) {
  71092. if (length === void 0) { length = 100; }
  71093. if (!this.mesh) {
  71094. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71095. }
  71096. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71097. var origin = m.getTranslation();
  71098. var forward = new BABYLON.Vector3(0, 0, -1);
  71099. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71100. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71101. return new BABYLON.Ray(origin, direction, length);
  71102. };
  71103. /**
  71104. * Name of the child mesh that can be used to cast a ray from the controller
  71105. */
  71106. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71107. return PoseEnabledController;
  71108. }(BABYLON.Gamepad));
  71109. BABYLON.PoseEnabledController = PoseEnabledController;
  71110. })(BABYLON || (BABYLON = {}));
  71111. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71112. var BABYLON;
  71113. (function (BABYLON) {
  71114. /**
  71115. * Defines the WebVRController object that represents controllers tracked in 3D space
  71116. */
  71117. var WebVRController = /** @class */ (function (_super) {
  71118. __extends(WebVRController, _super);
  71119. /**
  71120. * Creates a new WebVRController from a gamepad
  71121. * @param vrGamepad the gamepad that the WebVRController should be created from
  71122. */
  71123. function WebVRController(vrGamepad) {
  71124. var _this = _super.call(this, vrGamepad) || this;
  71125. // Observables
  71126. /**
  71127. * Fired when the trigger state has changed
  71128. */
  71129. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71130. /**
  71131. * Fired when the main button state has changed
  71132. */
  71133. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71134. /**
  71135. * Fired when the secondary button state has changed
  71136. */
  71137. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71138. /**
  71139. * Fired when the pad state has changed
  71140. */
  71141. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71142. /**
  71143. * Fired when controllers stick values have changed
  71144. */
  71145. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71146. /**
  71147. * X and Y axis corrisponding to the controllers joystick
  71148. */
  71149. _this.pad = { x: 0, y: 0 };
  71150. // avoid GC, store state in a tmp object
  71151. _this._changes = {
  71152. pressChanged: false,
  71153. touchChanged: false,
  71154. valueChanged: false,
  71155. changed: false
  71156. };
  71157. _this._buttons = new Array(vrGamepad.buttons.length);
  71158. _this.hand = vrGamepad.hand;
  71159. return _this;
  71160. }
  71161. /**
  71162. * Fired when a controller button's state has changed
  71163. * @param callback the callback containing the button that was modified
  71164. */
  71165. WebVRController.prototype.onButtonStateChange = function (callback) {
  71166. this._onButtonStateChange = callback;
  71167. };
  71168. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71169. /**
  71170. * The default controller model for the controller
  71171. */
  71172. get: function () {
  71173. return this._defaultModel;
  71174. },
  71175. enumerable: true,
  71176. configurable: true
  71177. });
  71178. /**
  71179. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71180. */
  71181. WebVRController.prototype.update = function () {
  71182. _super.prototype.update.call(this);
  71183. for (var index = 0; index < this._buttons.length; index++) {
  71184. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71185. }
  71186. ;
  71187. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71188. this.pad.x = this.leftStick.x;
  71189. this.pad.y = this.leftStick.y;
  71190. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71191. }
  71192. };
  71193. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71194. if (!newState) {
  71195. newState = {
  71196. pressed: false,
  71197. touched: false,
  71198. value: 0
  71199. };
  71200. }
  71201. if (!currentState) {
  71202. this._buttons[buttonIndex] = {
  71203. pressed: newState.pressed,
  71204. touched: newState.touched,
  71205. value: newState.value
  71206. };
  71207. return;
  71208. }
  71209. this._checkChanges(newState, currentState);
  71210. if (this._changes.changed) {
  71211. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71212. this._handleButtonChange(buttonIndex, newState, this._changes);
  71213. }
  71214. this._buttons[buttonIndex].pressed = newState.pressed;
  71215. this._buttons[buttonIndex].touched = newState.touched;
  71216. // oculus triggers are never 0, thou not touched.
  71217. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71218. };
  71219. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71220. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71221. this._changes.touchChanged = newState.touched !== currentState.touched;
  71222. this._changes.valueChanged = newState.value !== currentState.value;
  71223. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71224. return this._changes;
  71225. };
  71226. /**
  71227. * Disposes of th webVRCOntroller
  71228. */
  71229. WebVRController.prototype.dispose = function () {
  71230. _super.prototype.dispose.call(this);
  71231. this.onTriggerStateChangedObservable.clear();
  71232. this.onMainButtonStateChangedObservable.clear();
  71233. this.onSecondaryButtonStateChangedObservable.clear();
  71234. this.onPadStateChangedObservable.clear();
  71235. this.onPadValuesChangedObservable.clear();
  71236. };
  71237. return WebVRController;
  71238. }(BABYLON.PoseEnabledController));
  71239. BABYLON.WebVRController = WebVRController;
  71240. })(BABYLON || (BABYLON = {}));
  71241. //# sourceMappingURL=babylon.webVRController.js.map
  71242. var BABYLON;
  71243. (function (BABYLON) {
  71244. /**
  71245. * Oculus Touch Controller
  71246. */
  71247. var OculusTouchController = /** @class */ (function (_super) {
  71248. __extends(OculusTouchController, _super);
  71249. /**
  71250. * Creates a new OculusTouchController from a gamepad
  71251. * @param vrGamepad the gamepad that the controller should be created from
  71252. */
  71253. function OculusTouchController(vrGamepad) {
  71254. var _this = _super.call(this, vrGamepad) || this;
  71255. /**
  71256. * Fired when the secondary trigger on this controller is modified
  71257. */
  71258. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71259. /**
  71260. * Fired when the thumb rest on this controller is modified
  71261. */
  71262. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71263. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71264. return _this;
  71265. }
  71266. /**
  71267. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71268. * @param scene scene in which to add meshes
  71269. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71270. */
  71271. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71272. var _this = this;
  71273. var meshName;
  71274. // Hand
  71275. if (this.hand === 'left') {
  71276. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71277. }
  71278. else { // Right is the default if no hand is specified
  71279. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71280. }
  71281. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71282. /*
  71283. Parent Mesh name: oculus_touch_left
  71284. - body
  71285. - trigger
  71286. - thumbstick
  71287. - grip
  71288. - button_y
  71289. - button_x
  71290. - button_enter
  71291. */
  71292. _this._defaultModel = newMeshes[1];
  71293. _this.attachToMesh(_this._defaultModel);
  71294. if (meshLoaded) {
  71295. meshLoaded(_this._defaultModel);
  71296. }
  71297. });
  71298. };
  71299. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71300. /**
  71301. * Fired when the A button on this controller is modified
  71302. */
  71303. get: function () {
  71304. if (this.hand === 'right') {
  71305. return this.onMainButtonStateChangedObservable;
  71306. }
  71307. else {
  71308. throw new Error('No A button on left hand');
  71309. }
  71310. },
  71311. enumerable: true,
  71312. configurable: true
  71313. });
  71314. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71315. /**
  71316. * Fired when the B button on this controller is modified
  71317. */
  71318. get: function () {
  71319. if (this.hand === 'right') {
  71320. return this.onSecondaryButtonStateChangedObservable;
  71321. }
  71322. else {
  71323. throw new Error('No B button on left hand');
  71324. }
  71325. },
  71326. enumerable: true,
  71327. configurable: true
  71328. });
  71329. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71330. /**
  71331. * Fired when the X button on this controller is modified
  71332. */
  71333. get: function () {
  71334. if (this.hand === 'left') {
  71335. return this.onMainButtonStateChangedObservable;
  71336. }
  71337. else {
  71338. throw new Error('No X button on right hand');
  71339. }
  71340. },
  71341. enumerable: true,
  71342. configurable: true
  71343. });
  71344. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71345. /**
  71346. * Fired when the Y button on this controller is modified
  71347. */
  71348. get: function () {
  71349. if (this.hand === 'left') {
  71350. return this.onSecondaryButtonStateChangedObservable;
  71351. }
  71352. else {
  71353. throw new Error('No Y button on right hand');
  71354. }
  71355. },
  71356. enumerable: true,
  71357. configurable: true
  71358. });
  71359. /**
  71360. * Called once for each button that changed state since the last frame
  71361. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71362. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71363. * 2) secondary trigger (same)
  71364. * 3) A (right) X (left), touch, pressed = value
  71365. * 4) B / Y
  71366. * 5) thumb rest
  71367. * @param buttonIdx Which button index changed
  71368. * @param state New state of the button
  71369. * @param changes Which properties on the state changed since last frame
  71370. */
  71371. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71372. var notifyObject = state; //{ state: state, changes: changes };
  71373. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71374. switch (buttonIdx) {
  71375. case 0:
  71376. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71377. return;
  71378. case 1: // index trigger
  71379. if (this._defaultModel) {
  71380. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71381. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71382. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71383. }
  71384. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71385. return;
  71386. case 2: // secondary trigger
  71387. if (this._defaultModel) {
  71388. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71389. }
  71390. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71391. return;
  71392. case 3:
  71393. if (this._defaultModel) {
  71394. if (notifyObject.pressed) {
  71395. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71396. }
  71397. else {
  71398. (this._defaultModel.getChildren()[1]).position.y = 0;
  71399. }
  71400. }
  71401. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71402. return;
  71403. case 4:
  71404. if (this._defaultModel) {
  71405. if (notifyObject.pressed) {
  71406. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71407. }
  71408. else {
  71409. (this._defaultModel.getChildren()[2]).position.y = 0;
  71410. }
  71411. }
  71412. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71413. return;
  71414. case 5:
  71415. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71416. return;
  71417. }
  71418. };
  71419. /**
  71420. * Base Url for the controller model.
  71421. */
  71422. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71423. /**
  71424. * File name for the left controller model.
  71425. */
  71426. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71427. /**
  71428. * File name for the right controller model.
  71429. */
  71430. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71431. return OculusTouchController;
  71432. }(BABYLON.WebVRController));
  71433. BABYLON.OculusTouchController = OculusTouchController;
  71434. })(BABYLON || (BABYLON = {}));
  71435. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71436. var BABYLON;
  71437. (function (BABYLON) {
  71438. /**
  71439. * Vive Controller
  71440. */
  71441. var ViveController = /** @class */ (function (_super) {
  71442. __extends(ViveController, _super);
  71443. /**
  71444. * Creates a new ViveController from a gamepad
  71445. * @param vrGamepad the gamepad that the controller should be created from
  71446. */
  71447. function ViveController(vrGamepad) {
  71448. var _this = _super.call(this, vrGamepad) || this;
  71449. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  71450. _this._invertLeftStickY = true;
  71451. return _this;
  71452. }
  71453. /**
  71454. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71455. * @param scene scene in which to add meshes
  71456. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71457. */
  71458. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71459. var _this = this;
  71460. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  71461. /*
  71462. Parent Mesh name: ViveWand
  71463. - body
  71464. - r_gripper
  71465. - l_gripper
  71466. - menu_button
  71467. - system_button
  71468. - trackpad
  71469. - trigger
  71470. - LED
  71471. */
  71472. _this._defaultModel = newMeshes[1];
  71473. _this.attachToMesh(_this._defaultModel);
  71474. if (meshLoaded) {
  71475. meshLoaded(_this._defaultModel);
  71476. }
  71477. });
  71478. };
  71479. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  71480. /**
  71481. * Fired when the left button on this controller is modified
  71482. */
  71483. get: function () {
  71484. return this.onMainButtonStateChangedObservable;
  71485. },
  71486. enumerable: true,
  71487. configurable: true
  71488. });
  71489. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  71490. /**
  71491. * Fired when the right button on this controller is modified
  71492. */
  71493. get: function () {
  71494. return this.onMainButtonStateChangedObservable;
  71495. },
  71496. enumerable: true,
  71497. configurable: true
  71498. });
  71499. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  71500. /**
  71501. * Fired when the menu button on this controller is modified
  71502. */
  71503. get: function () {
  71504. return this.onSecondaryButtonStateChangedObservable;
  71505. },
  71506. enumerable: true,
  71507. configurable: true
  71508. });
  71509. /**
  71510. * Called once for each button that changed state since the last frame
  71511. * Vive mapping:
  71512. * 0: touchpad
  71513. * 1: trigger
  71514. * 2: left AND right buttons
  71515. * 3: menu button
  71516. * @param buttonIdx Which button index changed
  71517. * @param state New state of the button
  71518. * @param changes Which properties on the state changed since last frame
  71519. */
  71520. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71521. var notifyObject = state; //{ state: state, changes: changes };
  71522. switch (buttonIdx) {
  71523. case 0:
  71524. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71525. return;
  71526. case 1: // index trigger
  71527. if (this._defaultModel) {
  71528. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  71529. }
  71530. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71531. return;
  71532. case 2: // left AND right button
  71533. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71534. return;
  71535. case 3:
  71536. if (this._defaultModel) {
  71537. if (notifyObject.pressed) {
  71538. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71539. }
  71540. else {
  71541. (this._defaultModel.getChildren()[2]).position.y = 0;
  71542. }
  71543. }
  71544. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71545. return;
  71546. }
  71547. };
  71548. /**
  71549. * Base Url for the controller model.
  71550. */
  71551. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  71552. /**
  71553. * File name for the controller model.
  71554. */
  71555. ViveController.MODEL_FILENAME = 'wand.babylon';
  71556. return ViveController;
  71557. }(BABYLON.WebVRController));
  71558. BABYLON.ViveController = ViveController;
  71559. })(BABYLON || (BABYLON = {}));
  71560. //# sourceMappingURL=babylon.viveController.js.map
  71561. var BABYLON;
  71562. (function (BABYLON) {
  71563. /**
  71564. * Generic Controller
  71565. */
  71566. var GenericController = /** @class */ (function (_super) {
  71567. __extends(GenericController, _super);
  71568. /**
  71569. * Creates a new GenericController from a gamepad
  71570. * @param vrGamepad the gamepad that the controller should be created from
  71571. */
  71572. function GenericController(vrGamepad) {
  71573. return _super.call(this, vrGamepad) || this;
  71574. }
  71575. /**
  71576. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71577. * @param scene scene in which to add meshes
  71578. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71579. */
  71580. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71581. var _this = this;
  71582. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  71583. _this._defaultModel = newMeshes[1];
  71584. _this.attachToMesh(_this._defaultModel);
  71585. if (meshLoaded) {
  71586. meshLoaded(_this._defaultModel);
  71587. }
  71588. });
  71589. };
  71590. /**
  71591. * Called once for each button that changed state since the last frame
  71592. * @param buttonIdx Which button index changed
  71593. * @param state New state of the button
  71594. * @param changes Which properties on the state changed since last frame
  71595. */
  71596. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71597. console.log("Button id: " + buttonIdx + "state: ");
  71598. console.dir(state);
  71599. };
  71600. /**
  71601. * Base Url for the controller model.
  71602. */
  71603. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71604. /**
  71605. * File name for the controller model.
  71606. */
  71607. GenericController.MODEL_FILENAME = 'generic.babylon';
  71608. return GenericController;
  71609. }(BABYLON.WebVRController));
  71610. BABYLON.GenericController = GenericController;
  71611. })(BABYLON || (BABYLON = {}));
  71612. //# sourceMappingURL=babylon.genericController.js.map
  71613. var BABYLON;
  71614. (function (BABYLON) {
  71615. /**
  71616. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  71617. */
  71618. var LoadedMeshInfo = /** @class */ (function () {
  71619. function LoadedMeshInfo() {
  71620. /**
  71621. * Map of the button meshes contained in the controller
  71622. */
  71623. this.buttonMeshes = {};
  71624. /**
  71625. * Map of the axis meshes contained in the controller
  71626. */
  71627. this.axisMeshes = {};
  71628. }
  71629. return LoadedMeshInfo;
  71630. }());
  71631. /**
  71632. * Defines the WindowsMotionController object that the state of the windows motion controller
  71633. */
  71634. var WindowsMotionController = /** @class */ (function (_super) {
  71635. __extends(WindowsMotionController, _super);
  71636. /**
  71637. * Creates a new WindowsMotionController from a gamepad
  71638. * @param vrGamepad the gamepad that the controller should be created from
  71639. */
  71640. function WindowsMotionController(vrGamepad) {
  71641. var _this = _super.call(this, vrGamepad) || this;
  71642. _this._mapping = {
  71643. // Semantic button names
  71644. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  71645. // A mapping of the button name to glTF model node name
  71646. // that should be transformed by button value.
  71647. buttonMeshNames: {
  71648. 'trigger': 'SELECT',
  71649. 'menu': 'MENU',
  71650. 'grip': 'GRASP',
  71651. 'thumbstick': 'THUMBSTICK_PRESS',
  71652. 'trackpad': 'TOUCHPAD_PRESS'
  71653. },
  71654. // This mapping is used to translate from the Motion Controller to Babylon semantics
  71655. buttonObservableNames: {
  71656. 'trigger': 'onTriggerStateChangedObservable',
  71657. 'menu': 'onSecondaryButtonStateChangedObservable',
  71658. 'grip': 'onMainButtonStateChangedObservable',
  71659. 'thumbstick': 'onPadStateChangedObservable',
  71660. 'trackpad': 'onTrackpadChangedObservable'
  71661. },
  71662. // A mapping of the axis name to glTF model node name
  71663. // that should be transformed by axis value.
  71664. // This array mirrors the browserGamepad.axes array, such that
  71665. // the mesh corresponding to axis 0 is in this array index 0.
  71666. axisMeshNames: [
  71667. 'THUMBSTICK_X',
  71668. 'THUMBSTICK_Y',
  71669. 'TOUCHPAD_TOUCH_X',
  71670. 'TOUCHPAD_TOUCH_Y'
  71671. ],
  71672. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  71673. };
  71674. /**
  71675. * Fired when the trackpad on this controller is clicked
  71676. */
  71677. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  71678. /**
  71679. * Fired when the trackpad on this controller is modified
  71680. */
  71681. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  71682. /**
  71683. * The current x and y values of this controller's trackpad
  71684. */
  71685. _this.trackpad = { x: 0, y: 0 };
  71686. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  71687. _this._loadedMeshInfo = null;
  71688. return _this;
  71689. }
  71690. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  71691. /**
  71692. * Fired when the trigger on this controller is modified
  71693. */
  71694. get: function () {
  71695. return this.onTriggerStateChangedObservable;
  71696. },
  71697. enumerable: true,
  71698. configurable: true
  71699. });
  71700. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  71701. /**
  71702. * Fired when the menu button on this controller is modified
  71703. */
  71704. get: function () {
  71705. return this.onSecondaryButtonStateChangedObservable;
  71706. },
  71707. enumerable: true,
  71708. configurable: true
  71709. });
  71710. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  71711. /**
  71712. * Fired when the grip button on this controller is modified
  71713. */
  71714. get: function () {
  71715. return this.onMainButtonStateChangedObservable;
  71716. },
  71717. enumerable: true,
  71718. configurable: true
  71719. });
  71720. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  71721. /**
  71722. * Fired when the thumbstick button on this controller is modified
  71723. */
  71724. get: function () {
  71725. return this.onPadStateChangedObservable;
  71726. },
  71727. enumerable: true,
  71728. configurable: true
  71729. });
  71730. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  71731. /**
  71732. * Fired when the touchpad button on this controller is modified
  71733. */
  71734. get: function () {
  71735. return this.onTrackpadChangedObservable;
  71736. },
  71737. enumerable: true,
  71738. configurable: true
  71739. });
  71740. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  71741. /**
  71742. * Fired when the touchpad values on this controller are modified
  71743. */
  71744. get: function () {
  71745. return this.onTrackpadValuesChangedObservable;
  71746. },
  71747. enumerable: true,
  71748. configurable: true
  71749. });
  71750. /**
  71751. * Called once per frame by the engine.
  71752. */
  71753. WindowsMotionController.prototype.update = function () {
  71754. _super.prototype.update.call(this);
  71755. if (this.browserGamepad.axes) {
  71756. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  71757. this.trackpad.x = this.browserGamepad["axes"][2];
  71758. this.trackpad.y = this.browserGamepad["axes"][3];
  71759. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  71760. }
  71761. // Only need to animate axes if there is a loaded mesh
  71762. if (this._loadedMeshInfo) {
  71763. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  71764. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  71765. }
  71766. }
  71767. }
  71768. };
  71769. /**
  71770. * Called once for each button that changed state since the last frame
  71771. * @param buttonIdx Which button index changed
  71772. * @param state New state of the button
  71773. * @param changes Which properties on the state changed since last frame
  71774. */
  71775. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71776. var buttonName = this._mapping.buttons[buttonIdx];
  71777. if (!buttonName) {
  71778. return;
  71779. }
  71780. // Only emit events for buttons that we know how to map from index to name
  71781. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  71782. if (observable) {
  71783. observable.notifyObservers(state);
  71784. }
  71785. this._lerpButtonTransform(buttonName, state.value);
  71786. };
  71787. /**
  71788. * Moves the buttons on the controller mesh based on their current state
  71789. * @param buttonName the name of the button to move
  71790. * @param buttonValue the value of the button which determines the buttons new position
  71791. */
  71792. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  71793. // If there is no loaded mesh, there is nothing to transform.
  71794. if (!this._loadedMeshInfo) {
  71795. return;
  71796. }
  71797. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  71798. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71799. return;
  71800. }
  71801. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  71802. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  71803. };
  71804. /**
  71805. * Moves the axis on the controller mesh based on its current state
  71806. * @param axis the index of the axis
  71807. * @param axisValue the value of the axis which determines the meshes new position
  71808. * @hidden
  71809. */
  71810. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  71811. if (!this._loadedMeshInfo) {
  71812. return;
  71813. }
  71814. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  71815. if (!meshInfo) {
  71816. return;
  71817. }
  71818. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71819. return;
  71820. }
  71821. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  71822. var lerpValue = axisValue * 0.5 + 0.5;
  71823. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  71824. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  71825. };
  71826. /**
  71827. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71828. * @param scene scene in which to add meshes
  71829. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71830. */
  71831. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  71832. var _this = this;
  71833. if (forceDefault === void 0) { forceDefault = false; }
  71834. var path;
  71835. var filename;
  71836. // Checking if GLB loader is present
  71837. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  71838. // Determine the device specific folder based on the ID suffix
  71839. var device = 'default';
  71840. if (this.id && !forceDefault) {
  71841. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  71842. device = ((match && match[0]) || device);
  71843. }
  71844. // Hand
  71845. if (this.hand === 'left') {
  71846. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  71847. }
  71848. else { // Right is the default if no hand is specified
  71849. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  71850. }
  71851. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  71852. }
  71853. else {
  71854. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  71855. path = BABYLON.GenericController.MODEL_BASE_URL;
  71856. filename = BABYLON.GenericController.MODEL_FILENAME;
  71857. }
  71858. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  71859. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  71860. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  71861. if (!_this._loadedMeshInfo) {
  71862. return;
  71863. }
  71864. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  71865. _this.attachToMesh(_this._defaultModel);
  71866. if (meshLoaded) {
  71867. meshLoaded(_this._defaultModel);
  71868. }
  71869. }, null, function (scene, message) {
  71870. BABYLON.Tools.Log(message);
  71871. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  71872. if (!forceDefault) {
  71873. _this.initControllerMesh(scene, meshLoaded, true);
  71874. }
  71875. });
  71876. };
  71877. /**
  71878. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  71879. * can be transformed by button presses and axes values, based on this._mapping.
  71880. *
  71881. * @param scene scene in which the meshes exist
  71882. * @param meshes list of meshes that make up the controller model to process
  71883. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  71884. */
  71885. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  71886. var loadedMeshInfo = null;
  71887. // Create a new mesh to contain the glTF hierarchy
  71888. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  71889. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  71890. var childMesh = null;
  71891. for (var i = 0; i < meshes.length; i++) {
  71892. var mesh = meshes[i];
  71893. if (!mesh.parent) {
  71894. // Exclude controller meshes from picking results
  71895. mesh.isPickable = false;
  71896. // Handle root node, attach to the new parentMesh
  71897. childMesh = mesh;
  71898. break;
  71899. }
  71900. }
  71901. if (childMesh) {
  71902. childMesh.setParent(parentMesh);
  71903. // Create our mesh info. Note that this method will always return non-null.
  71904. loadedMeshInfo = this.createMeshInfo(parentMesh);
  71905. }
  71906. else {
  71907. BABYLON.Tools.Warn('Could not find root node in model file.');
  71908. }
  71909. return loadedMeshInfo;
  71910. };
  71911. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  71912. var loadedMeshInfo = new LoadedMeshInfo();
  71913. var i;
  71914. loadedMeshInfo.rootNode = rootNode;
  71915. // Reset the caches
  71916. loadedMeshInfo.buttonMeshes = {};
  71917. loadedMeshInfo.axisMeshes = {};
  71918. // Button Meshes
  71919. for (i = 0; i < this._mapping.buttons.length; i++) {
  71920. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  71921. if (!buttonMeshName) {
  71922. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  71923. continue;
  71924. }
  71925. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  71926. if (!buttonMesh) {
  71927. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  71928. continue;
  71929. }
  71930. var buttonMeshInfo = {
  71931. index: i,
  71932. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  71933. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  71934. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  71935. };
  71936. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  71937. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  71938. }
  71939. else {
  71940. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  71941. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  71942. '(VALUE: ' + !!buttonMeshInfo.value +
  71943. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  71944. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  71945. ')');
  71946. }
  71947. }
  71948. // Axis Meshes
  71949. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  71950. var axisMeshName = this._mapping.axisMeshNames[i];
  71951. if (!axisMeshName) {
  71952. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  71953. continue;
  71954. }
  71955. var axisMesh = getChildByName(rootNode, axisMeshName);
  71956. if (!axisMesh) {
  71957. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  71958. continue;
  71959. }
  71960. var axisMeshInfo = {
  71961. index: i,
  71962. value: getImmediateChildByName(axisMesh, 'VALUE'),
  71963. min: getImmediateChildByName(axisMesh, 'MIN'),
  71964. max: getImmediateChildByName(axisMesh, 'MAX')
  71965. };
  71966. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  71967. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  71968. }
  71969. else {
  71970. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  71971. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  71972. '(VALUE: ' + !!axisMeshInfo.value +
  71973. ', MIN: ' + !!axisMeshInfo.min +
  71974. ', MAX:' + !!axisMeshInfo.max +
  71975. ')');
  71976. }
  71977. }
  71978. // Pointing Ray
  71979. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  71980. if (!loadedMeshInfo.pointingPoseNode) {
  71981. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  71982. }
  71983. return loadedMeshInfo;
  71984. // Look through all children recursively. This will return null if no mesh exists with the given name.
  71985. function getChildByName(node, name) {
  71986. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  71987. }
  71988. // Look through only immediate children. This will return null if no mesh exists with the given name.
  71989. function getImmediateChildByName(node, name) {
  71990. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  71991. }
  71992. };
  71993. /**
  71994. * Gets the ray of the controller in the direction the controller is pointing
  71995. * @param length the length the resulting ray should be
  71996. * @returns a ray in the direction the controller is pointing
  71997. */
  71998. WindowsMotionController.prototype.getForwardRay = function (length) {
  71999. if (length === void 0) { length = 100; }
  72000. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72001. return _super.prototype.getForwardRay.call(this, length);
  72002. }
  72003. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72004. var origin = m.getTranslation();
  72005. var forward = new BABYLON.Vector3(0, 0, -1);
  72006. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72007. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72008. return new BABYLON.Ray(origin, direction, length);
  72009. };
  72010. /**
  72011. * Disposes of the controller
  72012. */
  72013. WindowsMotionController.prototype.dispose = function () {
  72014. _super.prototype.dispose.call(this);
  72015. this.onTrackpadChangedObservable.clear();
  72016. };
  72017. /**
  72018. * The base url used to load the left and right controller models
  72019. */
  72020. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72021. /**
  72022. * The name of the left controller model file
  72023. */
  72024. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72025. /**
  72026. * The name of the right controller model file
  72027. */
  72028. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72029. /**
  72030. * The controller name prefix for this controller type
  72031. */
  72032. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72033. /**
  72034. * The controller id pattern for this controller type
  72035. */
  72036. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72037. return WindowsMotionController;
  72038. }(BABYLON.WebVRController));
  72039. BABYLON.WindowsMotionController = WindowsMotionController;
  72040. })(BABYLON || (BABYLON = {}));
  72041. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72042. var BABYLON;
  72043. (function (BABYLON) {
  72044. /**
  72045. * Gear VR Controller
  72046. */
  72047. var GearVRController = /** @class */ (function (_super) {
  72048. __extends(GearVRController, _super);
  72049. /**
  72050. * Creates a new GearVRController from a gamepad
  72051. * @param vrGamepad the gamepad that the controller should be created from
  72052. */
  72053. function GearVRController(vrGamepad) {
  72054. var _this = _super.call(this, vrGamepad) || this;
  72055. _this._buttonIndexToObservableNameMap = [
  72056. 'onTrackpadChangedObservable',
  72057. 'onTriggerStateChangedObservable' // Trigger
  72058. ];
  72059. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72060. return _this;
  72061. }
  72062. /**
  72063. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72064. * @param scene scene in which to add meshes
  72065. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72066. */
  72067. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72068. var _this = this;
  72069. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72070. _this._defaultModel = newMeshes[1];
  72071. _this.attachToMesh(_this._defaultModel);
  72072. if (meshLoaded) {
  72073. meshLoaded(_this._defaultModel);
  72074. }
  72075. });
  72076. };
  72077. /**
  72078. * Called once for each button that changed state since the last frame
  72079. * @param buttonIdx Which button index changed
  72080. * @param state New state of the button
  72081. * @param changes Which properties on the state changed since last frame
  72082. */
  72083. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72084. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72085. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72086. // Only emit events for buttons that we know how to map from index to observable
  72087. var observable = this[observableName];
  72088. if (observable) {
  72089. observable.notifyObservers(state);
  72090. }
  72091. }
  72092. };
  72093. /**
  72094. * Base Url for the controller model.
  72095. */
  72096. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72097. /**
  72098. * File name for the controller model.
  72099. */
  72100. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72101. /**
  72102. * Gamepad Id prefix used to identify this controller.
  72103. */
  72104. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72105. return GearVRController;
  72106. }(BABYLON.WebVRController));
  72107. BABYLON.GearVRController = GearVRController;
  72108. })(BABYLON || (BABYLON = {}));
  72109. //# sourceMappingURL=babylon.gearVRController.js.map
  72110. var BABYLON;
  72111. (function (BABYLON) {
  72112. /**
  72113. * Google Daydream controller
  72114. */
  72115. var DaydreamController = /** @class */ (function (_super) {
  72116. __extends(DaydreamController, _super);
  72117. /**
  72118. * Creates a new DaydreamController from a gamepad
  72119. * @param vrGamepad the gamepad that the controller should be created from
  72120. */
  72121. function DaydreamController(vrGamepad) {
  72122. var _this = _super.call(this, vrGamepad) || this;
  72123. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72124. return _this;
  72125. }
  72126. /**
  72127. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72128. * @param scene scene in which to add meshes
  72129. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72130. */
  72131. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72132. var _this = this;
  72133. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72134. _this._defaultModel = newMeshes[1];
  72135. _this.attachToMesh(_this._defaultModel);
  72136. if (meshLoaded) {
  72137. meshLoaded(_this._defaultModel);
  72138. }
  72139. });
  72140. };
  72141. /**
  72142. * Called once for each button that changed state since the last frame
  72143. * @param buttonIdx Which button index changed
  72144. * @param state New state of the button
  72145. * @param changes Which properties on the state changed since last frame
  72146. */
  72147. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72148. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72149. if (buttonIdx === 0) {
  72150. var observable = this.onTriggerStateChangedObservable;
  72151. if (observable) {
  72152. observable.notifyObservers(state);
  72153. }
  72154. }
  72155. else {
  72156. // If the app or home buttons are ever made available
  72157. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72158. }
  72159. };
  72160. /**
  72161. * Base Url for the controller model.
  72162. */
  72163. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72164. /**
  72165. * File name for the controller model.
  72166. */
  72167. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72168. /**
  72169. * Gamepad Id prefix used to identify Daydream Controller.
  72170. */
  72171. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72172. return DaydreamController;
  72173. }(BABYLON.WebVRController));
  72174. BABYLON.DaydreamController = DaydreamController;
  72175. })(BABYLON || (BABYLON = {}));
  72176. //# sourceMappingURL=babylon.daydreamController.js.map
  72177. var BABYLON;
  72178. (function (BABYLON) {
  72179. var FollowCamera = /** @class */ (function (_super) {
  72180. __extends(FollowCamera, _super);
  72181. function FollowCamera(name, position, scene, lockedTarget) {
  72182. if (lockedTarget === void 0) { lockedTarget = null; }
  72183. var _this = _super.call(this, name, position, scene) || this;
  72184. _this.radius = 12;
  72185. _this.rotationOffset = 0;
  72186. _this.heightOffset = 4;
  72187. _this.cameraAcceleration = 0.05;
  72188. _this.maxCameraSpeed = 20;
  72189. _this.lockedTarget = lockedTarget;
  72190. return _this;
  72191. }
  72192. FollowCamera.prototype.getRadians = function (degrees) {
  72193. return degrees * Math.PI / 180;
  72194. };
  72195. FollowCamera.prototype.follow = function (cameraTarget) {
  72196. if (!cameraTarget)
  72197. return;
  72198. var yRotation;
  72199. if (cameraTarget.rotationQuaternion) {
  72200. var rotMatrix = new BABYLON.Matrix();
  72201. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72202. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72203. }
  72204. else {
  72205. yRotation = cameraTarget.rotation.y;
  72206. }
  72207. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72208. var targetPosition = cameraTarget.getAbsolutePosition();
  72209. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72210. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72211. var dx = targetX - this.position.x;
  72212. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72213. var dz = (targetZ) - this.position.z;
  72214. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72215. var vy = dy * this.cameraAcceleration;
  72216. var vz = dz * this.cameraAcceleration * 2;
  72217. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72218. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72219. }
  72220. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72221. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72222. }
  72223. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72224. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72225. }
  72226. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72227. this.setTarget(targetPosition);
  72228. };
  72229. FollowCamera.prototype._checkInputs = function () {
  72230. _super.prototype._checkInputs.call(this);
  72231. if (this.lockedTarget) {
  72232. this.follow(this.lockedTarget);
  72233. }
  72234. };
  72235. FollowCamera.prototype.getClassName = function () {
  72236. return "FollowCamera";
  72237. };
  72238. __decorate([
  72239. BABYLON.serialize()
  72240. ], FollowCamera.prototype, "radius", void 0);
  72241. __decorate([
  72242. BABYLON.serialize()
  72243. ], FollowCamera.prototype, "rotationOffset", void 0);
  72244. __decorate([
  72245. BABYLON.serialize()
  72246. ], FollowCamera.prototype, "heightOffset", void 0);
  72247. __decorate([
  72248. BABYLON.serialize()
  72249. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72250. __decorate([
  72251. BABYLON.serialize()
  72252. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72253. __decorate([
  72254. BABYLON.serializeAsMeshReference("lockedTargetId")
  72255. ], FollowCamera.prototype, "lockedTarget", void 0);
  72256. return FollowCamera;
  72257. }(BABYLON.TargetCamera));
  72258. BABYLON.FollowCamera = FollowCamera;
  72259. var ArcFollowCamera = /** @class */ (function (_super) {
  72260. __extends(ArcFollowCamera, _super);
  72261. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72262. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72263. _this.alpha = alpha;
  72264. _this.beta = beta;
  72265. _this.radius = radius;
  72266. _this.target = target;
  72267. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72268. _this.follow();
  72269. return _this;
  72270. }
  72271. ArcFollowCamera.prototype.follow = function () {
  72272. if (!this.target) {
  72273. return;
  72274. }
  72275. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72276. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72277. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72278. var targetPosition = this.target.getAbsolutePosition();
  72279. this.position = targetPosition.add(this._cartesianCoordinates);
  72280. this.setTarget(targetPosition);
  72281. };
  72282. ArcFollowCamera.prototype._checkInputs = function () {
  72283. _super.prototype._checkInputs.call(this);
  72284. this.follow();
  72285. };
  72286. ArcFollowCamera.prototype.getClassName = function () {
  72287. return "ArcFollowCamera";
  72288. };
  72289. return ArcFollowCamera;
  72290. }(BABYLON.TargetCamera));
  72291. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72292. })(BABYLON || (BABYLON = {}));
  72293. //# sourceMappingURL=babylon.followCamera.js.map
  72294. var BABYLON;
  72295. (function (BABYLON) {
  72296. // We're mainly based on the logic defined into the FreeCamera code
  72297. var UniversalCamera = /** @class */ (function (_super) {
  72298. __extends(UniversalCamera, _super);
  72299. //-- end properties for backward compatibility for inputs
  72300. function UniversalCamera(name, position, scene) {
  72301. var _this = _super.call(this, name, position, scene) || this;
  72302. _this.inputs.addGamepad();
  72303. return _this;
  72304. }
  72305. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72306. //-- Begin properties for backward compatibility for inputs
  72307. get: function () {
  72308. var gamepad = this.inputs.attached["gamepad"];
  72309. if (gamepad)
  72310. return gamepad.gamepadAngularSensibility;
  72311. return 0;
  72312. },
  72313. set: function (value) {
  72314. var gamepad = this.inputs.attached["gamepad"];
  72315. if (gamepad)
  72316. gamepad.gamepadAngularSensibility = value;
  72317. },
  72318. enumerable: true,
  72319. configurable: true
  72320. });
  72321. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72322. get: function () {
  72323. var gamepad = this.inputs.attached["gamepad"];
  72324. if (gamepad)
  72325. return gamepad.gamepadMoveSensibility;
  72326. return 0;
  72327. },
  72328. set: function (value) {
  72329. var gamepad = this.inputs.attached["gamepad"];
  72330. if (gamepad)
  72331. gamepad.gamepadMoveSensibility = value;
  72332. },
  72333. enumerable: true,
  72334. configurable: true
  72335. });
  72336. UniversalCamera.prototype.getClassName = function () {
  72337. return "UniversalCamera";
  72338. };
  72339. return UniversalCamera;
  72340. }(BABYLON.TouchCamera));
  72341. BABYLON.UniversalCamera = UniversalCamera;
  72342. })(BABYLON || (BABYLON = {}));
  72343. //# sourceMappingURL=babylon.universalCamera.js.map
  72344. var BABYLON;
  72345. (function (BABYLON) {
  72346. // We're mainly based on the logic defined into the FreeCamera code
  72347. var GamepadCamera = /** @class */ (function (_super) {
  72348. __extends(GamepadCamera, _super);
  72349. //-- end properties for backward compatibility for inputs
  72350. function GamepadCamera(name, position, scene) {
  72351. return _super.call(this, name, position, scene) || this;
  72352. }
  72353. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72354. //-- Begin properties for backward compatibility for inputs
  72355. get: function () {
  72356. var gamepad = this.inputs.attached["gamepad"];
  72357. if (gamepad)
  72358. return gamepad.gamepadAngularSensibility;
  72359. return 0;
  72360. },
  72361. set: function (value) {
  72362. var gamepad = this.inputs.attached["gamepad"];
  72363. if (gamepad)
  72364. gamepad.gamepadAngularSensibility = value;
  72365. },
  72366. enumerable: true,
  72367. configurable: true
  72368. });
  72369. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72370. get: function () {
  72371. var gamepad = this.inputs.attached["gamepad"];
  72372. if (gamepad)
  72373. return gamepad.gamepadMoveSensibility;
  72374. return 0;
  72375. },
  72376. set: function (value) {
  72377. var gamepad = this.inputs.attached["gamepad"];
  72378. if (gamepad)
  72379. gamepad.gamepadMoveSensibility = value;
  72380. },
  72381. enumerable: true,
  72382. configurable: true
  72383. });
  72384. GamepadCamera.prototype.getClassName = function () {
  72385. return "GamepadCamera";
  72386. };
  72387. return GamepadCamera;
  72388. }(BABYLON.UniversalCamera));
  72389. BABYLON.GamepadCamera = GamepadCamera;
  72390. })(BABYLON || (BABYLON = {}));
  72391. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72392. var BABYLON;
  72393. (function (BABYLON) {
  72394. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72395. function PostProcessRenderPipelineManager() {
  72396. this._renderPipelines = {};
  72397. }
  72398. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72399. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72400. };
  72401. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72402. if (unique === void 0) { unique = false; }
  72403. var renderPipeline = this._renderPipelines[renderPipelineName];
  72404. if (!renderPipeline) {
  72405. return;
  72406. }
  72407. renderPipeline._attachCameras(cameras, unique);
  72408. };
  72409. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72410. var renderPipeline = this._renderPipelines[renderPipelineName];
  72411. if (!renderPipeline) {
  72412. return;
  72413. }
  72414. renderPipeline._detachCameras(cameras);
  72415. };
  72416. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72417. var renderPipeline = this._renderPipelines[renderPipelineName];
  72418. if (!renderPipeline) {
  72419. return;
  72420. }
  72421. renderPipeline._enableEffect(renderEffectName, cameras);
  72422. };
  72423. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72424. var renderPipeline = this._renderPipelines[renderPipelineName];
  72425. if (!renderPipeline) {
  72426. return;
  72427. }
  72428. renderPipeline._disableEffect(renderEffectName, cameras);
  72429. };
  72430. PostProcessRenderPipelineManager.prototype.update = function () {
  72431. for (var renderPipelineName in this._renderPipelines) {
  72432. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72433. var pipeline = this._renderPipelines[renderPipelineName];
  72434. if (!pipeline.isSupported) {
  72435. pipeline.dispose();
  72436. delete this._renderPipelines[renderPipelineName];
  72437. }
  72438. else {
  72439. pipeline._update();
  72440. }
  72441. }
  72442. }
  72443. };
  72444. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  72445. for (var renderPipelineName in this._renderPipelines) {
  72446. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72447. var pipeline = this._renderPipelines[renderPipelineName];
  72448. pipeline._rebuild();
  72449. }
  72450. }
  72451. };
  72452. PostProcessRenderPipelineManager.prototype.dispose = function () {
  72453. for (var renderPipelineName in this._renderPipelines) {
  72454. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72455. var pipeline = this._renderPipelines[renderPipelineName];
  72456. pipeline.dispose();
  72457. }
  72458. }
  72459. };
  72460. return PostProcessRenderPipelineManager;
  72461. }());
  72462. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  72463. })(BABYLON || (BABYLON = {}));
  72464. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  72465. var BABYLON;
  72466. (function (BABYLON) {
  72467. /**
  72468. * This represents a set of one or more post processes in Babylon.
  72469. * A post process can be used to apply a shader to a texture after it is rendered.
  72470. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  72471. */
  72472. var PostProcessRenderEffect = /** @class */ (function () {
  72473. /**
  72474. * Instantiates a post process render effect.
  72475. * A post process can be used to apply a shader to a texture after it is rendered.
  72476. * @param engine The engine the effect is tied to
  72477. * @param name The name of the effect
  72478. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  72479. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  72480. */
  72481. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  72482. this._name = name;
  72483. this._singleInstance = singleInstance || true;
  72484. this._getPostProcesses = getPostProcesses;
  72485. this._cameras = {};
  72486. this._indicesForCamera = {};
  72487. this._postProcesses = {};
  72488. }
  72489. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  72490. /**
  72491. * Checks if all the post processes in the effect are supported.
  72492. */
  72493. get: function () {
  72494. for (var index in this._postProcesses) {
  72495. if (this._postProcesses.hasOwnProperty(index)) {
  72496. var pps = this._postProcesses[index];
  72497. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  72498. if (!pps[ppIndex].isSupported) {
  72499. return false;
  72500. }
  72501. }
  72502. }
  72503. }
  72504. return true;
  72505. },
  72506. enumerable: true,
  72507. configurable: true
  72508. });
  72509. /**
  72510. * Updates the current state of the effect
  72511. */
  72512. PostProcessRenderEffect.prototype._update = function () {
  72513. };
  72514. /**
  72515. * Attaches the effect on cameras
  72516. * @param cameras The camera to attach to.
  72517. */
  72518. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  72519. var _this = this;
  72520. var cameraKey;
  72521. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72522. if (!cams) {
  72523. return;
  72524. }
  72525. for (var i = 0; i < cams.length; i++) {
  72526. var camera = cams[i];
  72527. var cameraName = camera.name;
  72528. if (this._singleInstance) {
  72529. cameraKey = 0;
  72530. }
  72531. else {
  72532. cameraKey = cameraName;
  72533. }
  72534. if (!this._postProcesses[cameraKey]) {
  72535. var postProcess = this._getPostProcesses();
  72536. if (postProcess) {
  72537. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  72538. }
  72539. }
  72540. if (!this._indicesForCamera[cameraName]) {
  72541. this._indicesForCamera[cameraName] = [];
  72542. }
  72543. this._postProcesses[cameraKey].forEach(function (postProcess) {
  72544. var index = camera.attachPostProcess(postProcess);
  72545. _this._indicesForCamera[cameraName].push(index);
  72546. });
  72547. if (!this._cameras[cameraName]) {
  72548. this._cameras[cameraName] = camera;
  72549. }
  72550. }
  72551. };
  72552. /**
  72553. * Detatches the effect on cameras
  72554. * @param cameras The camera to detatch from.
  72555. */
  72556. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  72557. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72558. if (!cams) {
  72559. return;
  72560. }
  72561. for (var i = 0; i < cams.length; i++) {
  72562. var camera = cams[i];
  72563. var cameraName = camera.name;
  72564. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72565. camera.detachPostProcess(postProcess);
  72566. });
  72567. if (this._cameras[cameraName]) {
  72568. //this._indicesForCamera.splice(index, 1);
  72569. this._cameras[cameraName] = null;
  72570. }
  72571. }
  72572. };
  72573. /**
  72574. * Enables the effect on given cameras
  72575. * @param cameras The camera to enable.
  72576. */
  72577. PostProcessRenderEffect.prototype._enable = function (cameras) {
  72578. var _this = this;
  72579. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72580. if (!cams) {
  72581. return;
  72582. }
  72583. for (var i = 0; i < cams.length; i++) {
  72584. var camera = cams[i];
  72585. var cameraName = camera.name;
  72586. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  72587. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  72588. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72589. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  72590. });
  72591. }
  72592. }
  72593. }
  72594. };
  72595. /**
  72596. * Disables the effect on the given cameras
  72597. * @param cameras The camera to disable.
  72598. */
  72599. PostProcessRenderEffect.prototype._disable = function (cameras) {
  72600. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72601. if (!cams) {
  72602. return;
  72603. }
  72604. for (var i = 0; i < cams.length; i++) {
  72605. var camera = cams[i];
  72606. var cameraName = camera.name;
  72607. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72608. camera.detachPostProcess(postProcess);
  72609. });
  72610. }
  72611. };
  72612. /**
  72613. * Gets a list of the post processes contained in the effect.
  72614. * @param camera The camera to get the post processes on.
  72615. * @returns The list of the post processes in the effect.
  72616. */
  72617. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  72618. if (this._singleInstance) {
  72619. return this._postProcesses[0];
  72620. }
  72621. else {
  72622. if (!camera) {
  72623. return null;
  72624. }
  72625. return this._postProcesses[camera.name];
  72626. }
  72627. };
  72628. return PostProcessRenderEffect;
  72629. }());
  72630. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  72631. })(BABYLON || (BABYLON = {}));
  72632. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  72633. var BABYLON;
  72634. (function (BABYLON) {
  72635. var PostProcessRenderPipeline = /** @class */ (function () {
  72636. function PostProcessRenderPipeline(engine, name) {
  72637. this.engine = engine;
  72638. this._name = name;
  72639. this._renderEffects = {};
  72640. this._renderEffectsForIsolatedPass = new Array();
  72641. this._cameras = [];
  72642. }
  72643. PostProcessRenderPipeline.prototype.getClassName = function () {
  72644. return "PostProcessRenderPipeline";
  72645. };
  72646. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  72647. get: function () {
  72648. for (var renderEffectName in this._renderEffects) {
  72649. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72650. if (!this._renderEffects[renderEffectName].isSupported) {
  72651. return false;
  72652. }
  72653. }
  72654. }
  72655. return true;
  72656. },
  72657. enumerable: true,
  72658. configurable: true
  72659. });
  72660. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  72661. this._renderEffects[renderEffect._name] = renderEffect;
  72662. };
  72663. // private
  72664. PostProcessRenderPipeline.prototype._rebuild = function () {
  72665. };
  72666. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  72667. var renderEffects = this._renderEffects[renderEffectName];
  72668. if (!renderEffects) {
  72669. return;
  72670. }
  72671. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72672. };
  72673. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  72674. var renderEffects = this._renderEffects[renderEffectName];
  72675. if (!renderEffects) {
  72676. return;
  72677. }
  72678. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72679. };
  72680. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  72681. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72682. if (!cams) {
  72683. return;
  72684. }
  72685. var indicesToDelete = [];
  72686. var i;
  72687. for (i = 0; i < cams.length; i++) {
  72688. var camera = cams[i];
  72689. var cameraName = camera.name;
  72690. if (this._cameras.indexOf(camera) === -1) {
  72691. this._cameras[cameraName] = camera;
  72692. }
  72693. else if (unique) {
  72694. indicesToDelete.push(i);
  72695. }
  72696. }
  72697. for (i = 0; i < indicesToDelete.length; i++) {
  72698. cameras.splice(indicesToDelete[i], 1);
  72699. }
  72700. for (var renderEffectName in this._renderEffects) {
  72701. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72702. this._renderEffects[renderEffectName]._attachCameras(cams);
  72703. }
  72704. }
  72705. };
  72706. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  72707. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72708. if (!cams) {
  72709. return;
  72710. }
  72711. for (var renderEffectName in this._renderEffects) {
  72712. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72713. this._renderEffects[renderEffectName]._detachCameras(cams);
  72714. }
  72715. }
  72716. for (var i = 0; i < cams.length; i++) {
  72717. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  72718. }
  72719. };
  72720. PostProcessRenderPipeline.prototype._update = function () {
  72721. for (var renderEffectName in this._renderEffects) {
  72722. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72723. this._renderEffects[renderEffectName]._update();
  72724. }
  72725. }
  72726. for (var i = 0; i < this._cameras.length; i++) {
  72727. var cameraName = this._cameras[i].name;
  72728. if (this._renderEffectsForIsolatedPass[cameraName]) {
  72729. this._renderEffectsForIsolatedPass[cameraName]._update();
  72730. }
  72731. }
  72732. };
  72733. PostProcessRenderPipeline.prototype._reset = function () {
  72734. this._renderEffects = {};
  72735. this._renderEffectsForIsolatedPass = new Array();
  72736. };
  72737. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  72738. // 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)
  72739. var effectKeys = Object.keys(this._renderEffects);
  72740. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  72741. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  72742. if (postProcesses) {
  72743. postProcesses[0].samples = sampleCount;
  72744. return true;
  72745. }
  72746. }
  72747. return false;
  72748. };
  72749. PostProcessRenderPipeline.prototype.dispose = function () {
  72750. // Must be implemented by children
  72751. };
  72752. __decorate([
  72753. BABYLON.serialize()
  72754. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  72755. return PostProcessRenderPipeline;
  72756. }());
  72757. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  72758. })(BABYLON || (BABYLON = {}));
  72759. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  72760. var BABYLON;
  72761. (function (BABYLON) {
  72762. /**
  72763. * This represents a depth renderer in Babylon.
  72764. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  72765. */
  72766. var DepthRenderer = /** @class */ (function () {
  72767. /**
  72768. * Instantiates a depth renderer
  72769. * @param scene The scene the renderer belongs to
  72770. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  72771. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  72772. */
  72773. function DepthRenderer(scene, type, camera) {
  72774. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  72775. if (camera === void 0) { camera = null; }
  72776. var _this = this;
  72777. this._scene = scene;
  72778. this._camera = camera;
  72779. var engine = scene.getEngine();
  72780. // Render target
  72781. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  72782. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72783. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72784. this._depthMap.refreshRate = 1;
  72785. this._depthMap.renderParticles = false;
  72786. this._depthMap.renderList = null;
  72787. // Camera to get depth map from to support multiple concurrent cameras
  72788. this._depthMap.activeCamera = this._camera;
  72789. this._depthMap.ignoreCameraViewport = true;
  72790. this._depthMap.useCameraPostProcesses = false;
  72791. // set default depth value to 1.0 (far away)
  72792. this._depthMap.onClearObservable.add(function (engine) {
  72793. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  72794. });
  72795. // Custom render function
  72796. var renderSubMesh = function (subMesh) {
  72797. var mesh = subMesh.getRenderingMesh();
  72798. var scene = _this._scene;
  72799. var engine = scene.getEngine();
  72800. var material = subMesh.getMaterial();
  72801. if (!material) {
  72802. return;
  72803. }
  72804. // Culling and reverse (right handed system)
  72805. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  72806. // Managing instances
  72807. var batch = mesh._getInstancesRenderList(subMesh._id);
  72808. if (batch.mustReturn) {
  72809. return;
  72810. }
  72811. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  72812. var camera = _this._camera || scene.activeCamera;
  72813. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  72814. engine.enableEffect(_this._effect);
  72815. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  72816. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  72817. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  72818. // Alpha test
  72819. if (material && material.needAlphaTesting()) {
  72820. var alphaTexture = material.getAlphaTestTexture();
  72821. if (alphaTexture) {
  72822. _this._effect.setTexture("diffuseSampler", alphaTexture);
  72823. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72824. }
  72825. }
  72826. // Bones
  72827. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72828. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72829. }
  72830. // Draw
  72831. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72832. }
  72833. };
  72834. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72835. var index;
  72836. if (depthOnlySubMeshes.length) {
  72837. engine.setColorWrite(false);
  72838. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72839. renderSubMesh(depthOnlySubMeshes.data[index]);
  72840. }
  72841. engine.setColorWrite(true);
  72842. }
  72843. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72844. renderSubMesh(opaqueSubMeshes.data[index]);
  72845. }
  72846. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72847. renderSubMesh(alphaTestSubMeshes.data[index]);
  72848. }
  72849. };
  72850. }
  72851. /**
  72852. * Creates the depth rendering effect and checks if the effect is ready.
  72853. * @param subMesh The submesh to be used to render the depth map of
  72854. * @param useInstances If multiple world instances should be used
  72855. * @returns if the depth renderer is ready to render the depth map
  72856. */
  72857. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  72858. var material = subMesh.getMaterial();
  72859. if (material.disableDepthWrite) {
  72860. return false;
  72861. }
  72862. var defines = [];
  72863. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72864. var mesh = subMesh.getMesh();
  72865. // Alpha test
  72866. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  72867. defines.push("#define ALPHATEST");
  72868. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72869. attribs.push(BABYLON.VertexBuffer.UVKind);
  72870. defines.push("#define UV1");
  72871. }
  72872. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  72873. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72874. defines.push("#define UV2");
  72875. }
  72876. }
  72877. // Bones
  72878. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72879. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72880. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72881. if (mesh.numBoneInfluencers > 4) {
  72882. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72883. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72884. }
  72885. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72886. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  72887. }
  72888. else {
  72889. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72890. }
  72891. // Instances
  72892. if (useInstances) {
  72893. defines.push("#define INSTANCES");
  72894. attribs.push("world0");
  72895. attribs.push("world1");
  72896. attribs.push("world2");
  72897. attribs.push("world3");
  72898. }
  72899. // Get correct effect
  72900. var join = defines.join("\n");
  72901. if (this._cachedDefines !== join) {
  72902. this._cachedDefines = join;
  72903. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  72904. }
  72905. return this._effect.isReady();
  72906. };
  72907. /**
  72908. * Gets the texture which the depth map will be written to.
  72909. * @returns The depth map texture
  72910. */
  72911. DepthRenderer.prototype.getDepthMap = function () {
  72912. return this._depthMap;
  72913. };
  72914. /**
  72915. * Disposes of the depth renderer.
  72916. */
  72917. DepthRenderer.prototype.dispose = function () {
  72918. this._depthMap.dispose();
  72919. };
  72920. return DepthRenderer;
  72921. }());
  72922. BABYLON.DepthRenderer = DepthRenderer;
  72923. })(BABYLON || (BABYLON = {}));
  72924. //# sourceMappingURL=babylon.depthRenderer.js.map
  72925. var BABYLON;
  72926. (function (BABYLON) {
  72927. var SSAORenderingPipeline = /** @class */ (function (_super) {
  72928. __extends(SSAORenderingPipeline, _super);
  72929. /**
  72930. * @constructor
  72931. * @param {string} name - The rendering pipeline name
  72932. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72933. * @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 }
  72934. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72935. */
  72936. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  72937. var _this = _super.call(this, scene.getEngine(), name) || this;
  72938. // Members
  72939. /**
  72940. * The PassPostProcess id in the pipeline that contains the original scene color
  72941. */
  72942. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  72943. /**
  72944. * The SSAO PostProcess id in the pipeline
  72945. */
  72946. _this.SSAORenderEffect = "SSAORenderEffect";
  72947. /**
  72948. * The horizontal blur PostProcess id in the pipeline
  72949. */
  72950. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  72951. /**
  72952. * The vertical blur PostProcess id in the pipeline
  72953. */
  72954. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  72955. /**
  72956. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  72957. */
  72958. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  72959. /**
  72960. * The output strength of the SSAO post-process. Default value is 1.0.
  72961. */
  72962. _this.totalStrength = 1.0;
  72963. /**
  72964. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  72965. */
  72966. _this.radius = 0.0001;
  72967. /**
  72968. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  72969. * Must not be equal to fallOff and superior to fallOff.
  72970. * Default value is 0.975
  72971. */
  72972. _this.area = 0.0075;
  72973. /**
  72974. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  72975. * Must not be equal to area and inferior to area.
  72976. * Default value is 0.0
  72977. */
  72978. _this.fallOff = 0.000001;
  72979. /**
  72980. * The base color of the SSAO post-process
  72981. * The final result is "base + ssao" between [0, 1]
  72982. */
  72983. _this.base = 0.5;
  72984. _this._firstUpdate = true;
  72985. _this._scene = scene;
  72986. // Set up assets
  72987. _this._createRandomTexture();
  72988. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  72989. var ssaoRatio = ratio.ssaoRatio || ratio;
  72990. var combineRatio = ratio.combineRatio || ratio;
  72991. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  72992. _this._createSSAOPostProcess(ssaoRatio);
  72993. _this._createBlurPostProcess(ssaoRatio);
  72994. _this._createSSAOCombinePostProcess(combineRatio);
  72995. // Set up pipeline
  72996. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  72997. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  72998. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  72999. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73000. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73001. // Finish
  73002. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73003. if (cameras)
  73004. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73005. return _this;
  73006. }
  73007. // Public Methods
  73008. /**
  73009. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73010. */
  73011. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73012. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73013. for (var i = 0; i < this._scene.cameras.length; i++) {
  73014. var camera = this._scene.cameras[i];
  73015. this._originalColorPostProcess.dispose(camera);
  73016. this._ssaoPostProcess.dispose(camera);
  73017. this._blurHPostProcess.dispose(camera);
  73018. this._blurVPostProcess.dispose(camera);
  73019. this._ssaoCombinePostProcess.dispose(camera);
  73020. }
  73021. this._randomTexture.dispose();
  73022. if (disableDepthRender)
  73023. this._scene.disableDepthRenderer();
  73024. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73025. _super.prototype.dispose.call(this);
  73026. };
  73027. // Private Methods
  73028. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73029. var _this = this;
  73030. var size = 16;
  73031. 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);
  73032. 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);
  73033. this._blurHPostProcess.onActivateObservable.add(function () {
  73034. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73035. _this._blurHPostProcess.kernel = size * dw;
  73036. });
  73037. this._blurVPostProcess.onActivateObservable.add(function () {
  73038. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73039. _this._blurVPostProcess.kernel = size * dw;
  73040. });
  73041. };
  73042. SSAORenderingPipeline.prototype._rebuild = function () {
  73043. this._firstUpdate = true;
  73044. _super.prototype._rebuild.call(this);
  73045. };
  73046. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73047. var _this = this;
  73048. var numSamples = 16;
  73049. var sampleSphere = [
  73050. 0.5381, 0.1856, -0.4319,
  73051. 0.1379, 0.2486, 0.4430,
  73052. 0.3371, 0.5679, -0.0057,
  73053. -0.6999, -0.0451, -0.0019,
  73054. 0.0689, -0.1598, -0.8547,
  73055. 0.0560, 0.0069, -0.1843,
  73056. -0.0146, 0.1402, 0.0762,
  73057. 0.0100, -0.1924, -0.0344,
  73058. -0.3577, -0.5301, -0.4358,
  73059. -0.3169, 0.1063, 0.0158,
  73060. 0.0103, -0.5869, 0.0046,
  73061. -0.0897, -0.4940, 0.3287,
  73062. 0.7119, -0.0154, -0.0918,
  73063. -0.0533, 0.0596, -0.5411,
  73064. 0.0352, -0.0631, 0.5460,
  73065. -0.4776, 0.2847, -0.0271
  73066. ];
  73067. var samplesFactor = 1.0 / numSamples;
  73068. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73069. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73070. "area", "fallOff", "base", "range", "viewport"
  73071. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73072. this._ssaoPostProcess.onApply = function (effect) {
  73073. if (_this._firstUpdate) {
  73074. effect.setArray3("sampleSphere", sampleSphere);
  73075. effect.setFloat("samplesFactor", samplesFactor);
  73076. effect.setFloat("randTextureTiles", 4.0);
  73077. }
  73078. effect.setFloat("totalStrength", _this.totalStrength);
  73079. effect.setFloat("radius", _this.radius);
  73080. effect.setFloat("area", _this.area);
  73081. effect.setFloat("fallOff", _this.fallOff);
  73082. effect.setFloat("base", _this.base);
  73083. effect.setTexture("textureSampler", _this._depthTexture);
  73084. effect.setTexture("randomSampler", _this._randomTexture);
  73085. };
  73086. };
  73087. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73088. var _this = this;
  73089. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73090. this._ssaoCombinePostProcess.onApply = function (effect) {
  73091. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73092. };
  73093. };
  73094. SSAORenderingPipeline.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 = Math.floor(rand(-1.0, 1.0) * 255);
  73107. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73108. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73109. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73110. context.fillRect(x, y, 1, 1);
  73111. }
  73112. }
  73113. this._randomTexture.update(false);
  73114. };
  73115. __decorate([
  73116. BABYLON.serialize()
  73117. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73118. __decorate([
  73119. BABYLON.serialize()
  73120. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73121. __decorate([
  73122. BABYLON.serialize()
  73123. ], SSAORenderingPipeline.prototype, "area", void 0);
  73124. __decorate([
  73125. BABYLON.serialize()
  73126. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73127. __decorate([
  73128. BABYLON.serialize()
  73129. ], SSAORenderingPipeline.prototype, "base", void 0);
  73130. return SSAORenderingPipeline;
  73131. }(BABYLON.PostProcessRenderPipeline));
  73132. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73133. })(BABYLON || (BABYLON = {}));
  73134. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73135. var BABYLON;
  73136. (function (BABYLON) {
  73137. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73138. __extends(SSAO2RenderingPipeline, _super);
  73139. /**
  73140. * @constructor
  73141. * @param {string} name - The rendering pipeline name
  73142. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73143. * @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 }
  73144. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73145. */
  73146. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73147. var _this = _super.call(this, scene.getEngine(), name) || this;
  73148. // Members
  73149. /**
  73150. * The PassPostProcess id in the pipeline that contains the original scene color
  73151. */
  73152. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73153. /**
  73154. * The SSAO PostProcess id in the pipeline
  73155. */
  73156. _this.SSAORenderEffect = "SSAORenderEffect";
  73157. /**
  73158. * The horizontal blur PostProcess id in the pipeline
  73159. */
  73160. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73161. /**
  73162. * The vertical blur PostProcess id in the pipeline
  73163. */
  73164. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73165. /**
  73166. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73167. */
  73168. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73169. /**
  73170. * The output strength of the SSAO post-process. Default value is 1.0.
  73171. */
  73172. _this.totalStrength = 1.0;
  73173. /**
  73174. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73175. */
  73176. _this.maxZ = 100.0;
  73177. /**
  73178. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73179. */
  73180. _this.minZAspect = 0.2;
  73181. /**
  73182. * Number of samples used for the SSAO calculations. Default value is 8
  73183. */
  73184. _this._samples = 8;
  73185. /**
  73186. * Are we using bilateral blur ?
  73187. */
  73188. _this._expensiveBlur = true;
  73189. /**
  73190. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73191. */
  73192. _this.radius = 2.0;
  73193. /**
  73194. * The base color of the SSAO post-process
  73195. * The final result is "base + ssao" between [0, 1]
  73196. */
  73197. _this.base = 0.1;
  73198. _this._firstUpdate = true;
  73199. _this._scene = scene;
  73200. _this._ratio = ratio;
  73201. if (!_this.isSupported) {
  73202. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73203. return _this;
  73204. }
  73205. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73206. var blurRatio = _this._ratio.blurRatio || ratio;
  73207. // Set up assets
  73208. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73209. _this._createRandomTexture();
  73210. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73211. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73212. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73213. _this._createSSAOPostProcess(1.0);
  73214. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73215. _this._createSSAOCombinePostProcess(blurRatio);
  73216. // Set up pipeline
  73217. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73218. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73219. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73220. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73221. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73222. // Finish
  73223. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73224. if (cameras)
  73225. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73226. return _this;
  73227. }
  73228. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73229. get: function () {
  73230. return this._samples;
  73231. },
  73232. set: function (n) {
  73233. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73234. this._samples = n;
  73235. this._sampleSphere = this._generateHemisphere();
  73236. this._firstUpdate = true;
  73237. },
  73238. enumerable: true,
  73239. configurable: true
  73240. });
  73241. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73242. get: function () {
  73243. return this._expensiveBlur;
  73244. },
  73245. set: function (b) {
  73246. 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"]);
  73247. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73248. this._expensiveBlur = b;
  73249. this._firstUpdate = true;
  73250. },
  73251. enumerable: true,
  73252. configurable: true
  73253. });
  73254. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73255. /**
  73256. * Support test.
  73257. */
  73258. get: function () {
  73259. var engine = BABYLON.Engine.LastCreatedEngine;
  73260. if (!engine) {
  73261. return false;
  73262. }
  73263. return engine.getCaps().drawBuffersExtension;
  73264. },
  73265. enumerable: true,
  73266. configurable: true
  73267. });
  73268. // Public Methods
  73269. /**
  73270. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73271. */
  73272. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73273. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73274. for (var i = 0; i < this._scene.cameras.length; i++) {
  73275. var camera = this._scene.cameras[i];
  73276. this._originalColorPostProcess.dispose(camera);
  73277. this._ssaoPostProcess.dispose(camera);
  73278. this._blurHPostProcess.dispose(camera);
  73279. this._blurVPostProcess.dispose(camera);
  73280. this._ssaoCombinePostProcess.dispose(camera);
  73281. }
  73282. this._randomTexture.dispose();
  73283. if (disableGeometryBufferRenderer)
  73284. this._scene.disableGeometryBufferRenderer();
  73285. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73286. _super.prototype.dispose.call(this);
  73287. };
  73288. // Private Methods
  73289. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73290. var _this = this;
  73291. this._samplerOffsets = [];
  73292. var expensive = this.expensiveBlur;
  73293. for (var i = -8; i < 8; i++) {
  73294. this._samplerOffsets.push(i * 2 + 0.5);
  73295. }
  73296. 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");
  73297. this._blurHPostProcess.onApply = function (effect) {
  73298. if (!_this._scene.activeCamera) {
  73299. return;
  73300. }
  73301. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73302. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73303. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73304. effect.setFloat("radius", _this.radius);
  73305. effect.setTexture("depthSampler", _this._depthTexture);
  73306. if (_this._firstUpdate) {
  73307. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73308. }
  73309. };
  73310. 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");
  73311. this._blurVPostProcess.onApply = function (effect) {
  73312. if (!_this._scene.activeCamera) {
  73313. return;
  73314. }
  73315. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73316. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73317. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73318. effect.setFloat("radius", _this.radius);
  73319. effect.setTexture("depthSampler", _this._depthTexture);
  73320. if (_this._firstUpdate) {
  73321. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73322. _this._firstUpdate = false;
  73323. }
  73324. };
  73325. };
  73326. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73327. this._firstUpdate = true;
  73328. _super.prototype._rebuild.call(this);
  73329. };
  73330. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73331. var numSamples = this.samples;
  73332. var result = [];
  73333. var vector, scale;
  73334. var rand = function (min, max) {
  73335. return Math.random() * (max - min) + min;
  73336. };
  73337. var i = 0;
  73338. while (i < numSamples) {
  73339. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73340. vector.normalize();
  73341. scale = i / numSamples;
  73342. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73343. vector.scaleInPlace(scale);
  73344. result.push(vector.x, vector.y, vector.z);
  73345. i++;
  73346. }
  73347. return result;
  73348. };
  73349. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73350. var _this = this;
  73351. var numSamples = this.samples;
  73352. this._sampleSphere = this._generateHemisphere();
  73353. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73354. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73355. "base", "range", "projection", "near", "far", "texelSize",
  73356. "xViewport", "yViewport", "maxZ", "minZAspect"
  73357. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73358. this._ssaoPostProcess.onApply = function (effect) {
  73359. if (_this._firstUpdate) {
  73360. effect.setArray3("sampleSphere", _this._sampleSphere);
  73361. effect.setFloat("randTextureTiles", 4.0);
  73362. }
  73363. if (!_this._scene.activeCamera) {
  73364. return;
  73365. }
  73366. effect.setFloat("samplesFactor", 1 / _this.samples);
  73367. effect.setFloat("totalStrength", _this.totalStrength);
  73368. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73369. effect.setFloat("radius", _this.radius);
  73370. effect.setFloat("maxZ", _this.maxZ);
  73371. effect.setFloat("minZAspect", _this.minZAspect);
  73372. effect.setFloat("base", _this.base);
  73373. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73374. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73375. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73376. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73377. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73378. effect.setTexture("textureSampler", _this._depthTexture);
  73379. effect.setTexture("normalSampler", _this._normalTexture);
  73380. effect.setTexture("randomSampler", _this._randomTexture);
  73381. };
  73382. };
  73383. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73384. var _this = this;
  73385. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73386. this._ssaoCombinePostProcess.onApply = function (effect) {
  73387. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73388. };
  73389. };
  73390. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73391. var size = 512;
  73392. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73393. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73394. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73395. var context = this._randomTexture.getContext();
  73396. var rand = function (min, max) {
  73397. return Math.random() * (max - min) + min;
  73398. };
  73399. var randVector = BABYLON.Vector3.Zero();
  73400. for (var x = 0; x < size; x++) {
  73401. for (var y = 0; y < size; y++) {
  73402. randVector.x = rand(0.0, 1.0);
  73403. randVector.y = rand(0.0, 1.0);
  73404. randVector.z = 0.0;
  73405. randVector.normalize();
  73406. randVector.scaleInPlace(255);
  73407. randVector.x = Math.floor(randVector.x);
  73408. randVector.y = Math.floor(randVector.y);
  73409. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73410. context.fillRect(x, y, 1, 1);
  73411. }
  73412. }
  73413. this._randomTexture.update(false);
  73414. };
  73415. /**
  73416. * Serialize the rendering pipeline (Used when exporting)
  73417. * @returns the serialized object
  73418. */
  73419. SSAO2RenderingPipeline.prototype.serialize = function () {
  73420. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73421. serializationObject.customType = "SSAO2RenderingPipeline";
  73422. return serializationObject;
  73423. };
  73424. /**
  73425. * Parse the serialized pipeline
  73426. * @param source Source pipeline.
  73427. * @param scene The scene to load the pipeline to.
  73428. * @param rootUrl The URL of the serialized pipeline.
  73429. * @returns An instantiated pipeline from the serialized object.
  73430. */
  73431. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  73432. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73433. };
  73434. __decorate([
  73435. BABYLON.serialize()
  73436. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73437. __decorate([
  73438. BABYLON.serialize()
  73439. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73440. __decorate([
  73441. BABYLON.serialize()
  73442. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  73443. __decorate([
  73444. BABYLON.serialize("samples")
  73445. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  73446. __decorate([
  73447. BABYLON.serialize()
  73448. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  73449. __decorate([
  73450. BABYLON.serialize("expensiveBlur")
  73451. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  73452. __decorate([
  73453. BABYLON.serialize()
  73454. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  73455. __decorate([
  73456. BABYLON.serialize()
  73457. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  73458. return SSAO2RenderingPipeline;
  73459. }(BABYLON.PostProcessRenderPipeline));
  73460. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  73461. })(BABYLON || (BABYLON = {}));
  73462. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  73463. // BABYLON.JS Chromatic Aberration GLSL Shader
  73464. // Author: Olivier Guyot
  73465. // Separates very slightly R, G and B colors on the edges of the screen
  73466. // Inspired by Francois Tarlier & Martins Upitis
  73467. var BABYLON;
  73468. (function (BABYLON) {
  73469. var LensRenderingPipeline = /** @class */ (function (_super) {
  73470. __extends(LensRenderingPipeline, _super);
  73471. /**
  73472. * @constructor
  73473. *
  73474. * Effect parameters are as follow:
  73475. * {
  73476. * chromatic_aberration: number; // from 0 to x (1 for realism)
  73477. * edge_blur: number; // from 0 to x (1 for realism)
  73478. * distortion: number; // from 0 to x (1 for realism)
  73479. * grain_amount: number; // from 0 to 1
  73480. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  73481. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  73482. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  73483. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  73484. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  73485. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  73486. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  73487. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  73488. * }
  73489. * Note: if an effect parameter is unset, effect is disabled
  73490. *
  73491. * @param {string} name - The rendering pipeline name
  73492. * @param {object} parameters - An object containing all parameters (see above)
  73493. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73494. * @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)
  73495. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73496. */
  73497. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  73498. if (ratio === void 0) { ratio = 1.0; }
  73499. var _this = _super.call(this, scene.getEngine(), name) || this;
  73500. // Lens effects can be of the following:
  73501. // - chromatic aberration (slight shift of RGB colors)
  73502. // - blur on the edge of the lens
  73503. // - lens distortion
  73504. // - depth-of-field blur & highlights enhancing
  73505. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  73506. // - grain effect (noise or custom texture)
  73507. // Two additional texture samplers are needed:
  73508. // - depth map (for depth-of-field)
  73509. // - grain texture
  73510. /**
  73511. * The chromatic aberration PostProcess id in the pipeline
  73512. */
  73513. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  73514. /**
  73515. * The highlights enhancing PostProcess id in the pipeline
  73516. */
  73517. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  73518. /**
  73519. * The depth-of-field PostProcess id in the pipeline
  73520. */
  73521. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  73522. _this._scene = scene;
  73523. // Fetch texture samplers
  73524. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73525. if (parameters.grain_texture) {
  73526. _this._grainTexture = parameters.grain_texture;
  73527. }
  73528. else {
  73529. _this._createGrainTexture();
  73530. }
  73531. // save parameters
  73532. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  73533. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  73534. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  73535. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  73536. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  73537. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  73538. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  73539. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  73540. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  73541. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  73542. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  73543. // Create effects
  73544. _this._createChromaticAberrationPostProcess(ratio);
  73545. _this._createHighlightsPostProcess(ratio);
  73546. _this._createDepthOfFieldPostProcess(ratio / 4);
  73547. // Set up pipeline
  73548. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  73549. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  73550. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  73551. if (_this._highlightsGain === -1) {
  73552. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  73553. }
  73554. // Finish
  73555. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73556. if (cameras) {
  73557. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73558. }
  73559. return _this;
  73560. }
  73561. // public methods (self explanatory)
  73562. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  73563. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  73564. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  73565. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  73566. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  73567. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  73568. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  73569. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  73570. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  73571. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  73572. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  73573. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  73574. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  73575. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  73576. };
  73577. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  73578. this._highlightsPostProcess.updateEffect();
  73579. };
  73580. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  73581. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  73582. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  73583. this._highlightsGain = amount;
  73584. };
  73585. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  73586. if (this._highlightsGain === -1) {
  73587. this._highlightsGain = 1.0;
  73588. }
  73589. this._highlightsThreshold = amount;
  73590. };
  73591. LensRenderingPipeline.prototype.disableHighlights = function () {
  73592. this._highlightsGain = -1;
  73593. };
  73594. /**
  73595. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  73596. */
  73597. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73598. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73599. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73600. this._chromaticAberrationPostProcess = null;
  73601. this._highlightsPostProcess = null;
  73602. this._depthOfFieldPostProcess = null;
  73603. this._grainTexture.dispose();
  73604. if (disableDepthRender)
  73605. this._scene.disableDepthRenderer();
  73606. };
  73607. // colors shifting and distortion
  73608. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  73609. var _this = this;
  73610. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  73611. [], // samplers
  73612. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73613. this._chromaticAberrationPostProcess.onApply = function (effect) {
  73614. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  73615. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73616. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73617. effect.setFloat('radialIntensity', 1);
  73618. effect.setFloat2('direction', 17, 17);
  73619. effect.setFloat2('centerPosition', 0.5, 0.5);
  73620. };
  73621. };
  73622. // highlights enhancing
  73623. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  73624. var _this = this;
  73625. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  73626. [], // samplers
  73627. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  73628. this._highlightsPostProcess.onApply = function (effect) {
  73629. effect.setFloat('gain', _this._highlightsGain);
  73630. effect.setFloat('threshold', _this._highlightsThreshold);
  73631. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  73632. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73633. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73634. };
  73635. };
  73636. // colors shifting and distortion
  73637. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  73638. var _this = this;
  73639. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  73640. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  73641. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  73642. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73643. this._depthOfFieldPostProcess.onApply = function (effect) {
  73644. effect.setTexture("depthSampler", _this._depthTexture);
  73645. effect.setTexture("grainSampler", _this._grainTexture);
  73646. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  73647. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  73648. effect.setFloat('grain_amount', _this._grainAmount);
  73649. effect.setBool('blur_noise', _this._blurNoise);
  73650. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73651. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73652. effect.setFloat('distortion', _this._distortion);
  73653. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  73654. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  73655. effect.setFloat('aperture', _this._dofAperture);
  73656. effect.setFloat('darken', _this._dofDarken);
  73657. effect.setFloat('edge_blur', _this._edgeBlur);
  73658. effect.setBool('highlights', (_this._highlightsGain !== -1));
  73659. if (_this._scene.activeCamera) {
  73660. effect.setFloat('near', _this._scene.activeCamera.minZ);
  73661. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  73662. }
  73663. };
  73664. };
  73665. // creates a black and white random noise texture, 512x512
  73666. LensRenderingPipeline.prototype._createGrainTexture = function () {
  73667. var size = 512;
  73668. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73669. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73670. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73671. var context = this._grainTexture.getContext();
  73672. var rand = function (min, max) {
  73673. return Math.random() * (max - min) + min;
  73674. };
  73675. var value;
  73676. for (var x = 0; x < size; x++) {
  73677. for (var y = 0; y < size; y++) {
  73678. value = Math.floor(rand(0.42, 0.58) * 255);
  73679. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  73680. context.fillRect(x, y, 1, 1);
  73681. }
  73682. }
  73683. this._grainTexture.update(false);
  73684. };
  73685. return LensRenderingPipeline;
  73686. }(BABYLON.PostProcessRenderPipeline));
  73687. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  73688. })(BABYLON || (BABYLON = {}));
  73689. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  73690. var BABYLON;
  73691. (function (BABYLON) {
  73692. var StandardRenderingPipeline = /** @class */ (function (_super) {
  73693. __extends(StandardRenderingPipeline, _super);
  73694. /**
  73695. * @constructor
  73696. * @param {string} name - The rendering pipeline name
  73697. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73698. * @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)
  73699. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  73700. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73701. */
  73702. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  73703. if (originalPostProcess === void 0) { originalPostProcess = null; }
  73704. var _this = _super.call(this, scene.getEngine(), name) || this;
  73705. _this.downSampleX4PostProcess = null;
  73706. _this.brightPassPostProcess = null;
  73707. _this.blurHPostProcesses = [];
  73708. _this.blurVPostProcesses = [];
  73709. _this.textureAdderPostProcess = null;
  73710. _this.volumetricLightPostProcess = null;
  73711. _this.volumetricLightSmoothXPostProcess = null;
  73712. _this.volumetricLightSmoothYPostProcess = null;
  73713. _this.volumetricLightMergePostProces = null;
  73714. _this.volumetricLightFinalPostProcess = null;
  73715. _this.luminancePostProcess = null;
  73716. _this.luminanceDownSamplePostProcesses = [];
  73717. _this.hdrPostProcess = null;
  73718. _this.textureAdderFinalPostProcess = null;
  73719. _this.lensFlareFinalPostProcess = null;
  73720. _this.hdrFinalPostProcess = null;
  73721. _this.lensFlarePostProcess = null;
  73722. _this.lensFlareComposePostProcess = null;
  73723. _this.motionBlurPostProcess = null;
  73724. _this.depthOfFieldPostProcess = null;
  73725. // Values
  73726. _this.brightThreshold = 1.0;
  73727. _this.blurWidth = 512.0;
  73728. _this.horizontalBlur = false;
  73729. _this.exposure = 1.0;
  73730. _this.lensTexture = null;
  73731. _this.volumetricLightCoefficient = 0.2;
  73732. _this.volumetricLightPower = 4.0;
  73733. _this.volumetricLightBlurScale = 64.0;
  73734. _this.sourceLight = null;
  73735. _this.hdrMinimumLuminance = 1.0;
  73736. _this.hdrDecreaseRate = 0.5;
  73737. _this.hdrIncreaseRate = 0.5;
  73738. _this.lensColorTexture = null;
  73739. _this.lensFlareStrength = 20.0;
  73740. _this.lensFlareGhostDispersal = 1.4;
  73741. _this.lensFlareHaloWidth = 0.7;
  73742. _this.lensFlareDistortionStrength = 16.0;
  73743. _this.lensStarTexture = null;
  73744. _this.lensFlareDirtTexture = null;
  73745. _this.depthOfFieldDistance = 10.0;
  73746. _this.depthOfFieldBlurWidth = 64.0;
  73747. _this.motionStrength = 1.0;
  73748. // IAnimatable
  73749. _this.animations = [];
  73750. _this._currentDepthOfFieldSource = null;
  73751. _this._hdrCurrentLuminance = 1.0;
  73752. // Getters and setters
  73753. _this._bloomEnabled = true;
  73754. _this._depthOfFieldEnabled = false;
  73755. _this._vlsEnabled = false;
  73756. _this._lensFlareEnabled = false;
  73757. _this._hdrEnabled = false;
  73758. _this._motionBlurEnabled = false;
  73759. _this._motionBlurSamples = 64.0;
  73760. _this._volumetricLightStepsCount = 50.0;
  73761. _this._cameras = cameras || [];
  73762. // Initialize
  73763. _this._scene = scene;
  73764. _this._basePostProcess = originalPostProcess;
  73765. _this._ratio = ratio;
  73766. // Misc
  73767. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73768. // Finish
  73769. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73770. _this._buildPipeline();
  73771. return _this;
  73772. }
  73773. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  73774. get: function () {
  73775. return this._bloomEnabled;
  73776. },
  73777. set: function (enabled) {
  73778. if (this._bloomEnabled === enabled) {
  73779. return;
  73780. }
  73781. this._bloomEnabled = enabled;
  73782. this._buildPipeline();
  73783. },
  73784. enumerable: true,
  73785. configurable: true
  73786. });
  73787. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  73788. get: function () {
  73789. return this._depthOfFieldEnabled;
  73790. },
  73791. set: function (enabled) {
  73792. if (this._depthOfFieldEnabled === enabled) {
  73793. return;
  73794. }
  73795. this._depthOfFieldEnabled = enabled;
  73796. this._buildPipeline();
  73797. },
  73798. enumerable: true,
  73799. configurable: true
  73800. });
  73801. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  73802. get: function () {
  73803. return this._lensFlareEnabled;
  73804. },
  73805. set: function (enabled) {
  73806. if (this._lensFlareEnabled === enabled) {
  73807. return;
  73808. }
  73809. this._lensFlareEnabled = enabled;
  73810. this._buildPipeline();
  73811. },
  73812. enumerable: true,
  73813. configurable: true
  73814. });
  73815. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  73816. get: function () {
  73817. return this._hdrEnabled;
  73818. },
  73819. set: function (enabled) {
  73820. if (this._hdrEnabled === enabled) {
  73821. return;
  73822. }
  73823. this._hdrEnabled = enabled;
  73824. this._buildPipeline();
  73825. },
  73826. enumerable: true,
  73827. configurable: true
  73828. });
  73829. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  73830. get: function () {
  73831. return this._vlsEnabled;
  73832. },
  73833. set: function (enabled) {
  73834. if (this._vlsEnabled === enabled) {
  73835. return;
  73836. }
  73837. if (enabled) {
  73838. var geometry = this._scene.enableGeometryBufferRenderer();
  73839. if (!geometry) {
  73840. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  73841. return;
  73842. }
  73843. }
  73844. this._vlsEnabled = enabled;
  73845. this._buildPipeline();
  73846. },
  73847. enumerable: true,
  73848. configurable: true
  73849. });
  73850. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  73851. get: function () {
  73852. return this._motionBlurEnabled;
  73853. },
  73854. set: function (enabled) {
  73855. if (this._motionBlurEnabled === enabled) {
  73856. return;
  73857. }
  73858. this._motionBlurEnabled = enabled;
  73859. this._buildPipeline();
  73860. },
  73861. enumerable: true,
  73862. configurable: true
  73863. });
  73864. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  73865. get: function () {
  73866. return this._volumetricLightStepsCount;
  73867. },
  73868. set: function (count) {
  73869. if (this.volumetricLightPostProcess) {
  73870. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  73871. }
  73872. this._volumetricLightStepsCount = count;
  73873. },
  73874. enumerable: true,
  73875. configurable: true
  73876. });
  73877. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  73878. get: function () {
  73879. return this._motionBlurSamples;
  73880. },
  73881. set: function (samples) {
  73882. if (this.motionBlurPostProcess) {
  73883. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  73884. }
  73885. this._motionBlurSamples = samples;
  73886. },
  73887. enumerable: true,
  73888. configurable: true
  73889. });
  73890. StandardRenderingPipeline.prototype._buildPipeline = function () {
  73891. var _this = this;
  73892. var ratio = this._ratio;
  73893. var scene = this._scene;
  73894. this._disposePostProcesses();
  73895. this._reset();
  73896. // Create pass post-process
  73897. if (!this._basePostProcess) {
  73898. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  73899. this.originalPostProcess.onApply = function (effect) {
  73900. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  73901. };
  73902. }
  73903. else {
  73904. this.originalPostProcess = this._basePostProcess;
  73905. }
  73906. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  73907. this._currentDepthOfFieldSource = this.originalPostProcess;
  73908. if (this._bloomEnabled) {
  73909. // Create down sample X4 post-process
  73910. this._createDownSampleX4PostProcess(scene, ratio / 2);
  73911. // Create bright pass post-process
  73912. this._createBrightPassPostProcess(scene, ratio / 2);
  73913. // Create gaussian blur post-processes (down sampling blurs)
  73914. this._createBlurPostProcesses(scene, ratio / 4, 1);
  73915. // Create texture adder post-process
  73916. this._createTextureAdderPostProcess(scene, ratio);
  73917. // Create depth-of-field source post-process
  73918. 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);
  73919. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  73920. }
  73921. if (this._vlsEnabled) {
  73922. // Create volumetric light
  73923. this._createVolumetricLightPostProcess(scene, ratio);
  73924. // Create volumetric light final post-process
  73925. 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);
  73926. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  73927. }
  73928. if (this._lensFlareEnabled) {
  73929. // Create lens flare post-process
  73930. this._createLensFlarePostProcess(scene, ratio);
  73931. // Create depth-of-field source post-process post lens-flare and disable it now
  73932. 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);
  73933. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  73934. }
  73935. if (this._hdrEnabled) {
  73936. // Create luminance
  73937. this._createLuminancePostProcesses(scene, this._floatTextureType);
  73938. // Create HDR
  73939. this._createHdrPostProcess(scene, ratio);
  73940. // Create depth-of-field source post-process post hdr and disable it now
  73941. 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);
  73942. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  73943. }
  73944. if (this._depthOfFieldEnabled) {
  73945. // Create gaussian blur used by depth-of-field
  73946. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  73947. // Create depth-of-field post-process
  73948. this._createDepthOfFieldPostProcess(scene, ratio);
  73949. }
  73950. if (this._motionBlurEnabled) {
  73951. // Create motion blur post-process
  73952. this._createMotionBlurPostProcess(scene, ratio);
  73953. }
  73954. if (this._cameras !== null) {
  73955. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  73956. }
  73957. };
  73958. // Down Sample X4 Post-Processs
  73959. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  73960. var _this = this;
  73961. var downSampleX4Offsets = new Array(32);
  73962. 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);
  73963. this.downSampleX4PostProcess.onApply = function (effect) {
  73964. var id = 0;
  73965. var width = _this.downSampleX4PostProcess.width;
  73966. var height = _this.downSampleX4PostProcess.height;
  73967. for (var i = -2; i < 2; i++) {
  73968. for (var j = -2; j < 2; j++) {
  73969. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  73970. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  73971. id += 2;
  73972. }
  73973. }
  73974. effect.setArray2("dsOffsets", downSampleX4Offsets);
  73975. };
  73976. // Add to pipeline
  73977. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  73978. };
  73979. // Brightpass Post-Process
  73980. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  73981. var _this = this;
  73982. var brightOffsets = new Array(8);
  73983. 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);
  73984. this.brightPassPostProcess.onApply = function (effect) {
  73985. var sU = (1.0 / _this.brightPassPostProcess.width);
  73986. var sV = (1.0 / _this.brightPassPostProcess.height);
  73987. brightOffsets[0] = -0.5 * sU;
  73988. brightOffsets[1] = 0.5 * sV;
  73989. brightOffsets[2] = 0.5 * sU;
  73990. brightOffsets[3] = 0.5 * sV;
  73991. brightOffsets[4] = -0.5 * sU;
  73992. brightOffsets[5] = -0.5 * sV;
  73993. brightOffsets[6] = 0.5 * sU;
  73994. brightOffsets[7] = -0.5 * sV;
  73995. effect.setArray2("dsOffsets", brightOffsets);
  73996. effect.setFloat("brightThreshold", _this.brightThreshold);
  73997. };
  73998. // Add to pipeline
  73999. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74000. };
  74001. // Create blur H&V post-processes
  74002. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74003. var _this = this;
  74004. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74005. var engine = scene.getEngine();
  74006. 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);
  74007. 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);
  74008. blurX.onActivateObservable.add(function () {
  74009. var dw = blurX.width / engine.getRenderWidth();
  74010. blurX.kernel = _this[blurWidthKey] * dw;
  74011. });
  74012. blurY.onActivateObservable.add(function () {
  74013. var dw = blurY.height / engine.getRenderHeight();
  74014. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74015. });
  74016. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74017. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74018. this.blurHPostProcesses.push(blurX);
  74019. this.blurVPostProcesses.push(blurY);
  74020. };
  74021. // Create texture adder post-process
  74022. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74023. var _this = this;
  74024. 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);
  74025. this.textureAdderPostProcess.onApply = function (effect) {
  74026. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74027. effect.setTexture("lensSampler", _this.lensTexture);
  74028. effect.setFloat("exposure", _this.exposure);
  74029. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74030. };
  74031. // Add to pipeline
  74032. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74033. };
  74034. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74035. var _this = this;
  74036. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74037. geometryRenderer.enablePosition = true;
  74038. var geometry = geometryRenderer.getGBuffer();
  74039. // Base post-process
  74040. 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));
  74041. var depthValues = BABYLON.Vector2.Zero();
  74042. this.volumetricLightPostProcess.onApply = function (effect) {
  74043. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74044. var generator = _this.sourceLight.getShadowGenerator();
  74045. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74046. effect.setTexture("positionSampler", geometry.textures[2]);
  74047. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74048. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74049. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74050. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74051. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74052. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74053. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74054. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74055. effect.setVector2("depthValues", depthValues);
  74056. }
  74057. };
  74058. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74059. // Smooth
  74060. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74061. // Merge
  74062. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74063. this.volumetricLightMergePostProces.onApply = function (effect) {
  74064. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74065. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74066. };
  74067. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74068. };
  74069. // Create luminance
  74070. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74071. var _this = this;
  74072. // Create luminance
  74073. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74074. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74075. var offsets = [];
  74076. this.luminancePostProcess.onApply = function (effect) {
  74077. var sU = (1.0 / _this.luminancePostProcess.width);
  74078. var sV = (1.0 / _this.luminancePostProcess.height);
  74079. offsets[0] = -0.5 * sU;
  74080. offsets[1] = 0.5 * sV;
  74081. offsets[2] = 0.5 * sU;
  74082. offsets[3] = 0.5 * sV;
  74083. offsets[4] = -0.5 * sU;
  74084. offsets[5] = -0.5 * sV;
  74085. offsets[6] = 0.5 * sU;
  74086. offsets[7] = -0.5 * sV;
  74087. effect.setArray2("lumOffsets", offsets);
  74088. };
  74089. // Add to pipeline
  74090. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74091. // Create down sample luminance
  74092. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74093. var size = Math.pow(3, i);
  74094. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74095. if (i === 0) {
  74096. defines += "#define FINAL_DOWN_SAMPLER";
  74097. }
  74098. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74099. this.luminanceDownSamplePostProcesses.push(postProcess);
  74100. }
  74101. // Create callbacks and add effects
  74102. var lastLuminance = this.luminancePostProcess;
  74103. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74104. var downSampleOffsets = new Array(18);
  74105. pp.onApply = function (effect) {
  74106. if (!lastLuminance) {
  74107. return;
  74108. }
  74109. var id = 0;
  74110. for (var x = -1; x < 2; x++) {
  74111. for (var y = -1; y < 2; y++) {
  74112. downSampleOffsets[id] = x / lastLuminance.width;
  74113. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74114. id += 2;
  74115. }
  74116. }
  74117. effect.setArray2("dsOffsets", downSampleOffsets);
  74118. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74119. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74120. lastLuminance = _this.luminancePostProcess;
  74121. }
  74122. else {
  74123. lastLuminance = pp;
  74124. }
  74125. };
  74126. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74127. pp.onAfterRender = function (effect) {
  74128. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74129. 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);
  74130. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74131. };
  74132. }
  74133. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74134. });
  74135. };
  74136. // Create HDR post-process
  74137. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74138. var _this = this;
  74139. 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);
  74140. var outputLiminance = 1;
  74141. var time = 0;
  74142. var lastTime = 0;
  74143. this.hdrPostProcess.onApply = function (effect) {
  74144. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74145. time += scene.getEngine().getDeltaTime();
  74146. if (outputLiminance < 0) {
  74147. outputLiminance = _this._hdrCurrentLuminance;
  74148. }
  74149. else {
  74150. var dt = (lastTime - time) / 1000.0;
  74151. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74152. outputLiminance += _this.hdrDecreaseRate * dt;
  74153. }
  74154. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74155. outputLiminance -= _this.hdrIncreaseRate * dt;
  74156. }
  74157. else {
  74158. outputLiminance = _this._hdrCurrentLuminance;
  74159. }
  74160. }
  74161. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74162. effect.setFloat("averageLuminance", outputLiminance);
  74163. lastTime = time;
  74164. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74165. };
  74166. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74167. };
  74168. // Create lens flare post-process
  74169. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74170. var _this = this;
  74171. 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);
  74172. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74173. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74174. 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);
  74175. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74176. var resolution = new BABYLON.Vector2(0, 0);
  74177. // Lens flare
  74178. this.lensFlarePostProcess.onApply = function (effect) {
  74179. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74180. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74181. effect.setFloat("strength", _this.lensFlareStrength);
  74182. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74183. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74184. // Shift
  74185. resolution.x = _this.lensFlarePostProcess.width;
  74186. resolution.y = _this.lensFlarePostProcess.height;
  74187. effect.setVector2("resolution", resolution);
  74188. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74189. };
  74190. // Compose
  74191. 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);
  74192. 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);
  74193. this.lensFlareComposePostProcess.onApply = function (effect) {
  74194. if (!_this._scene.activeCamera) {
  74195. return;
  74196. }
  74197. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74198. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74199. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74200. // Lens start rotation matrix
  74201. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74202. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74203. 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));
  74204. camRot *= 4.0;
  74205. 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);
  74206. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74207. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74208. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74209. };
  74210. };
  74211. // Create depth-of-field post-process
  74212. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74213. var _this = this;
  74214. 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);
  74215. this.depthOfFieldPostProcess.onApply = function (effect) {
  74216. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74217. effect.setTexture("depthSampler", _this._getDepthTexture());
  74218. effect.setFloat("distance", _this.depthOfFieldDistance);
  74219. };
  74220. // Add to pipeline
  74221. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74222. };
  74223. // Create motion blur post-process
  74224. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74225. var _this = this;
  74226. 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);
  74227. var motionScale = 0;
  74228. var prevViewProjection = BABYLON.Matrix.Identity();
  74229. var invViewProjection = BABYLON.Matrix.Identity();
  74230. var viewProjection = BABYLON.Matrix.Identity();
  74231. var screenSize = BABYLON.Vector2.Zero();
  74232. this.motionBlurPostProcess.onApply = function (effect) {
  74233. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74234. viewProjection.invertToRef(invViewProjection);
  74235. effect.setMatrix("inverseViewProjection", invViewProjection);
  74236. effect.setMatrix("prevViewProjection", prevViewProjection);
  74237. prevViewProjection = viewProjection;
  74238. screenSize.x = _this.motionBlurPostProcess.width;
  74239. screenSize.y = _this.motionBlurPostProcess.height;
  74240. effect.setVector2("screenSize", screenSize);
  74241. motionScale = scene.getEngine().getFps() / 60.0;
  74242. effect.setFloat("motionScale", motionScale);
  74243. effect.setFloat("motionStrength", _this.motionStrength);
  74244. effect.setTexture("depthSampler", _this._getDepthTexture());
  74245. };
  74246. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74247. };
  74248. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74249. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74250. var renderer = this._scene.enableGeometryBufferRenderer();
  74251. return renderer.getGBuffer().textures[0];
  74252. }
  74253. return this._scene.enableDepthRenderer().getDepthMap();
  74254. };
  74255. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74256. for (var i = 0; i < this._cameras.length; i++) {
  74257. var camera = this._cameras[i];
  74258. if (this.originalPostProcess) {
  74259. this.originalPostProcess.dispose(camera);
  74260. }
  74261. if (this.downSampleX4PostProcess) {
  74262. this.downSampleX4PostProcess.dispose(camera);
  74263. }
  74264. if (this.brightPassPostProcess) {
  74265. this.brightPassPostProcess.dispose(camera);
  74266. }
  74267. if (this.textureAdderPostProcess) {
  74268. this.textureAdderPostProcess.dispose(camera);
  74269. }
  74270. if (this.textureAdderFinalPostProcess) {
  74271. this.textureAdderFinalPostProcess.dispose(camera);
  74272. }
  74273. if (this.volumetricLightPostProcess) {
  74274. this.volumetricLightPostProcess.dispose(camera);
  74275. }
  74276. if (this.volumetricLightSmoothXPostProcess) {
  74277. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74278. }
  74279. if (this.volumetricLightSmoothYPostProcess) {
  74280. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74281. }
  74282. if (this.volumetricLightMergePostProces) {
  74283. this.volumetricLightMergePostProces.dispose(camera);
  74284. }
  74285. if (this.volumetricLightFinalPostProcess) {
  74286. this.volumetricLightFinalPostProcess.dispose(camera);
  74287. }
  74288. if (this.lensFlarePostProcess) {
  74289. this.lensFlarePostProcess.dispose(camera);
  74290. }
  74291. if (this.lensFlareComposePostProcess) {
  74292. this.lensFlareComposePostProcess.dispose(camera);
  74293. }
  74294. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74295. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74296. }
  74297. if (this.luminancePostProcess) {
  74298. this.luminancePostProcess.dispose(camera);
  74299. }
  74300. if (this.hdrPostProcess) {
  74301. this.hdrPostProcess.dispose(camera);
  74302. }
  74303. if (this.hdrFinalPostProcess) {
  74304. this.hdrFinalPostProcess.dispose(camera);
  74305. }
  74306. if (this.depthOfFieldPostProcess) {
  74307. this.depthOfFieldPostProcess.dispose(camera);
  74308. }
  74309. if (this.motionBlurPostProcess) {
  74310. this.motionBlurPostProcess.dispose(camera);
  74311. }
  74312. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74313. this.blurHPostProcesses[j].dispose(camera);
  74314. }
  74315. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74316. this.blurVPostProcesses[j].dispose(camera);
  74317. }
  74318. }
  74319. this.originalPostProcess = null;
  74320. this.downSampleX4PostProcess = null;
  74321. this.brightPassPostProcess = null;
  74322. this.textureAdderPostProcess = null;
  74323. this.textureAdderFinalPostProcess = null;
  74324. this.volumetricLightPostProcess = null;
  74325. this.volumetricLightSmoothXPostProcess = null;
  74326. this.volumetricLightSmoothYPostProcess = null;
  74327. this.volumetricLightMergePostProces = null;
  74328. this.volumetricLightFinalPostProcess = null;
  74329. this.lensFlarePostProcess = null;
  74330. this.lensFlareComposePostProcess = null;
  74331. this.luminancePostProcess = null;
  74332. this.hdrPostProcess = null;
  74333. this.hdrFinalPostProcess = null;
  74334. this.depthOfFieldPostProcess = null;
  74335. this.motionBlurPostProcess = null;
  74336. this.luminanceDownSamplePostProcesses = [];
  74337. this.blurHPostProcesses = [];
  74338. this.blurVPostProcesses = [];
  74339. };
  74340. /**
  74341. * Dispose of the pipeline and stop all post processes
  74342. */
  74343. StandardRenderingPipeline.prototype.dispose = function () {
  74344. this._disposePostProcesses();
  74345. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74346. _super.prototype.dispose.call(this);
  74347. };
  74348. /**
  74349. * Serialize the rendering pipeline (Used when exporting)
  74350. * @returns the serialized object
  74351. */
  74352. StandardRenderingPipeline.prototype.serialize = function () {
  74353. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74354. if (this.sourceLight) {
  74355. serializationObject.sourceLightId = this.sourceLight.id;
  74356. }
  74357. serializationObject.customType = "StandardRenderingPipeline";
  74358. return serializationObject;
  74359. };
  74360. /**
  74361. * Parse the serialized pipeline
  74362. * @param source Source pipeline.
  74363. * @param scene The scene to load the pipeline to.
  74364. * @param rootUrl The URL of the serialized pipeline.
  74365. * @returns An instantiated pipeline from the serialized object.
  74366. */
  74367. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74368. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74369. if (source.sourceLightId) {
  74370. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74371. }
  74372. return p;
  74373. };
  74374. // Luminance steps
  74375. StandardRenderingPipeline.LuminanceSteps = 6;
  74376. __decorate([
  74377. BABYLON.serialize()
  74378. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74379. __decorate([
  74380. BABYLON.serialize()
  74381. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74382. __decorate([
  74383. BABYLON.serialize()
  74384. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74385. __decorate([
  74386. BABYLON.serialize()
  74387. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74388. __decorate([
  74389. BABYLON.serializeAsTexture("lensTexture")
  74390. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74391. __decorate([
  74392. BABYLON.serialize()
  74393. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74394. __decorate([
  74395. BABYLON.serialize()
  74396. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74397. __decorate([
  74398. BABYLON.serialize()
  74399. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74400. __decorate([
  74401. BABYLON.serialize()
  74402. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74403. __decorate([
  74404. BABYLON.serialize()
  74405. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74406. __decorate([
  74407. BABYLON.serialize()
  74408. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74409. __decorate([
  74410. BABYLON.serializeAsTexture("lensColorTexture")
  74411. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74412. __decorate([
  74413. BABYLON.serialize()
  74414. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74415. __decorate([
  74416. BABYLON.serialize()
  74417. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74418. __decorate([
  74419. BABYLON.serialize()
  74420. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74421. __decorate([
  74422. BABYLON.serialize()
  74423. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74424. __decorate([
  74425. BABYLON.serializeAsTexture("lensStarTexture")
  74426. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74427. __decorate([
  74428. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74429. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74430. __decorate([
  74431. BABYLON.serialize()
  74432. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74433. __decorate([
  74434. BABYLON.serialize()
  74435. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74436. __decorate([
  74437. BABYLON.serialize()
  74438. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74439. __decorate([
  74440. BABYLON.serialize()
  74441. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  74442. __decorate([
  74443. BABYLON.serialize()
  74444. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  74445. __decorate([
  74446. BABYLON.serialize()
  74447. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  74448. __decorate([
  74449. BABYLON.serialize()
  74450. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  74451. __decorate([
  74452. BABYLON.serialize()
  74453. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  74454. __decorate([
  74455. BABYLON.serialize()
  74456. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  74457. __decorate([
  74458. BABYLON.serialize()
  74459. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  74460. __decorate([
  74461. BABYLON.serialize()
  74462. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  74463. __decorate([
  74464. BABYLON.serialize()
  74465. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  74466. return StandardRenderingPipeline;
  74467. }(BABYLON.PostProcessRenderPipeline));
  74468. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  74469. })(BABYLON || (BABYLON = {}));
  74470. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  74471. var BABYLON;
  74472. (function (BABYLON) {
  74473. var FxaaPostProcess = /** @class */ (function (_super) {
  74474. __extends(FxaaPostProcess, _super);
  74475. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74476. if (camera === void 0) { camera = null; }
  74477. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74478. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  74479. _this.onApplyObservable.add(function (effect) {
  74480. var texelSize = _this.texelSize;
  74481. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  74482. });
  74483. return _this;
  74484. }
  74485. return FxaaPostProcess;
  74486. }(BABYLON.PostProcess));
  74487. BABYLON.FxaaPostProcess = FxaaPostProcess;
  74488. })(BABYLON || (BABYLON = {}));
  74489. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  74490. var BABYLON;
  74491. (function (BABYLON) {
  74492. /**
  74493. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  74494. */
  74495. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  74496. __extends(ChromaticAberrationPostProcess, _super);
  74497. /**
  74498. * Creates a new instance ChromaticAberrationPostProcess
  74499. * @param name The name of the effect.
  74500. * @param screenWidth The width of the screen to apply the effect on.
  74501. * @param screenHeight The height of the screen to apply the effect on.
  74502. * @param options The required width/height ratio to downsize to before computing the render pass.
  74503. * @param camera The camera to apply the render pass to.
  74504. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74505. * @param engine The engine which the post process will be applied. (default: current engine)
  74506. * @param reusable If the post process can be reused on the same frame. (default: false)
  74507. * @param textureType Type of textures used when performing the post process. (default: 0)
  74508. * @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)
  74509. */
  74510. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74511. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74512. if (blockCompilation === void 0) { blockCompilation = false; }
  74513. 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;
  74514. /**
  74515. * The amount of seperation of rgb channels (default: 30)
  74516. */
  74517. _this.aberrationAmount = 30;
  74518. /**
  74519. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  74520. */
  74521. _this.radialIntensity = 0;
  74522. /**
  74523. * 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))
  74524. */
  74525. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  74526. /**
  74527. * 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))
  74528. */
  74529. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  74530. _this.onApplyObservable.add(function (effect) {
  74531. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  74532. effect.setFloat('screen_width', screenWidth);
  74533. effect.setFloat('screen_height', screenHeight);
  74534. effect.setFloat('radialIntensity', _this.radialIntensity);
  74535. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  74536. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  74537. });
  74538. return _this;
  74539. }
  74540. return ChromaticAberrationPostProcess;
  74541. }(BABYLON.PostProcess));
  74542. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  74543. })(BABYLON || (BABYLON = {}));
  74544. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  74545. var BABYLON;
  74546. (function (BABYLON) {
  74547. /**
  74548. * The GrainPostProcess adds noise to the image at mid luminance levels
  74549. */
  74550. var GrainPostProcess = /** @class */ (function (_super) {
  74551. __extends(GrainPostProcess, _super);
  74552. /**
  74553. * Creates a new instance of @see GrainPostProcess
  74554. * @param name The name of the effect.
  74555. * @param options The required width/height ratio to downsize to before computing the render pass.
  74556. * @param camera The camera to apply the render pass to.
  74557. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74558. * @param engine The engine which the post process will be applied. (default: current engine)
  74559. * @param reusable If the post process can be reused on the same frame. (default: false)
  74560. * @param textureType Type of textures used when performing the post process. (default: 0)
  74561. * @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)
  74562. */
  74563. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74564. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74565. if (blockCompilation === void 0) { blockCompilation = false; }
  74566. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74567. /**
  74568. * The intensity of the grain added (default: 30)
  74569. */
  74570. _this.intensity = 30;
  74571. /**
  74572. * If the grain should be randomized on every frame
  74573. */
  74574. _this.animated = false;
  74575. _this.onApplyObservable.add(function (effect) {
  74576. effect.setFloat('intensity', _this.intensity);
  74577. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  74578. });
  74579. return _this;
  74580. }
  74581. return GrainPostProcess;
  74582. }(BABYLON.PostProcess));
  74583. BABYLON.GrainPostProcess = GrainPostProcess;
  74584. })(BABYLON || (BABYLON = {}));
  74585. //# sourceMappingURL=babylon.grainPostProcess.js.map
  74586. var BABYLON;
  74587. (function (BABYLON) {
  74588. /**
  74589. * The SharpenPostProcess applies a sharpen kernel to every pixel
  74590. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  74591. */
  74592. var SharpenPostProcess = /** @class */ (function (_super) {
  74593. __extends(SharpenPostProcess, _super);
  74594. /**
  74595. * Creates a new instance ConvolutionPostProcess
  74596. * @param name The name of the effect.
  74597. * @param options The required width/height ratio to downsize to before computing the render pass.
  74598. * @param camera The camera to apply the render pass to.
  74599. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74600. * @param engine The engine which the post process will be applied. (default: current engine)
  74601. * @param reusable If the post process can be reused on the same frame. (default: false)
  74602. * @param textureType Type of textures used when performing the post process. (default: 0)
  74603. * @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)
  74604. */
  74605. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74606. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74607. if (blockCompilation === void 0) { blockCompilation = false; }
  74608. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74609. /**
  74610. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  74611. */
  74612. _this.colorAmount = 1.0;
  74613. /**
  74614. * How much sharpness should be applied (default: 0.3)
  74615. */
  74616. _this.edgeAmount = 0.3;
  74617. _this.onApply = function (effect) {
  74618. effect.setFloat2("screenSize", _this.width, _this.height);
  74619. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  74620. };
  74621. return _this;
  74622. }
  74623. return SharpenPostProcess;
  74624. }(BABYLON.PostProcess));
  74625. BABYLON.SharpenPostProcess = SharpenPostProcess;
  74626. })(BABYLON || (BABYLON = {}));
  74627. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  74628. var BABYLON;
  74629. (function (BABYLON) {
  74630. /**
  74631. * The Blur Post Process which blurs an image based on a kernel and direction.
  74632. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  74633. */
  74634. var BlurPostProcess = /** @class */ (function (_super) {
  74635. __extends(BlurPostProcess, _super);
  74636. /**
  74637. * Creates a new instance BlurPostProcess
  74638. * @param name The name of the effect.
  74639. * @param direction The direction in which to blur the image.
  74640. * @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.
  74641. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  74642. * @param camera The camera to apply the render pass to.
  74643. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74644. * @param engine The engine which the post process will be applied. (default: current engine)
  74645. * @param reusable If the post process can be reused on the same frame. (default: false)
  74646. * @param textureType Type of textures used when performing the post process. (default: 0)
  74647. * @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)
  74648. */
  74649. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  74650. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74651. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74652. if (defines === void 0) { defines = ""; }
  74653. if (blockCompilation === void 0) { blockCompilation = false; }
  74654. 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;
  74655. _this.direction = direction;
  74656. _this.blockCompilation = blockCompilation;
  74657. _this._packedFloat = false;
  74658. _this._staticDefines = "";
  74659. _this._staticDefines = defines;
  74660. _this.onApplyObservable.add(function (effect) {
  74661. if (_this._outputTexture) {
  74662. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  74663. }
  74664. else {
  74665. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  74666. }
  74667. });
  74668. _this.kernel = kernel;
  74669. return _this;
  74670. }
  74671. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  74672. /**
  74673. * Gets the length in pixels of the blur sample region
  74674. */
  74675. get: function () {
  74676. return this._idealKernel;
  74677. },
  74678. /**
  74679. * Sets the length in pixels of the blur sample region
  74680. */
  74681. set: function (v) {
  74682. if (this._idealKernel === v) {
  74683. return;
  74684. }
  74685. v = Math.max(v, 1);
  74686. this._idealKernel = v;
  74687. this._kernel = this._nearestBestKernel(v);
  74688. if (!this.blockCompilation) {
  74689. this._updateParameters();
  74690. }
  74691. },
  74692. enumerable: true,
  74693. configurable: true
  74694. });
  74695. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  74696. /**
  74697. * Gets wether or not the blur is unpacking/repacking floats
  74698. */
  74699. get: function () {
  74700. return this._packedFloat;
  74701. },
  74702. /**
  74703. * Sets wether or not the blur needs to unpack/repack floats
  74704. */
  74705. set: function (v) {
  74706. if (this._packedFloat === v) {
  74707. return;
  74708. }
  74709. this._packedFloat = v;
  74710. if (!this.blockCompilation) {
  74711. this._updateParameters();
  74712. }
  74713. },
  74714. enumerable: true,
  74715. configurable: true
  74716. });
  74717. /**
  74718. * Updates the effect with the current post process compile time values and recompiles the shader.
  74719. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74720. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74721. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74722. * @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
  74723. * @param onCompiled Called when the shader has been compiled.
  74724. * @param onError Called if there is an error when compiling a shader.
  74725. */
  74726. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74727. if (defines === void 0) { defines = null; }
  74728. if (uniforms === void 0) { uniforms = null; }
  74729. if (samplers === void 0) { samplers = null; }
  74730. this._updateParameters(onCompiled, onError);
  74731. };
  74732. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  74733. // Generate sampling offsets and weights
  74734. var N = this._kernel;
  74735. var centerIndex = (N - 1) / 2;
  74736. // Generate Gaussian sampling weights over kernel
  74737. var offsets = [];
  74738. var weights = [];
  74739. var totalWeight = 0;
  74740. for (var i = 0; i < N; i++) {
  74741. var u = i / (N - 1);
  74742. var w = this._gaussianWeight(u * 2.0 - 1);
  74743. offsets[i] = (i - centerIndex);
  74744. weights[i] = w;
  74745. totalWeight += w;
  74746. }
  74747. // Normalize weights
  74748. for (var i = 0; i < weights.length; i++) {
  74749. weights[i] /= totalWeight;
  74750. }
  74751. // Optimize: combine samples to take advantage of hardware linear sampling
  74752. // Walk from left to center, combining pairs (symmetrically)
  74753. var linearSamplingWeights = [];
  74754. var linearSamplingOffsets = [];
  74755. var linearSamplingMap = [];
  74756. for (var i = 0; i <= centerIndex; i += 2) {
  74757. var j = Math.min(i + 1, Math.floor(centerIndex));
  74758. var singleCenterSample = i === j;
  74759. if (singleCenterSample) {
  74760. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74761. }
  74762. else {
  74763. var sharedCell = j === centerIndex;
  74764. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  74765. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  74766. if (offsetLinear === 0) {
  74767. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74768. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  74769. }
  74770. else {
  74771. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  74772. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  74773. }
  74774. }
  74775. }
  74776. for (var i = 0; i < linearSamplingMap.length; i++) {
  74777. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  74778. linearSamplingWeights[i] = linearSamplingMap[i].w;
  74779. }
  74780. // Replace with optimized
  74781. offsets = linearSamplingOffsets;
  74782. weights = linearSamplingWeights;
  74783. // Generate shaders
  74784. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  74785. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  74786. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  74787. var defines = "";
  74788. defines += this._staticDefines;
  74789. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  74790. if (this._staticDefines.indexOf("DOF") != -1) {
  74791. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  74792. varyingCount--;
  74793. }
  74794. for (var i = 0; i < varyingCount; i++) {
  74795. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  74796. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  74797. }
  74798. var depCount = 0;
  74799. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  74800. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  74801. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  74802. depCount++;
  74803. }
  74804. if (this.packedFloat) {
  74805. defines += "#define PACKEDFLOAT 1";
  74806. }
  74807. this.blockCompilation = false;
  74808. _super.prototype.updateEffect.call(this, defines, null, null, {
  74809. varyingCount: varyingCount,
  74810. depCount: depCount
  74811. }, onCompiled, onError);
  74812. };
  74813. /**
  74814. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  74815. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  74816. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  74817. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  74818. * The gaps between physical kernels are compensated for in the weighting of the samples
  74819. * @param idealKernel Ideal blur kernel.
  74820. * @return Nearest best kernel.
  74821. */
  74822. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  74823. var v = Math.round(idealKernel);
  74824. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  74825. var k = _a[_i];
  74826. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  74827. return Math.max(k, 3);
  74828. }
  74829. }
  74830. return Math.max(v, 3);
  74831. };
  74832. /**
  74833. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  74834. * @param x The point on the Gaussian distribution to sample.
  74835. * @return the value of the Gaussian function at x.
  74836. */
  74837. BlurPostProcess.prototype._gaussianWeight = function (x) {
  74838. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  74839. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  74840. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  74841. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  74842. // truncated at around 1.3% of peak strength.
  74843. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  74844. var sigma = (1 / 3);
  74845. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  74846. var exponent = -((x * x) / (2.0 * sigma * sigma));
  74847. var weight = (1.0 / denominator) * Math.exp(exponent);
  74848. return weight;
  74849. };
  74850. /**
  74851. * Generates a string that can be used as a floating point number in GLSL.
  74852. * @param x Value to print.
  74853. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  74854. * @return GLSL float string.
  74855. */
  74856. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  74857. if (decimalFigures === void 0) { decimalFigures = 8; }
  74858. return x.toFixed(decimalFigures).replace(/0+$/, '');
  74859. };
  74860. return BlurPostProcess;
  74861. }(BABYLON.PostProcess));
  74862. BABYLON.BlurPostProcess = BlurPostProcess;
  74863. })(BABYLON || (BABYLON = {}));
  74864. //# sourceMappingURL=babylon.blurPostProcess.js.map
  74865. var BABYLON;
  74866. (function (BABYLON) {
  74867. /**
  74868. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  74869. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  74870. * based on samples that have a large difference in distance than the center pixel.
  74871. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74872. */
  74873. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  74874. __extends(DepthOfFieldBlurPostProcess, _super);
  74875. /**
  74876. * Creates a new instance CircleOfConfusionPostProcess
  74877. * @param name The name of the effect.
  74878. * @param scene The scene the effect belongs to.
  74879. * @param direction The direction the blur should be applied.
  74880. * @param kernel The size of the kernel used to blur.
  74881. * @param options The required width/height ratio to downsize to before computing the render pass.
  74882. * @param camera The camera to apply the render pass to.
  74883. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  74884. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  74885. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74886. * @param engine The engine which the post process will be applied. (default: current engine)
  74887. * @param reusable If the post process can be reused on the same frame. (default: false)
  74888. * @param textureType Type of textures used when performing the post process. (default: 0)
  74889. * @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)
  74890. */
  74891. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  74892. if (imageToBlur === void 0) { imageToBlur = null; }
  74893. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74894. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74895. if (blockCompilation === void 0) { blockCompilation = false; }
  74896. 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;
  74897. _this.direction = direction;
  74898. _this.onApplyObservable.add(function (effect) {
  74899. if (imageToBlur != null) {
  74900. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  74901. }
  74902. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74903. if (scene.activeCamera) {
  74904. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  74905. }
  74906. });
  74907. return _this;
  74908. }
  74909. return DepthOfFieldBlurPostProcess;
  74910. }(BABYLON.BlurPostProcess));
  74911. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  74912. })(BABYLON || (BABYLON = {}));
  74913. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  74914. var BABYLON;
  74915. (function (BABYLON) {
  74916. /**
  74917. * Options to be set when merging outputs from the default pipeline.
  74918. */
  74919. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  74920. function DepthOfFieldMergePostProcessOptions() {
  74921. }
  74922. return DepthOfFieldMergePostProcessOptions;
  74923. }());
  74924. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  74925. /**
  74926. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  74927. */
  74928. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  74929. __extends(DepthOfFieldMergePostProcess, _super);
  74930. /**
  74931. * Creates a new instance of DepthOfFieldMergePostProcess
  74932. * @param name The name of the effect.
  74933. * @param originalFromInput Post process which's input will be used for the merge.
  74934. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  74935. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  74936. * @param options The required width/height ratio to downsize to before computing the render pass.
  74937. * @param camera The camera to apply the render pass to.
  74938. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74939. * @param engine The engine which the post process will be applied. (default: current engine)
  74940. * @param reusable If the post process can be reused on the same frame. (default: false)
  74941. * @param textureType Type of textures used when performing the post process. (default: 0)
  74942. * @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)
  74943. */
  74944. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74945. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74946. if (blockCompilation === void 0) { blockCompilation = false; }
  74947. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  74948. _this.blurSteps = blurSteps;
  74949. _this.onApplyObservable.add(function (effect) {
  74950. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  74951. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74952. blurSteps.forEach(function (step, index) {
  74953. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  74954. });
  74955. });
  74956. if (!blockCompilation) {
  74957. _this.updateEffect();
  74958. }
  74959. return _this;
  74960. }
  74961. /**
  74962. * Updates the effect with the current post process compile time values and recompiles the shader.
  74963. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74964. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74965. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74966. * @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
  74967. * @param onCompiled Called when the shader has been compiled.
  74968. * @param onError Called if there is an error when compiling a shader.
  74969. */
  74970. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74971. if (defines === void 0) { defines = null; }
  74972. if (uniforms === void 0) { uniforms = null; }
  74973. if (samplers === void 0) { samplers = null; }
  74974. if (!defines) {
  74975. defines = "";
  74976. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  74977. }
  74978. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  74979. };
  74980. return DepthOfFieldMergePostProcess;
  74981. }(BABYLON.PostProcess));
  74982. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  74983. })(BABYLON || (BABYLON = {}));
  74984. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  74985. var BABYLON;
  74986. (function (BABYLON) {
  74987. /**
  74988. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  74989. */
  74990. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  74991. __extends(CircleOfConfusionPostProcess, _super);
  74992. /**
  74993. * Creates a new instance CircleOfConfusionPostProcess
  74994. * @param name The name of the effect.
  74995. * @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.
  74996. * @param options The required width/height ratio to downsize to before computing the render pass.
  74997. * @param camera The camera to apply the render pass to.
  74998. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74999. * @param engine The engine which the post process will be applied. (default: current engine)
  75000. * @param reusable If the post process can be reused on the same frame. (default: false)
  75001. * @param textureType Type of textures used when performing the post process. (default: 0)
  75002. * @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)
  75003. */
  75004. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75005. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75006. if (blockCompilation === void 0) { blockCompilation = false; }
  75007. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75008. /**
  75009. * 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.
  75010. */
  75011. _this.lensSize = 50;
  75012. /**
  75013. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75014. */
  75015. _this.fStop = 1.4;
  75016. /**
  75017. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75018. */
  75019. _this.focusDistance = 2000;
  75020. /**
  75021. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75022. */
  75023. _this.focalLength = 50;
  75024. _this._depthTexture = null;
  75025. _this._depthTexture = depthTexture;
  75026. _this.onApplyObservable.add(function (effect) {
  75027. if (!_this._depthTexture) {
  75028. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75029. return;
  75030. }
  75031. effect.setTexture("depthSampler", _this._depthTexture);
  75032. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75033. var aperture = _this.lensSize / _this.fStop;
  75034. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75035. effect.setFloat('focusDistance', _this.focusDistance);
  75036. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75037. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75038. });
  75039. return _this;
  75040. }
  75041. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75042. /**
  75043. * 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.
  75044. */
  75045. set: function (value) {
  75046. this._depthTexture = value;
  75047. },
  75048. enumerable: true,
  75049. configurable: true
  75050. });
  75051. return CircleOfConfusionPostProcess;
  75052. }(BABYLON.PostProcess));
  75053. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75054. })(BABYLON || (BABYLON = {}));
  75055. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75056. var BABYLON;
  75057. (function (BABYLON) {
  75058. /**
  75059. * Specifies the level of max blur that should be applied when using the depth of field effect
  75060. */
  75061. var DepthOfFieldEffectBlurLevel;
  75062. (function (DepthOfFieldEffectBlurLevel) {
  75063. /**
  75064. * Subtle blur
  75065. */
  75066. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75067. /**
  75068. * Medium blur
  75069. */
  75070. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75071. /**
  75072. * Large blur
  75073. */
  75074. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75075. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75076. ;
  75077. /**
  75078. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75079. */
  75080. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75081. __extends(DepthOfFieldEffect, _super);
  75082. /**
  75083. * Creates a new instance DepthOfFieldEffect
  75084. * @param scene The scene the effect belongs to.
  75085. * @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.
  75086. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75087. * @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)
  75088. */
  75089. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75090. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75091. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75092. if (blockCompilation === void 0) { blockCompilation = false; }
  75093. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75094. return _this._effects;
  75095. }, true) || this;
  75096. /**
  75097. * Internal post processes in depth of field effect
  75098. */
  75099. _this._effects = [];
  75100. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75101. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75102. // 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)
  75103. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75104. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75105. _this._depthOfFieldBlurY = [];
  75106. _this._depthOfFieldBlurX = [];
  75107. var blurCount = 1;
  75108. var kernelSize = 15;
  75109. switch (blurLevel) {
  75110. case DepthOfFieldEffectBlurLevel.High: {
  75111. blurCount = 3;
  75112. kernelSize = 51;
  75113. break;
  75114. }
  75115. case DepthOfFieldEffectBlurLevel.Medium: {
  75116. blurCount = 2;
  75117. kernelSize = 31;
  75118. break;
  75119. }
  75120. default: {
  75121. kernelSize = 15;
  75122. blurCount = 1;
  75123. break;
  75124. }
  75125. }
  75126. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75127. var ratio = 1.0;
  75128. for (var i = 0; i < blurCount; i++) {
  75129. 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);
  75130. blurY.autoClear = false;
  75131. ratio = 0.75 / Math.pow(2, i);
  75132. 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);
  75133. blurX.autoClear = false;
  75134. _this._depthOfFieldBlurY.push(blurY);
  75135. _this._depthOfFieldBlurX.push(blurX);
  75136. }
  75137. // Set all post processes on the effect.
  75138. _this._effects = [_this._circleOfConfusion];
  75139. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75140. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75141. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75142. }
  75143. // Merge blurred images with original image based on circleOfConfusion
  75144. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75145. _this._dofMerge.autoClear = false;
  75146. _this._effects.push(_this._dofMerge);
  75147. return _this;
  75148. }
  75149. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75150. get: function () {
  75151. return this._circleOfConfusion.focalLength;
  75152. },
  75153. /**
  75154. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75155. */
  75156. set: function (value) {
  75157. this._circleOfConfusion.focalLength = value;
  75158. },
  75159. enumerable: true,
  75160. configurable: true
  75161. });
  75162. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75163. get: function () {
  75164. return this._circleOfConfusion.fStop;
  75165. },
  75166. /**
  75167. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75168. */
  75169. set: function (value) {
  75170. this._circleOfConfusion.fStop = value;
  75171. },
  75172. enumerable: true,
  75173. configurable: true
  75174. });
  75175. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75176. get: function () {
  75177. return this._circleOfConfusion.focusDistance;
  75178. },
  75179. /**
  75180. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75181. */
  75182. set: function (value) {
  75183. this._circleOfConfusion.focusDistance = value;
  75184. },
  75185. enumerable: true,
  75186. configurable: true
  75187. });
  75188. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75189. get: function () {
  75190. return this._circleOfConfusion.lensSize;
  75191. },
  75192. /**
  75193. * 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.
  75194. */
  75195. set: function (value) {
  75196. this._circleOfConfusion.lensSize = value;
  75197. },
  75198. enumerable: true,
  75199. configurable: true
  75200. });
  75201. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75202. /**
  75203. * 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.
  75204. */
  75205. set: function (value) {
  75206. this._circleOfConfusion.depthTexture = value;
  75207. },
  75208. enumerable: true,
  75209. configurable: true
  75210. });
  75211. /**
  75212. * Disposes each of the internal effects for a given camera.
  75213. * @param camera The camera to dispose the effect on.
  75214. */
  75215. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75216. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75217. this._effects[effectIndex].dispose(camera);
  75218. }
  75219. };
  75220. /**
  75221. * Internal
  75222. */
  75223. DepthOfFieldEffect.prototype._updateEffects = function () {
  75224. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75225. this._effects[effectIndex].updateEffect();
  75226. }
  75227. };
  75228. /**
  75229. * Internal
  75230. * @returns if all the contained post processes are ready.
  75231. */
  75232. DepthOfFieldEffect.prototype._isReady = function () {
  75233. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75234. if (!this._effects[effectIndex].isReady()) {
  75235. return false;
  75236. }
  75237. }
  75238. return true;
  75239. };
  75240. return DepthOfFieldEffect;
  75241. }(BABYLON.PostProcessRenderEffect));
  75242. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75243. })(BABYLON || (BABYLON = {}));
  75244. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75245. var BABYLON;
  75246. (function (BABYLON) {
  75247. /**
  75248. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75249. */
  75250. var BloomMergePostProcess = /** @class */ (function (_super) {
  75251. __extends(BloomMergePostProcess, _super);
  75252. /**
  75253. * Creates a new instance of @see BloomMergePostProcess
  75254. * @param name The name of the effect.
  75255. * @param originalFromInput Post process which's input will be used for the merge.
  75256. * @param blurred Blurred highlights post process which's output will be used.
  75257. * @param weight Weight of the bloom to be added to the original input.
  75258. * @param options The required width/height ratio to downsize to before computing the render pass.
  75259. * @param camera The camera to apply the render pass to.
  75260. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75261. * @param engine The engine which the post process will be applied. (default: current engine)
  75262. * @param reusable If the post process can be reused on the same frame. (default: false)
  75263. * @param textureType Type of textures used when performing the post process. (default: 0)
  75264. * @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)
  75265. */
  75266. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75267. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75268. if (blockCompilation === void 0) { blockCompilation = false; }
  75269. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75270. _this.weight = weight;
  75271. _this.onApplyObservable.add(function (effect) {
  75272. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75273. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75274. effect.setFloat("bloomWeight", _this.weight);
  75275. });
  75276. if (!blockCompilation) {
  75277. _this.updateEffect();
  75278. }
  75279. return _this;
  75280. }
  75281. return BloomMergePostProcess;
  75282. }(BABYLON.PostProcess));
  75283. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75284. })(BABYLON || (BABYLON = {}));
  75285. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75286. var BABYLON;
  75287. (function (BABYLON) {
  75288. /**
  75289. * 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.
  75290. */
  75291. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75292. __extends(ExtractHighlightsPostProcess, _super);
  75293. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75294. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75295. if (blockCompilation === void 0) { blockCompilation = false; }
  75296. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75297. /**
  75298. * The luminance threshold, pixels below this value will be set to black.
  75299. */
  75300. _this.threshold = 0.9;
  75301. /**
  75302. * Internal
  75303. */
  75304. _this._exposure = 1;
  75305. /**
  75306. * Post process which has the input texture to be used when performing highlight extraction
  75307. */
  75308. _this._inputPostProcess = null;
  75309. _this.onApplyObservable.add(function (effect) {
  75310. if (_this._inputPostProcess) {
  75311. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75312. }
  75313. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75314. effect.setFloat('exposure', _this._exposure);
  75315. });
  75316. return _this;
  75317. }
  75318. return ExtractHighlightsPostProcess;
  75319. }(BABYLON.PostProcess));
  75320. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75321. })(BABYLON || (BABYLON = {}));
  75322. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75323. var BABYLON;
  75324. (function (BABYLON) {
  75325. /**
  75326. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75327. */
  75328. var BloomEffect = /** @class */ (function (_super) {
  75329. __extends(BloomEffect, _super);
  75330. /**
  75331. * Creates a new instance of @see BloomEffect
  75332. * @param scene The scene the effect belongs to.
  75333. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75334. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75335. * @param bloomWeight The the strength of bloom.
  75336. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75337. * @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)
  75338. */
  75339. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75340. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75341. if (blockCompilation === void 0) { blockCompilation = false; }
  75342. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75343. return _this._effects;
  75344. }, true) || this;
  75345. _this.bloomScale = bloomScale;
  75346. /**
  75347. * Internal
  75348. */
  75349. _this._effects = [];
  75350. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75351. _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);
  75352. _this._blurX.alwaysForcePOT = true;
  75353. _this._blurX.autoClear = false;
  75354. _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);
  75355. _this._blurY.alwaysForcePOT = true;
  75356. _this._blurY.autoClear = false;
  75357. _this.kernel = bloomKernel;
  75358. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75359. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75360. _this._merge.autoClear = false;
  75361. _this._effects.push(_this._merge);
  75362. return _this;
  75363. }
  75364. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75365. /**
  75366. * The luminance threshold to find bright areas of the image to bloom.
  75367. */
  75368. get: function () {
  75369. return this._downscale.threshold;
  75370. },
  75371. set: function (value) {
  75372. this._downscale.threshold = value;
  75373. },
  75374. enumerable: true,
  75375. configurable: true
  75376. });
  75377. Object.defineProperty(BloomEffect.prototype, "weight", {
  75378. /**
  75379. * The strength of the bloom.
  75380. */
  75381. get: function () {
  75382. return this._merge.weight;
  75383. },
  75384. set: function (value) {
  75385. this._merge.weight = value;
  75386. },
  75387. enumerable: true,
  75388. configurable: true
  75389. });
  75390. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75391. /**
  75392. * Specifies the size of the bloom blur kernel, relative to the final output size
  75393. */
  75394. get: function () {
  75395. return this._blurX.kernel / this.bloomScale;
  75396. },
  75397. set: function (value) {
  75398. this._blurX.kernel = value * this.bloomScale;
  75399. this._blurY.kernel = value * this.bloomScale;
  75400. },
  75401. enumerable: true,
  75402. configurable: true
  75403. });
  75404. /**
  75405. * Disposes each of the internal effects for a given camera.
  75406. * @param camera The camera to dispose the effect on.
  75407. */
  75408. BloomEffect.prototype.disposeEffects = function (camera) {
  75409. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75410. this._effects[effectIndex].dispose(camera);
  75411. }
  75412. };
  75413. /**
  75414. * Internal
  75415. */
  75416. BloomEffect.prototype._updateEffects = function () {
  75417. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75418. this._effects[effectIndex].updateEffect();
  75419. }
  75420. };
  75421. /**
  75422. * Internal
  75423. * @returns if all the contained post processes are ready.
  75424. */
  75425. BloomEffect.prototype._isReady = function () {
  75426. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75427. if (!this._effects[effectIndex].isReady()) {
  75428. return false;
  75429. }
  75430. }
  75431. return true;
  75432. };
  75433. return BloomEffect;
  75434. }(BABYLON.PostProcessRenderEffect));
  75435. BABYLON.BloomEffect = BloomEffect;
  75436. })(BABYLON || (BABYLON = {}));
  75437. //# sourceMappingURL=babylon.bloomEffect.js.map
  75438. var BABYLON;
  75439. (function (BABYLON) {
  75440. /**
  75441. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  75442. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  75443. */
  75444. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  75445. __extends(DefaultRenderingPipeline, _super);
  75446. /**
  75447. * @constructor
  75448. * @param {string} name - The rendering pipeline name
  75449. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75450. * @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)
  75451. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75452. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  75453. */
  75454. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  75455. if (automaticBuild === void 0) { automaticBuild = true; }
  75456. var _this = _super.call(this, scene.getEngine(), name) || this;
  75457. _this._originalCameras = [];
  75458. /**
  75459. * ID of the sharpen post process,
  75460. */
  75461. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  75462. /**
  75463. * ID of the image processing post process;
  75464. */
  75465. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  75466. /**
  75467. * ID of the Fast Approximate Anti-Aliasing post process;
  75468. */
  75469. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  75470. /**
  75471. * ID of the chromatic aberration post process,
  75472. */
  75473. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  75474. /**
  75475. * ID of the grain post process
  75476. */
  75477. _this.GrainPostProcessId = "GrainPostProcessEffect";
  75478. /**
  75479. * Animations which can be used to tweak settings over a period of time
  75480. */
  75481. _this.animations = [];
  75482. _this._imageProcessingConfigurationObserver = null;
  75483. // Values
  75484. _this._sharpenEnabled = false;
  75485. _this._bloomEnabled = false;
  75486. _this._depthOfFieldEnabled = false;
  75487. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  75488. _this._fxaaEnabled = false;
  75489. _this._imageProcessingEnabled = true;
  75490. _this._bloomScale = 0.5;
  75491. _this._chromaticAberrationEnabled = false;
  75492. _this._grainEnabled = false;
  75493. _this._buildAllowed = true;
  75494. _this._resizeObserver = null;
  75495. _this._hardwareScaleLevel = 1.0;
  75496. _this._bloomKernel = 64;
  75497. /**
  75498. * Specifies the weight of the bloom in the final rendering
  75499. */
  75500. _this._bloomWeight = 0.15;
  75501. /**
  75502. * Specifies the luma threshold for the area that will be blurred by the bloom
  75503. */
  75504. _this._bloomThreshold = 0.9;
  75505. _this._samples = 1;
  75506. _this._hasCleared = false;
  75507. _this._prevPostProcess = null;
  75508. _this._prevPrevPostProcess = null;
  75509. _this._cameras = cameras || [];
  75510. _this._originalCameras = _this._cameras.slice();
  75511. _this._buildAllowed = automaticBuild;
  75512. // Initialize
  75513. _this._scene = scene;
  75514. var caps = _this._scene.getEngine().getCaps();
  75515. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  75516. // Misc
  75517. if (_this._hdr) {
  75518. if (caps.textureHalfFloatRender) {
  75519. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75520. }
  75521. else if (caps.textureFloatRender) {
  75522. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75523. }
  75524. }
  75525. else {
  75526. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75527. }
  75528. // Attach
  75529. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75530. var engine = _this._scene.getEngine();
  75531. // Create post processes before hand so they can be modified before enabled.
  75532. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  75533. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75534. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  75535. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  75536. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  75537. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75538. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  75539. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75540. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  75541. _this._resizeObserver = engine.onResizeObservable.add(function () {
  75542. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  75543. _this.bloomKernel = _this.bloomKernel;
  75544. });
  75545. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  75546. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  75547. });
  75548. _this._buildPipeline();
  75549. return _this;
  75550. }
  75551. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  75552. get: function () {
  75553. return this._sharpenEnabled;
  75554. },
  75555. /**
  75556. * Enable or disable the sharpen process from the pipeline
  75557. */
  75558. set: function (enabled) {
  75559. if (this._sharpenEnabled === enabled) {
  75560. return;
  75561. }
  75562. this._sharpenEnabled = enabled;
  75563. this._buildPipeline();
  75564. },
  75565. enumerable: true,
  75566. configurable: true
  75567. });
  75568. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  75569. /**
  75570. * Specifies the size of the bloom blur kernel, relative to the final output size
  75571. */
  75572. get: function () {
  75573. return this._bloomKernel;
  75574. },
  75575. set: function (value) {
  75576. this._bloomKernel = value;
  75577. this.bloom.kernel = value / this._hardwareScaleLevel;
  75578. },
  75579. enumerable: true,
  75580. configurable: true
  75581. });
  75582. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  75583. get: function () {
  75584. return this._bloomWeight;
  75585. },
  75586. /**
  75587. * The strength of the bloom.
  75588. */
  75589. set: function (value) {
  75590. if (this._bloomWeight === value) {
  75591. return;
  75592. }
  75593. this.bloom.weight = value;
  75594. this._bloomWeight = value;
  75595. },
  75596. enumerable: true,
  75597. configurable: true
  75598. });
  75599. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  75600. get: function () {
  75601. return this._bloomThreshold;
  75602. },
  75603. /**
  75604. * The strength of the bloom.
  75605. */
  75606. set: function (value) {
  75607. if (this._bloomThreshold === value) {
  75608. return;
  75609. }
  75610. this.bloom.threshold = value;
  75611. this._bloomThreshold = value;
  75612. },
  75613. enumerable: true,
  75614. configurable: true
  75615. });
  75616. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  75617. get: function () {
  75618. return this._bloomScale;
  75619. },
  75620. /**
  75621. * The scale of the bloom, lower value will provide better performance.
  75622. */
  75623. set: function (value) {
  75624. if (this._bloomScale === value) {
  75625. return;
  75626. }
  75627. this._bloomScale = value;
  75628. // recreate bloom and dispose old as this setting is not dynamic
  75629. this._rebuildBloom();
  75630. this._buildPipeline();
  75631. },
  75632. enumerable: true,
  75633. configurable: true
  75634. });
  75635. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  75636. get: function () {
  75637. return this._bloomEnabled;
  75638. },
  75639. /**
  75640. * Enable or disable the bloom from the pipeline
  75641. */
  75642. set: function (enabled) {
  75643. if (this._bloomEnabled === enabled) {
  75644. return;
  75645. }
  75646. this._bloomEnabled = enabled;
  75647. this._buildPipeline();
  75648. },
  75649. enumerable: true,
  75650. configurable: true
  75651. });
  75652. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  75653. // recreate bloom and dispose old as this setting is not dynamic
  75654. var oldBloom = this.bloom;
  75655. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  75656. this.bloom.threshold = oldBloom.threshold;
  75657. for (var i = 0; i < this._cameras.length; i++) {
  75658. oldBloom.disposeEffects(this._cameras[i]);
  75659. }
  75660. };
  75661. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  75662. /**
  75663. * If the depth of field is enabled.
  75664. */
  75665. get: function () {
  75666. return this._depthOfFieldEnabled;
  75667. },
  75668. set: function (enabled) {
  75669. if (this._depthOfFieldEnabled === enabled) {
  75670. return;
  75671. }
  75672. this._depthOfFieldEnabled = enabled;
  75673. this._buildPipeline();
  75674. },
  75675. enumerable: true,
  75676. configurable: true
  75677. });
  75678. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  75679. /**
  75680. * Blur level of the depth of field effect. (Higher blur will effect performance)
  75681. */
  75682. get: function () {
  75683. return this._depthOfFieldBlurLevel;
  75684. },
  75685. set: function (value) {
  75686. if (this._depthOfFieldBlurLevel === value) {
  75687. return;
  75688. }
  75689. this._depthOfFieldBlurLevel = value;
  75690. // recreate dof and dispose old as this setting is not dynamic
  75691. var oldDof = this.depthOfField;
  75692. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  75693. this.depthOfField.focalLength = oldDof.focalLength;
  75694. this.depthOfField.focusDistance = oldDof.focusDistance;
  75695. this.depthOfField.fStop = oldDof.fStop;
  75696. this.depthOfField.lensSize = oldDof.lensSize;
  75697. for (var i = 0; i < this._cameras.length; i++) {
  75698. oldDof.disposeEffects(this._cameras[i]);
  75699. }
  75700. this._buildPipeline();
  75701. },
  75702. enumerable: true,
  75703. configurable: true
  75704. });
  75705. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  75706. get: function () {
  75707. return this._fxaaEnabled;
  75708. },
  75709. /**
  75710. * If the anti aliasing is enabled.
  75711. */
  75712. set: function (enabled) {
  75713. if (this._fxaaEnabled === enabled) {
  75714. return;
  75715. }
  75716. this._fxaaEnabled = enabled;
  75717. this._buildPipeline();
  75718. },
  75719. enumerable: true,
  75720. configurable: true
  75721. });
  75722. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  75723. get: function () {
  75724. return this._samples;
  75725. },
  75726. /**
  75727. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  75728. */
  75729. set: function (sampleCount) {
  75730. if (this._samples === sampleCount) {
  75731. return;
  75732. }
  75733. this._samples = sampleCount;
  75734. this._buildPipeline();
  75735. },
  75736. enumerable: true,
  75737. configurable: true
  75738. });
  75739. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  75740. get: function () {
  75741. return this._imageProcessingEnabled;
  75742. },
  75743. /**
  75744. * If image processing is enabled.
  75745. */
  75746. set: function (enabled) {
  75747. if (this._imageProcessingEnabled === enabled) {
  75748. return;
  75749. }
  75750. this._imageProcessingEnabled = enabled;
  75751. this._buildPipeline();
  75752. },
  75753. enumerable: true,
  75754. configurable: true
  75755. });
  75756. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  75757. get: function () {
  75758. return this._chromaticAberrationEnabled;
  75759. },
  75760. /**
  75761. * Enable or disable the chromaticAberration process from the pipeline
  75762. */
  75763. set: function (enabled) {
  75764. if (this._chromaticAberrationEnabled === enabled) {
  75765. return;
  75766. }
  75767. this._chromaticAberrationEnabled = enabled;
  75768. this._buildPipeline();
  75769. },
  75770. enumerable: true,
  75771. configurable: true
  75772. });
  75773. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  75774. get: function () {
  75775. return this._grainEnabled;
  75776. },
  75777. /**
  75778. * Enable or disable the grain process from the pipeline
  75779. */
  75780. set: function (enabled) {
  75781. if (this._grainEnabled === enabled) {
  75782. return;
  75783. }
  75784. this._grainEnabled = enabled;
  75785. this._buildPipeline();
  75786. },
  75787. enumerable: true,
  75788. configurable: true
  75789. });
  75790. /**
  75791. * Force the compilation of the entire pipeline.
  75792. */
  75793. DefaultRenderingPipeline.prototype.prepare = function () {
  75794. var previousState = this._buildAllowed;
  75795. this._buildAllowed = true;
  75796. this._buildPipeline();
  75797. this._buildAllowed = previousState;
  75798. };
  75799. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  75800. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  75801. if (this._hasCleared) {
  75802. postProcess.autoClear = false;
  75803. }
  75804. else {
  75805. postProcess.autoClear = true;
  75806. this._scene.autoClear = false;
  75807. this._hasCleared = true;
  75808. }
  75809. if (!skipTextureSharing) {
  75810. if (this._prevPrevPostProcess) {
  75811. postProcess.shareOutputWith(this._prevPrevPostProcess);
  75812. }
  75813. else {
  75814. postProcess.useOwnOutput();
  75815. }
  75816. if (this._prevPostProcess) {
  75817. this._prevPrevPostProcess = this._prevPostProcess;
  75818. }
  75819. this._prevPostProcess = postProcess;
  75820. }
  75821. };
  75822. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  75823. var _this = this;
  75824. if (!this._buildAllowed) {
  75825. return;
  75826. }
  75827. this._scene.autoClear = true;
  75828. var engine = this._scene.getEngine();
  75829. this._disposePostProcesses();
  75830. if (this._cameras !== null) {
  75831. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75832. // get back cameras to be used to reattach pipeline
  75833. this._cameras = this._originalCameras.slice();
  75834. }
  75835. this._reset();
  75836. this._prevPostProcess = null;
  75837. this._prevPrevPostProcess = null;
  75838. this._hasCleared = false;
  75839. if (this.depthOfFieldEnabled) {
  75840. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  75841. this.depthOfField.depthTexture = depthTexture;
  75842. if (!this.depthOfField._isReady()) {
  75843. this.depthOfField._updateEffects();
  75844. }
  75845. this.addEffect(this.depthOfField);
  75846. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  75847. }
  75848. if (this.bloomEnabled) {
  75849. if (!this.bloom._isReady()) {
  75850. this.bloom._updateEffects();
  75851. }
  75852. this.addEffect(this.bloom);
  75853. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  75854. }
  75855. if (this._imageProcessingEnabled) {
  75856. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75857. if (this._hdr) {
  75858. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  75859. this._setAutoClearAndTextureSharing(this.imageProcessing);
  75860. }
  75861. else {
  75862. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  75863. }
  75864. }
  75865. if (this.sharpenEnabled) {
  75866. if (!this.sharpen.isReady()) {
  75867. this.sharpen.updateEffect();
  75868. }
  75869. this.addEffect(this._sharpenEffect);
  75870. this._setAutoClearAndTextureSharing(this.sharpen);
  75871. }
  75872. if (this.grainEnabled) {
  75873. if (!this.grain.isReady()) {
  75874. this.grain.updateEffect();
  75875. }
  75876. this.addEffect(this._grainEffect);
  75877. this._setAutoClearAndTextureSharing(this.grain);
  75878. }
  75879. if (this.chromaticAberrationEnabled) {
  75880. if (!this.chromaticAberration.isReady()) {
  75881. this.chromaticAberration.updateEffect();
  75882. }
  75883. this.addEffect(this._chromaticAberrationEffect);
  75884. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  75885. }
  75886. if (this.fxaaEnabled) {
  75887. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75888. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  75889. this._setAutoClearAndTextureSharing(this.fxaa, true);
  75890. }
  75891. if (this._cameras !== null) {
  75892. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  75893. }
  75894. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  75895. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  75896. }
  75897. };
  75898. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  75899. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  75900. for (var i = 0; i < this._cameras.length; i++) {
  75901. var camera = this._cameras[i];
  75902. if (this.imageProcessing) {
  75903. this.imageProcessing.dispose(camera);
  75904. }
  75905. if (this.fxaa) {
  75906. this.fxaa.dispose(camera);
  75907. }
  75908. // These are created in the constructor and should not be disposed on every pipeline change
  75909. if (disposeNonRecreated) {
  75910. if (this.sharpen) {
  75911. this.sharpen.dispose(camera);
  75912. }
  75913. if (this.depthOfField) {
  75914. this.depthOfField.disposeEffects(camera);
  75915. }
  75916. if (this.bloom) {
  75917. this.bloom.disposeEffects(camera);
  75918. }
  75919. if (this.chromaticAberration) {
  75920. this.chromaticAberration.dispose(camera);
  75921. }
  75922. if (this.grain) {
  75923. this.grain.dispose(camera);
  75924. }
  75925. }
  75926. }
  75927. this.imageProcessing = null;
  75928. this.fxaa = null;
  75929. if (disposeNonRecreated) {
  75930. this.sharpen = null;
  75931. this._sharpenEffect = null;
  75932. this.depthOfField = null;
  75933. this.bloom = null;
  75934. this.chromaticAberration = null;
  75935. this._chromaticAberrationEffect = null;
  75936. this.grain = null;
  75937. this._grainEffect = null;
  75938. }
  75939. };
  75940. /**
  75941. * Dispose of the pipeline and stop all post processes
  75942. */
  75943. DefaultRenderingPipeline.prototype.dispose = function () {
  75944. this._disposePostProcesses(true);
  75945. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75946. this._scene.autoClear = true;
  75947. if (this._resizeObserver) {
  75948. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  75949. this._resizeObserver = null;
  75950. }
  75951. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  75952. _super.prototype.dispose.call(this);
  75953. };
  75954. /**
  75955. * Serialize the rendering pipeline (Used when exporting)
  75956. * @returns the serialized object
  75957. */
  75958. DefaultRenderingPipeline.prototype.serialize = function () {
  75959. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75960. serializationObject.customType = "DefaultRenderingPipeline";
  75961. return serializationObject;
  75962. };
  75963. /**
  75964. * Parse the serialized pipeline
  75965. * @param source Source pipeline.
  75966. * @param scene The scene to load the pipeline to.
  75967. * @param rootUrl The URL of the serialized pipeline.
  75968. * @returns An instantiated pipeline from the serialized object.
  75969. */
  75970. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75971. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  75972. };
  75973. __decorate([
  75974. BABYLON.serialize()
  75975. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  75976. __decorate([
  75977. BABYLON.serialize()
  75978. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  75979. __decorate([
  75980. BABYLON.serialize()
  75981. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  75982. __decorate([
  75983. BABYLON.serialize()
  75984. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  75985. __decorate([
  75986. BABYLON.serialize()
  75987. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  75988. __decorate([
  75989. BABYLON.serialize()
  75990. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  75991. __decorate([
  75992. BABYLON.serialize()
  75993. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  75994. __decorate([
  75995. BABYLON.serialize()
  75996. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  75997. __decorate([
  75998. BABYLON.serialize()
  75999. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76000. __decorate([
  76001. BABYLON.serialize()
  76002. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76003. __decorate([
  76004. BABYLON.serialize()
  76005. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76006. __decorate([
  76007. BABYLON.serialize()
  76008. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76009. __decorate([
  76010. BABYLON.serialize()
  76011. ], DefaultRenderingPipeline.prototype, "samples", null);
  76012. __decorate([
  76013. BABYLON.serialize()
  76014. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76015. __decorate([
  76016. BABYLON.serialize()
  76017. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76018. __decorate([
  76019. BABYLON.serialize()
  76020. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76021. return DefaultRenderingPipeline;
  76022. }(BABYLON.PostProcessRenderPipeline));
  76023. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76024. })(BABYLON || (BABYLON = {}));
  76025. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76026. var BABYLON;
  76027. (function (BABYLON) {
  76028. /**
  76029. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76030. */
  76031. var GeometryBufferRenderer = /** @class */ (function () {
  76032. /**
  76033. * Creates a new G Buffer for the scene
  76034. * @param scene The scene the buffer belongs to
  76035. * @param ratio How big is the buffer related to the main canvas.
  76036. */
  76037. function GeometryBufferRenderer(scene, ratio) {
  76038. if (ratio === void 0) { ratio = 1; }
  76039. this._enablePosition = false;
  76040. this._scene = scene;
  76041. this._ratio = ratio;
  76042. // Render target
  76043. this._createRenderTargets();
  76044. }
  76045. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76046. /**
  76047. * Set the render list (meshes to be rendered) used in the G buffer.
  76048. */
  76049. set: function (meshes) {
  76050. this._multiRenderTarget.renderList = meshes;
  76051. },
  76052. enumerable: true,
  76053. configurable: true
  76054. });
  76055. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76056. /**
  76057. * Gets wether or not G buffer are supported by the running hardware.
  76058. * This requires draw buffer supports
  76059. */
  76060. get: function () {
  76061. return this._multiRenderTarget.isSupported;
  76062. },
  76063. enumerable: true,
  76064. configurable: true
  76065. });
  76066. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76067. /**
  76068. * Gets wether or not position are enabled for the G buffer.
  76069. */
  76070. get: function () {
  76071. return this._enablePosition;
  76072. },
  76073. /**
  76074. * Sets wether or not position are enabled for the G buffer.
  76075. */
  76076. set: function (enable) {
  76077. this._enablePosition = enable;
  76078. this.dispose();
  76079. this._createRenderTargets();
  76080. },
  76081. enumerable: true,
  76082. configurable: true
  76083. });
  76084. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76085. /**
  76086. * Gets the scene associated with the buffer.
  76087. */
  76088. get: function () {
  76089. return this._scene;
  76090. },
  76091. enumerable: true,
  76092. configurable: true
  76093. });
  76094. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76095. /**
  76096. * Gets the ratio used by the buffer during its creation.
  76097. * How big is the buffer related to the main canvas.
  76098. */
  76099. get: function () {
  76100. return this._ratio;
  76101. },
  76102. enumerable: true,
  76103. configurable: true
  76104. });
  76105. /**
  76106. * Checks wether everything is ready to render a submesh to the G buffer.
  76107. * @param subMesh the submesh to check readiness for
  76108. * @param useInstances is the mesh drawn using instance or not
  76109. * @returns true if ready otherwise false
  76110. */
  76111. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76112. var material = subMesh.getMaterial();
  76113. if (material && material.disableDepthWrite) {
  76114. return false;
  76115. }
  76116. var defines = [];
  76117. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76118. var mesh = subMesh.getMesh();
  76119. // Alpha test
  76120. if (material && material.needAlphaTesting()) {
  76121. defines.push("#define ALPHATEST");
  76122. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76123. attribs.push(BABYLON.VertexBuffer.UVKind);
  76124. defines.push("#define UV1");
  76125. }
  76126. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76127. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76128. defines.push("#define UV2");
  76129. }
  76130. }
  76131. // Buffers
  76132. if (this._enablePosition) {
  76133. defines.push("#define POSITION");
  76134. }
  76135. // Bones
  76136. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76137. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76138. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76139. if (mesh.numBoneInfluencers > 4) {
  76140. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76141. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76142. }
  76143. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76144. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76145. }
  76146. else {
  76147. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76148. }
  76149. // Instances
  76150. if (useInstances) {
  76151. defines.push("#define INSTANCES");
  76152. attribs.push("world0");
  76153. attribs.push("world1");
  76154. attribs.push("world2");
  76155. attribs.push("world3");
  76156. }
  76157. // Get correct effect
  76158. var join = defines.join("\n");
  76159. if (this._cachedDefines !== join) {
  76160. this._cachedDefines = join;
  76161. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76162. }
  76163. return this._effect.isReady();
  76164. };
  76165. /**
  76166. * Gets the current underlying G Buffer.
  76167. * @returns the buffer
  76168. */
  76169. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76170. return this._multiRenderTarget;
  76171. };
  76172. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76173. /**
  76174. * Gets the number of samples used to render the buffer (anti aliasing).
  76175. */
  76176. get: function () {
  76177. return this._multiRenderTarget.samples;
  76178. },
  76179. /**
  76180. * Sets the number of samples used to render the buffer (anti aliasing).
  76181. */
  76182. set: function (value) {
  76183. this._multiRenderTarget.samples = value;
  76184. },
  76185. enumerable: true,
  76186. configurable: true
  76187. });
  76188. /**
  76189. * Disposes the renderer and frees up associated resources.
  76190. */
  76191. GeometryBufferRenderer.prototype.dispose = function () {
  76192. this.getGBuffer().dispose();
  76193. };
  76194. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76195. var _this = this;
  76196. var engine = this._scene.getEngine();
  76197. var count = this._enablePosition ? 3 : 2;
  76198. 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 });
  76199. if (!this.isSupported) {
  76200. return;
  76201. }
  76202. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76203. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76204. this._multiRenderTarget.refreshRate = 1;
  76205. this._multiRenderTarget.renderParticles = false;
  76206. this._multiRenderTarget.renderList = null;
  76207. // set default depth value to 1.0 (far away)
  76208. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76209. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76210. });
  76211. // Custom render function
  76212. var renderSubMesh = function (subMesh) {
  76213. var mesh = subMesh.getRenderingMesh();
  76214. var scene = _this._scene;
  76215. var engine = scene.getEngine();
  76216. var material = subMesh.getMaterial();
  76217. if (!material) {
  76218. return;
  76219. }
  76220. // Culling
  76221. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76222. // Managing instances
  76223. var batch = mesh._getInstancesRenderList(subMesh._id);
  76224. if (batch.mustReturn) {
  76225. return;
  76226. }
  76227. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76228. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76229. engine.enableEffect(_this._effect);
  76230. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76231. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76232. _this._effect.setMatrix("view", scene.getViewMatrix());
  76233. // Alpha test
  76234. if (material && material.needAlphaTesting()) {
  76235. var alphaTexture = material.getAlphaTestTexture();
  76236. if (alphaTexture) {
  76237. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76238. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76239. }
  76240. }
  76241. // Bones
  76242. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76243. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76244. }
  76245. // Draw
  76246. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76247. }
  76248. };
  76249. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76250. var index;
  76251. if (depthOnlySubMeshes.length) {
  76252. engine.setColorWrite(false);
  76253. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76254. renderSubMesh(depthOnlySubMeshes.data[index]);
  76255. }
  76256. engine.setColorWrite(true);
  76257. }
  76258. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76259. renderSubMesh(opaqueSubMeshes.data[index]);
  76260. }
  76261. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76262. renderSubMesh(alphaTestSubMeshes.data[index]);
  76263. }
  76264. };
  76265. };
  76266. return GeometryBufferRenderer;
  76267. }());
  76268. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76269. })(BABYLON || (BABYLON = {}));
  76270. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76271. var BABYLON;
  76272. (function (BABYLON) {
  76273. var RefractionPostProcess = /** @class */ (function (_super) {
  76274. __extends(RefractionPostProcess, _super);
  76275. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  76276. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  76277. _this.color = color;
  76278. _this.depth = depth;
  76279. _this.colorLevel = colorLevel;
  76280. _this._ownRefractionTexture = true;
  76281. _this.onActivateObservable.add(function (cam) {
  76282. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  76283. });
  76284. _this.onApplyObservable.add(function (effect) {
  76285. effect.setColor3("baseColor", _this.color);
  76286. effect.setFloat("depth", _this.depth);
  76287. effect.setFloat("colorLevel", _this.colorLevel);
  76288. effect.setTexture("refractionSampler", _this._refTexture);
  76289. });
  76290. return _this;
  76291. }
  76292. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  76293. /**
  76294. * Gets or sets the refraction texture
  76295. * Please note that you are responsible for disposing the texture if you set it manually
  76296. */
  76297. get: function () {
  76298. return this._refTexture;
  76299. },
  76300. set: function (value) {
  76301. if (this._refTexture && this._ownRefractionTexture) {
  76302. this._refTexture.dispose();
  76303. }
  76304. this._refTexture = value;
  76305. this._ownRefractionTexture = false;
  76306. },
  76307. enumerable: true,
  76308. configurable: true
  76309. });
  76310. // Methods
  76311. RefractionPostProcess.prototype.dispose = function (camera) {
  76312. if (this._refTexture && this._ownRefractionTexture) {
  76313. this._refTexture.dispose();
  76314. this._refTexture = null;
  76315. }
  76316. _super.prototype.dispose.call(this, camera);
  76317. };
  76318. return RefractionPostProcess;
  76319. }(BABYLON.PostProcess));
  76320. BABYLON.RefractionPostProcess = RefractionPostProcess;
  76321. })(BABYLON || (BABYLON = {}));
  76322. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  76323. var BABYLON;
  76324. (function (BABYLON) {
  76325. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  76326. __extends(BlackAndWhitePostProcess, _super);
  76327. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  76328. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  76329. _this.degree = 1;
  76330. _this.onApplyObservable.add(function (effect) {
  76331. effect.setFloat("degree", _this.degree);
  76332. });
  76333. return _this;
  76334. }
  76335. return BlackAndWhitePostProcess;
  76336. }(BABYLON.PostProcess));
  76337. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  76338. })(BABYLON || (BABYLON = {}));
  76339. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  76340. var BABYLON;
  76341. (function (BABYLON) {
  76342. /**
  76343. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  76344. * input texture to perform effects such as edge detection or sharpening
  76345. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  76346. */
  76347. var ConvolutionPostProcess = /** @class */ (function (_super) {
  76348. __extends(ConvolutionPostProcess, _super);
  76349. /**
  76350. * Creates a new instance ConvolutionPostProcess
  76351. * @param name The name of the effect.
  76352. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  76353. * @param options The required width/height ratio to downsize to before computing the render pass.
  76354. * @param camera The camera to apply the render pass to.
  76355. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76356. * @param engine The engine which the post process will be applied. (default: current engine)
  76357. * @param reusable If the post process can be reused on the same frame. (default: false)
  76358. * @param textureType Type of textures used when performing the post process. (default: 0)
  76359. */
  76360. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  76361. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76362. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76363. _this.kernel = kernel;
  76364. _this.onApply = function (effect) {
  76365. effect.setFloat2("screenSize", _this.width, _this.height);
  76366. effect.setArray("kernel", _this.kernel);
  76367. };
  76368. return _this;
  76369. }
  76370. // Statics
  76371. /**
  76372. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76373. */
  76374. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  76375. /**
  76376. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76377. */
  76378. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  76379. /**
  76380. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76381. */
  76382. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  76383. /**
  76384. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76385. */
  76386. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  76387. /**
  76388. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76389. */
  76390. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  76391. /**
  76392. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76393. */
  76394. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  76395. return ConvolutionPostProcess;
  76396. }(BABYLON.PostProcess));
  76397. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  76398. })(BABYLON || (BABYLON = {}));
  76399. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  76400. var BABYLON;
  76401. (function (BABYLON) {
  76402. var FilterPostProcess = /** @class */ (function (_super) {
  76403. __extends(FilterPostProcess, _super);
  76404. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  76405. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  76406. _this.kernelMatrix = kernelMatrix;
  76407. _this.onApply = function (effect) {
  76408. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  76409. };
  76410. return _this;
  76411. }
  76412. return FilterPostProcess;
  76413. }(BABYLON.PostProcess));
  76414. BABYLON.FilterPostProcess = FilterPostProcess;
  76415. })(BABYLON || (BABYLON = {}));
  76416. //# sourceMappingURL=babylon.filterPostProcess.js.map
  76417. var BABYLON;
  76418. (function (BABYLON) {
  76419. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  76420. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  76421. __extends(VolumetricLightScatteringPostProcess, _super);
  76422. /**
  76423. * @constructor
  76424. * @param {string} name - The post-process name
  76425. * @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)
  76426. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  76427. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  76428. * @param {number} samples - The post-process quality, default 100
  76429. * @param {number} samplingMode - The post-process filtering mode
  76430. * @param {BABYLON.Engine} engine - The babylon engine
  76431. * @param {boolean} reusable - If the post-process is reusable
  76432. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  76433. */
  76434. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  76435. if (samples === void 0) { samples = 100; }
  76436. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76437. 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;
  76438. _this._screenCoordinates = BABYLON.Vector2.Zero();
  76439. /**
  76440. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  76441. */
  76442. _this.customMeshPosition = BABYLON.Vector3.Zero();
  76443. /**
  76444. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  76445. */
  76446. _this.useCustomMeshPosition = false;
  76447. /**
  76448. * If the post-process should inverse the light scattering direction
  76449. */
  76450. _this.invert = true;
  76451. /**
  76452. * Array containing the excluded meshes not rendered in the internal pass
  76453. */
  76454. _this.excludedMeshes = new Array();
  76455. /**
  76456. * Controls the overall intensity of the post-process
  76457. */
  76458. _this.exposure = 0.3;
  76459. /**
  76460. * Dissipates each sample's contribution in range [0, 1]
  76461. */
  76462. _this.decay = 0.96815;
  76463. /**
  76464. * Controls the overall intensity of each sample
  76465. */
  76466. _this.weight = 0.58767;
  76467. /**
  76468. * Controls the density of each sample
  76469. */
  76470. _this.density = 0.926;
  76471. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  76472. engine = scene.getEngine();
  76473. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  76474. // Configure mesh
  76475. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  76476. // Configure
  76477. _this._createPass(scene, ratio.passRatio || ratio);
  76478. _this.onActivate = function (camera) {
  76479. if (!_this.isSupported) {
  76480. _this.dispose(camera);
  76481. }
  76482. _this.onActivate = null;
  76483. };
  76484. _this.onApplyObservable.add(function (effect) {
  76485. _this._updateMeshScreenCoordinates(scene);
  76486. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  76487. effect.setFloat("exposure", _this.exposure);
  76488. effect.setFloat("decay", _this.decay);
  76489. effect.setFloat("weight", _this.weight);
  76490. effect.setFloat("density", _this.density);
  76491. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  76492. });
  76493. return _this;
  76494. }
  76495. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  76496. get: function () {
  76497. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76498. return false;
  76499. },
  76500. set: function (useDiffuseColor) {
  76501. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76502. },
  76503. enumerable: true,
  76504. configurable: true
  76505. });
  76506. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  76507. return "VolumetricLightScatteringPostProcess";
  76508. };
  76509. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  76510. var mesh = subMesh.getMesh();
  76511. // Render this.mesh as default
  76512. if (mesh === this.mesh && mesh.material) {
  76513. return mesh.material.isReady(mesh);
  76514. }
  76515. var defines = [];
  76516. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76517. var material = subMesh.getMaterial();
  76518. // Alpha test
  76519. if (material) {
  76520. if (material.needAlphaTesting()) {
  76521. defines.push("#define ALPHATEST");
  76522. }
  76523. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76524. attribs.push(BABYLON.VertexBuffer.UVKind);
  76525. defines.push("#define UV1");
  76526. }
  76527. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76528. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76529. defines.push("#define UV2");
  76530. }
  76531. }
  76532. // Bones
  76533. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76534. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76535. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76536. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76537. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  76538. }
  76539. else {
  76540. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76541. }
  76542. // Instances
  76543. if (useInstances) {
  76544. defines.push("#define INSTANCES");
  76545. attribs.push("world0");
  76546. attribs.push("world1");
  76547. attribs.push("world2");
  76548. attribs.push("world3");
  76549. }
  76550. // Get correct effect
  76551. var join = defines.join("\n");
  76552. if (this._cachedDefines !== join) {
  76553. this._cachedDefines = join;
  76554. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  76555. }
  76556. return this._volumetricLightScatteringPass.isReady();
  76557. };
  76558. /**
  76559. * Sets the new light position for light scattering effect
  76560. * @param {BABYLON.Vector3} The new custom light position
  76561. */
  76562. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  76563. this.customMeshPosition = position;
  76564. };
  76565. /**
  76566. * Returns the light position for light scattering effect
  76567. * @return {BABYLON.Vector3} The custom light position
  76568. */
  76569. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  76570. return this.customMeshPosition;
  76571. };
  76572. /**
  76573. * Disposes the internal assets and detaches the post-process from the camera
  76574. */
  76575. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  76576. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  76577. if (rttIndex !== -1) {
  76578. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  76579. }
  76580. this._volumetricLightScatteringRTT.dispose();
  76581. _super.prototype.dispose.call(this, camera);
  76582. };
  76583. /**
  76584. * Returns the render target texture used by the post-process
  76585. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  76586. */
  76587. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  76588. return this._volumetricLightScatteringRTT;
  76589. };
  76590. // Private methods
  76591. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  76592. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  76593. return true;
  76594. }
  76595. return false;
  76596. };
  76597. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  76598. var _this = this;
  76599. var engine = scene.getEngine();
  76600. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76601. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76602. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76603. this._volumetricLightScatteringRTT.renderList = null;
  76604. this._volumetricLightScatteringRTT.renderParticles = false;
  76605. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  76606. var camera = this.getCamera();
  76607. if (camera) {
  76608. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76609. }
  76610. else {
  76611. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76612. }
  76613. // Custom render function for submeshes
  76614. var renderSubMesh = function (subMesh) {
  76615. var mesh = subMesh.getRenderingMesh();
  76616. if (_this._meshExcluded(mesh)) {
  76617. return;
  76618. }
  76619. var material = subMesh.getMaterial();
  76620. if (!material) {
  76621. return;
  76622. }
  76623. var scene = mesh.getScene();
  76624. var engine = scene.getEngine();
  76625. // Culling
  76626. engine.setState(material.backFaceCulling);
  76627. // Managing instances
  76628. var batch = mesh._getInstancesRenderList(subMesh._id);
  76629. if (batch.mustReturn) {
  76630. return;
  76631. }
  76632. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76633. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  76634. var effect = _this._volumetricLightScatteringPass;
  76635. if (mesh === _this.mesh) {
  76636. if (subMesh.effect) {
  76637. effect = subMesh.effect;
  76638. }
  76639. else {
  76640. effect = material.getEffect();
  76641. }
  76642. }
  76643. engine.enableEffect(effect);
  76644. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  76645. if (mesh === _this.mesh) {
  76646. material.bind(mesh.getWorldMatrix(), mesh);
  76647. }
  76648. else {
  76649. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  76650. // Alpha test
  76651. if (material && material.needAlphaTesting()) {
  76652. var alphaTexture = material.getAlphaTestTexture();
  76653. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  76654. if (alphaTexture) {
  76655. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76656. }
  76657. }
  76658. // Bones
  76659. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76660. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76661. }
  76662. }
  76663. // Draw
  76664. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  76665. }
  76666. };
  76667. // Render target texture callbacks
  76668. var savedSceneClearColor;
  76669. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  76670. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  76671. savedSceneClearColor = scene.clearColor;
  76672. scene.clearColor = sceneClearColor;
  76673. });
  76674. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  76675. scene.clearColor = savedSceneClearColor;
  76676. });
  76677. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76678. var engine = scene.getEngine();
  76679. var index;
  76680. if (depthOnlySubMeshes.length) {
  76681. engine.setColorWrite(false);
  76682. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76683. renderSubMesh(depthOnlySubMeshes.data[index]);
  76684. }
  76685. engine.setColorWrite(true);
  76686. }
  76687. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76688. renderSubMesh(opaqueSubMeshes.data[index]);
  76689. }
  76690. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76691. renderSubMesh(alphaTestSubMeshes.data[index]);
  76692. }
  76693. if (transparentSubMeshes.length) {
  76694. // Sort sub meshes
  76695. for (index = 0; index < transparentSubMeshes.length; index++) {
  76696. var submesh = transparentSubMeshes.data[index];
  76697. var boundingInfo = submesh.getBoundingInfo();
  76698. if (boundingInfo && scene.activeCamera) {
  76699. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  76700. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  76701. }
  76702. }
  76703. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  76704. sortedArray.sort(function (a, b) {
  76705. // Alpha index first
  76706. if (a._alphaIndex > b._alphaIndex) {
  76707. return 1;
  76708. }
  76709. if (a._alphaIndex < b._alphaIndex) {
  76710. return -1;
  76711. }
  76712. // Then distance to camera
  76713. if (a._distanceToCamera < b._distanceToCamera) {
  76714. return 1;
  76715. }
  76716. if (a._distanceToCamera > b._distanceToCamera) {
  76717. return -1;
  76718. }
  76719. return 0;
  76720. });
  76721. // Render sub meshes
  76722. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  76723. for (index = 0; index < sortedArray.length; index++) {
  76724. renderSubMesh(sortedArray[index]);
  76725. }
  76726. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76727. }
  76728. };
  76729. };
  76730. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  76731. var transform = scene.getTransformMatrix();
  76732. var meshPosition;
  76733. if (this.useCustomMeshPosition) {
  76734. meshPosition = this.customMeshPosition;
  76735. }
  76736. else if (this.attachedNode) {
  76737. meshPosition = this.attachedNode.position;
  76738. }
  76739. else {
  76740. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  76741. }
  76742. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  76743. this._screenCoordinates.x = pos.x / this._viewPort.width;
  76744. this._screenCoordinates.y = pos.y / this._viewPort.height;
  76745. if (this.invert)
  76746. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  76747. };
  76748. // Static methods
  76749. /**
  76750. * Creates a default mesh for the Volumeric Light Scattering post-process
  76751. * @param {string} The mesh name
  76752. * @param {BABYLON.Scene} The scene where to create the mesh
  76753. * @return {BABYLON.Mesh} the default mesh
  76754. */
  76755. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  76756. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  76757. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  76758. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  76759. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  76760. mesh.material = material;
  76761. return mesh;
  76762. };
  76763. __decorate([
  76764. BABYLON.serializeAsVector3()
  76765. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  76766. __decorate([
  76767. BABYLON.serialize()
  76768. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  76769. __decorate([
  76770. BABYLON.serialize()
  76771. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  76772. __decorate([
  76773. BABYLON.serializeAsMeshReference()
  76774. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  76775. __decorate([
  76776. BABYLON.serialize()
  76777. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  76778. __decorate([
  76779. BABYLON.serialize()
  76780. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  76781. __decorate([
  76782. BABYLON.serialize()
  76783. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  76784. __decorate([
  76785. BABYLON.serialize()
  76786. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  76787. __decorate([
  76788. BABYLON.serialize()
  76789. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  76790. return VolumetricLightScatteringPostProcess;
  76791. }(BABYLON.PostProcess));
  76792. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  76793. })(BABYLON || (BABYLON = {}));
  76794. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  76795. //
  76796. // This post-process allows the modification of rendered colors by using
  76797. // a 'look-up table' (LUT). This effect is also called Color Grading.
  76798. //
  76799. // The object needs to be provided an url to a texture containing the color
  76800. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  76801. // Use an image editing software to tweak the LUT to match your needs.
  76802. //
  76803. // For an example of a color LUT, see here:
  76804. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  76805. // For explanations on color grading, see here:
  76806. // http://udn.epicgames.com/Three/ColorGrading.html
  76807. //
  76808. var BABYLON;
  76809. (function (BABYLON) {
  76810. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  76811. __extends(ColorCorrectionPostProcess, _super);
  76812. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  76813. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  76814. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76815. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  76816. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76817. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76818. _this.onApply = function (effect) {
  76819. effect.setTexture("colorTable", _this._colorTableTexture);
  76820. };
  76821. return _this;
  76822. }
  76823. return ColorCorrectionPostProcess;
  76824. }(BABYLON.PostProcess));
  76825. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  76826. })(BABYLON || (BABYLON = {}));
  76827. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  76828. var BABYLON;
  76829. (function (BABYLON) {
  76830. /** Defines operator used for tonemapping */
  76831. var TonemappingOperator;
  76832. (function (TonemappingOperator) {
  76833. /** Hable */
  76834. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  76835. /** Reinhard */
  76836. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  76837. /** HejiDawson */
  76838. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  76839. /** Photographic */
  76840. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  76841. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  76842. ;
  76843. /**
  76844. * Defines a post process to apply tone mapping
  76845. */
  76846. var TonemapPostProcess = /** @class */ (function (_super) {
  76847. __extends(TonemapPostProcess, _super);
  76848. /**
  76849. * Creates a new TonemapPostProcess
  76850. * @param name defines the name of the postprocess
  76851. * @param _operator defines the operator to use
  76852. * @param exposureAdjustment defines the required exposure adjustement
  76853. * @param camera defines the camera to use (can be null)
  76854. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  76855. * @param engine defines the hosting engine (can be ignore if camera is set)
  76856. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  76857. */
  76858. function TonemapPostProcess(name, _operator,
  76859. /** Defines the required exposure adjustement */
  76860. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  76861. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76862. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76863. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  76864. _this._operator = _operator;
  76865. _this.exposureAdjustment = exposureAdjustment;
  76866. var defines = "#define ";
  76867. if (_this._operator === TonemappingOperator.Hable)
  76868. defines += "HABLE_TONEMAPPING";
  76869. else if (_this._operator === TonemappingOperator.Reinhard)
  76870. defines += "REINHARD_TONEMAPPING";
  76871. else if (_this._operator === TonemappingOperator.HejiDawson)
  76872. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  76873. else if (_this._operator === TonemappingOperator.Photographic)
  76874. defines += "PHOTOGRAPHIC_TONEMAPPING";
  76875. //sadly a second call to create the effect.
  76876. _this.updateEffect(defines);
  76877. _this.onApply = function (effect) {
  76878. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  76879. };
  76880. return _this;
  76881. }
  76882. return TonemapPostProcess;
  76883. }(BABYLON.PostProcess));
  76884. BABYLON.TonemapPostProcess = TonemapPostProcess;
  76885. })(BABYLON || (BABYLON = {}));
  76886. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  76887. var BABYLON;
  76888. (function (BABYLON) {
  76889. var DisplayPassPostProcess = /** @class */ (function (_super) {
  76890. __extends(DisplayPassPostProcess, _super);
  76891. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  76892. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  76893. }
  76894. return DisplayPassPostProcess;
  76895. }(BABYLON.PostProcess));
  76896. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  76897. })(BABYLON || (BABYLON = {}));
  76898. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  76899. var BABYLON;
  76900. (function (BABYLON) {
  76901. var HighlightsPostProcess = /** @class */ (function (_super) {
  76902. __extends(HighlightsPostProcess, _super);
  76903. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  76904. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76905. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76906. }
  76907. return HighlightsPostProcess;
  76908. }(BABYLON.PostProcess));
  76909. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  76910. })(BABYLON || (BABYLON = {}));
  76911. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  76912. var BABYLON;
  76913. (function (BABYLON) {
  76914. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  76915. __extends(ImageProcessingPostProcess, _super);
  76916. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  76917. if (camera === void 0) { camera = null; }
  76918. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76919. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  76920. _this._fromLinearSpace = true;
  76921. /**
  76922. * Defines cache preventing GC.
  76923. */
  76924. _this._defines = {
  76925. IMAGEPROCESSING: false,
  76926. VIGNETTE: false,
  76927. VIGNETTEBLENDMODEMULTIPLY: false,
  76928. VIGNETTEBLENDMODEOPAQUE: false,
  76929. TONEMAPPING: false,
  76930. CONTRAST: false,
  76931. COLORCURVES: false,
  76932. COLORGRADING: false,
  76933. COLORGRADING3D: false,
  76934. FROMLINEARSPACE: false,
  76935. SAMPLER3DGREENDEPTH: false,
  76936. SAMPLER3DBGRMAP: false,
  76937. IMAGEPROCESSINGPOSTPROCESS: false,
  76938. EXPOSURE: false,
  76939. };
  76940. // Setup the configuration as forced by the constructor. This would then not force the
  76941. // scene materials output in linear space and let untouched the default forward pass.
  76942. if (imageProcessingConfiguration) {
  76943. imageProcessingConfiguration.applyByPostProcess = true;
  76944. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  76945. // This will cause the shader to be compiled
  76946. _this.fromLinearSpace = false;
  76947. }
  76948. // Setup the default processing configuration to the scene.
  76949. else {
  76950. _this._attachImageProcessingConfiguration(null, true);
  76951. _this.imageProcessingConfiguration.applyByPostProcess = true;
  76952. }
  76953. _this.onApply = function (effect) {
  76954. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  76955. };
  76956. return _this;
  76957. }
  76958. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  76959. /**
  76960. * Gets the image processing configuration used either in this material.
  76961. */
  76962. get: function () {
  76963. return this._imageProcessingConfiguration;
  76964. },
  76965. /**
  76966. * Sets the Default image processing configuration used either in the this material.
  76967. *
  76968. * If sets to null, the scene one is in use.
  76969. */
  76970. set: function (value) {
  76971. this._attachImageProcessingConfiguration(value);
  76972. },
  76973. enumerable: true,
  76974. configurable: true
  76975. });
  76976. /**
  76977. * Attaches a new image processing configuration to the PBR Material.
  76978. * @param configuration
  76979. */
  76980. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  76981. var _this = this;
  76982. if (doNotBuild === void 0) { doNotBuild = false; }
  76983. if (configuration === this._imageProcessingConfiguration) {
  76984. return;
  76985. }
  76986. // Detaches observer.
  76987. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  76988. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  76989. }
  76990. // Pick the scene configuration if needed.
  76991. if (!configuration) {
  76992. var scene = null;
  76993. var engine = this.getEngine();
  76994. var camera = this.getCamera();
  76995. if (camera) {
  76996. scene = camera.getScene();
  76997. }
  76998. else if (engine && engine.scenes) {
  76999. var scenes = engine.scenes;
  77000. scene = scenes[scenes.length - 1];
  77001. }
  77002. else {
  77003. scene = BABYLON.Engine.LastCreatedScene;
  77004. }
  77005. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  77006. }
  77007. else {
  77008. this._imageProcessingConfiguration = configuration;
  77009. }
  77010. // Attaches observer.
  77011. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  77012. _this._updateParameters();
  77013. });
  77014. // Ensure the effect will be rebuilt.
  77015. if (!doNotBuild) {
  77016. this._updateParameters();
  77017. }
  77018. };
  77019. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  77020. /**
  77021. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77022. */
  77023. get: function () {
  77024. return this.imageProcessingConfiguration.colorCurves;
  77025. },
  77026. /**
  77027. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77028. */
  77029. set: function (value) {
  77030. this.imageProcessingConfiguration.colorCurves = value;
  77031. },
  77032. enumerable: true,
  77033. configurable: true
  77034. });
  77035. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  77036. /**
  77037. * Gets wether the color curves effect is enabled.
  77038. */
  77039. get: function () {
  77040. return this.imageProcessingConfiguration.colorCurvesEnabled;
  77041. },
  77042. /**
  77043. * Sets wether the color curves effect is enabled.
  77044. */
  77045. set: function (value) {
  77046. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  77047. },
  77048. enumerable: true,
  77049. configurable: true
  77050. });
  77051. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  77052. /**
  77053. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77054. */
  77055. get: function () {
  77056. return this.imageProcessingConfiguration.colorGradingTexture;
  77057. },
  77058. /**
  77059. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77060. */
  77061. set: function (value) {
  77062. this.imageProcessingConfiguration.colorGradingTexture = value;
  77063. },
  77064. enumerable: true,
  77065. configurable: true
  77066. });
  77067. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  77068. /**
  77069. * Gets wether the color grading effect is enabled.
  77070. */
  77071. get: function () {
  77072. return this.imageProcessingConfiguration.colorGradingEnabled;
  77073. },
  77074. /**
  77075. * Gets wether the color grading effect is enabled.
  77076. */
  77077. set: function (value) {
  77078. this.imageProcessingConfiguration.colorGradingEnabled = value;
  77079. },
  77080. enumerable: true,
  77081. configurable: true
  77082. });
  77083. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  77084. /**
  77085. * Gets exposure used in the effect.
  77086. */
  77087. get: function () {
  77088. return this.imageProcessingConfiguration.exposure;
  77089. },
  77090. /**
  77091. * Sets exposure used in the effect.
  77092. */
  77093. set: function (value) {
  77094. this.imageProcessingConfiguration.exposure = value;
  77095. },
  77096. enumerable: true,
  77097. configurable: true
  77098. });
  77099. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  77100. /**
  77101. * Gets wether tonemapping is enabled or not.
  77102. */
  77103. get: function () {
  77104. return this._imageProcessingConfiguration.toneMappingEnabled;
  77105. },
  77106. /**
  77107. * Sets wether tonemapping is enabled or not
  77108. */
  77109. set: function (value) {
  77110. this._imageProcessingConfiguration.toneMappingEnabled = value;
  77111. },
  77112. enumerable: true,
  77113. configurable: true
  77114. });
  77115. ;
  77116. ;
  77117. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  77118. /**
  77119. * Gets contrast used in the effect.
  77120. */
  77121. get: function () {
  77122. return this.imageProcessingConfiguration.contrast;
  77123. },
  77124. /**
  77125. * Sets contrast used in the effect.
  77126. */
  77127. set: function (value) {
  77128. this.imageProcessingConfiguration.contrast = value;
  77129. },
  77130. enumerable: true,
  77131. configurable: true
  77132. });
  77133. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  77134. /**
  77135. * Gets Vignette stretch size.
  77136. */
  77137. get: function () {
  77138. return this.imageProcessingConfiguration.vignetteStretch;
  77139. },
  77140. /**
  77141. * Sets Vignette stretch size.
  77142. */
  77143. set: function (value) {
  77144. this.imageProcessingConfiguration.vignetteStretch = value;
  77145. },
  77146. enumerable: true,
  77147. configurable: true
  77148. });
  77149. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  77150. /**
  77151. * Gets Vignette centre X Offset.
  77152. */
  77153. get: function () {
  77154. return this.imageProcessingConfiguration.vignetteCentreX;
  77155. },
  77156. /**
  77157. * Sets Vignette centre X Offset.
  77158. */
  77159. set: function (value) {
  77160. this.imageProcessingConfiguration.vignetteCentreX = value;
  77161. },
  77162. enumerable: true,
  77163. configurable: true
  77164. });
  77165. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  77166. /**
  77167. * Gets Vignette centre Y Offset.
  77168. */
  77169. get: function () {
  77170. return this.imageProcessingConfiguration.vignetteCentreY;
  77171. },
  77172. /**
  77173. * Sets Vignette centre Y Offset.
  77174. */
  77175. set: function (value) {
  77176. this.imageProcessingConfiguration.vignetteCentreY = value;
  77177. },
  77178. enumerable: true,
  77179. configurable: true
  77180. });
  77181. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  77182. /**
  77183. * Gets Vignette weight or intensity of the vignette effect.
  77184. */
  77185. get: function () {
  77186. return this.imageProcessingConfiguration.vignetteWeight;
  77187. },
  77188. /**
  77189. * Sets Vignette weight or intensity of the vignette effect.
  77190. */
  77191. set: function (value) {
  77192. this.imageProcessingConfiguration.vignetteWeight = value;
  77193. },
  77194. enumerable: true,
  77195. configurable: true
  77196. });
  77197. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  77198. /**
  77199. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77200. * if vignetteEnabled is set to true.
  77201. */
  77202. get: function () {
  77203. return this.imageProcessingConfiguration.vignetteColor;
  77204. },
  77205. /**
  77206. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77207. * if vignetteEnabled is set to true.
  77208. */
  77209. set: function (value) {
  77210. this.imageProcessingConfiguration.vignetteColor = value;
  77211. },
  77212. enumerable: true,
  77213. configurable: true
  77214. });
  77215. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  77216. /**
  77217. * Gets Camera field of view used by the Vignette effect.
  77218. */
  77219. get: function () {
  77220. return this.imageProcessingConfiguration.vignetteCameraFov;
  77221. },
  77222. /**
  77223. * Sets Camera field of view used by the Vignette effect.
  77224. */
  77225. set: function (value) {
  77226. this.imageProcessingConfiguration.vignetteCameraFov = value;
  77227. },
  77228. enumerable: true,
  77229. configurable: true
  77230. });
  77231. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  77232. /**
  77233. * Gets the vignette blend mode allowing different kind of effect.
  77234. */
  77235. get: function () {
  77236. return this.imageProcessingConfiguration.vignetteBlendMode;
  77237. },
  77238. /**
  77239. * Sets the vignette blend mode allowing different kind of effect.
  77240. */
  77241. set: function (value) {
  77242. this.imageProcessingConfiguration.vignetteBlendMode = value;
  77243. },
  77244. enumerable: true,
  77245. configurable: true
  77246. });
  77247. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  77248. /**
  77249. * Gets wether the vignette effect is enabled.
  77250. */
  77251. get: function () {
  77252. return this.imageProcessingConfiguration.vignetteEnabled;
  77253. },
  77254. /**
  77255. * Sets wether the vignette effect is enabled.
  77256. */
  77257. set: function (value) {
  77258. this.imageProcessingConfiguration.vignetteEnabled = value;
  77259. },
  77260. enumerable: true,
  77261. configurable: true
  77262. });
  77263. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  77264. /**
  77265. * Gets wether the input of the processing is in Gamma or Linear Space.
  77266. */
  77267. get: function () {
  77268. return this._fromLinearSpace;
  77269. },
  77270. /**
  77271. * Sets wether the input of the processing is in Gamma or Linear Space.
  77272. */
  77273. set: function (value) {
  77274. if (this._fromLinearSpace === value) {
  77275. return;
  77276. }
  77277. this._fromLinearSpace = value;
  77278. this._updateParameters();
  77279. },
  77280. enumerable: true,
  77281. configurable: true
  77282. });
  77283. ImageProcessingPostProcess.prototype.getClassName = function () {
  77284. return "ImageProcessingPostProcess";
  77285. };
  77286. ImageProcessingPostProcess.prototype._updateParameters = function () {
  77287. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  77288. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  77289. var defines = "";
  77290. for (var define in this._defines) {
  77291. if (this._defines[define]) {
  77292. defines += "#define " + define + ";\r\n";
  77293. }
  77294. }
  77295. var samplers = ["textureSampler"];
  77296. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  77297. var uniforms = ["scale"];
  77298. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  77299. this.updateEffect(defines, uniforms, samplers);
  77300. };
  77301. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  77302. _super.prototype.dispose.call(this, camera);
  77303. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77304. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77305. }
  77306. this.imageProcessingConfiguration.applyByPostProcess = false;
  77307. };
  77308. __decorate([
  77309. BABYLON.serialize()
  77310. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  77311. return ImageProcessingPostProcess;
  77312. }(BABYLON.PostProcess));
  77313. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  77314. })(BABYLON || (BABYLON = {}));
  77315. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  77316. var BABYLON;
  77317. (function (BABYLON) {
  77318. /**
  77319. * Class used to store bone information
  77320. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  77321. */
  77322. var Bone = /** @class */ (function (_super) {
  77323. __extends(Bone, _super);
  77324. /**
  77325. * Create a new bone
  77326. * @param name defines the bone name
  77327. * @param skeleton defines the parent skeleton
  77328. * @param parentBone defines the parent (can be null if the bone is the root)
  77329. * @param localMatrix defines the local matrix
  77330. * @param restPose defines the rest pose matrix
  77331. * @param baseMatrix defines the base matrix
  77332. * @param index defines index of the bone in the hiearchy
  77333. */
  77334. function Bone(
  77335. /**
  77336. * defines the bone name
  77337. */
  77338. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  77339. if (parentBone === void 0) { parentBone = null; }
  77340. if (localMatrix === void 0) { localMatrix = null; }
  77341. if (restPose === void 0) { restPose = null; }
  77342. if (baseMatrix === void 0) { baseMatrix = null; }
  77343. if (index === void 0) { index = null; }
  77344. var _this = _super.call(this, name, skeleton.getScene()) || this;
  77345. _this.name = name;
  77346. /**
  77347. * Gets the list of child bones
  77348. */
  77349. _this.children = new Array();
  77350. /** Gets the animations associated with this bone */
  77351. _this.animations = new Array();
  77352. /**
  77353. * @hidden Internal only
  77354. * Set this value to map this bone to a different index in the transform matrices
  77355. * Set this value to -1 to exclude the bone from the transform matrices
  77356. */
  77357. _this._index = null;
  77358. _this._absoluteTransform = new BABYLON.Matrix();
  77359. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  77360. _this._scalingDeterminant = 1;
  77361. _this._worldTransform = new BABYLON.Matrix();
  77362. _this._needToDecompose = true;
  77363. _this._needToCompose = false;
  77364. _this._skeleton = skeleton;
  77365. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  77366. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  77367. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  77368. _this._index = index;
  77369. skeleton.bones.push(_this);
  77370. _this.setParent(parentBone, false);
  77371. if (baseMatrix || localMatrix) {
  77372. _this._updateDifferenceMatrix();
  77373. }
  77374. return _this;
  77375. }
  77376. Object.defineProperty(Bone.prototype, "_matrix", {
  77377. /** @hidden */
  77378. get: function () {
  77379. this._compose();
  77380. return this._localMatrix;
  77381. },
  77382. /** @hidden */
  77383. set: function (value) {
  77384. this._localMatrix.copyFrom(value);
  77385. this._needToDecompose = true;
  77386. },
  77387. enumerable: true,
  77388. configurable: true
  77389. });
  77390. // Members
  77391. /**
  77392. * Gets the parent skeleton
  77393. * @returns a skeleton
  77394. */
  77395. Bone.prototype.getSkeleton = function () {
  77396. return this._skeleton;
  77397. };
  77398. /**
  77399. * Gets parent bone
  77400. * @returns a bone or null if the bone is the root of the bone hierarchy
  77401. */
  77402. Bone.prototype.getParent = function () {
  77403. return this._parent;
  77404. };
  77405. /**
  77406. * Sets the parent bone
  77407. * @param parent defines the parent (can be null if the bone is the root)
  77408. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77409. */
  77410. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  77411. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77412. if (this._parent === parent) {
  77413. return;
  77414. }
  77415. if (this._parent) {
  77416. var index = this._parent.children.indexOf(this);
  77417. if (index !== -1) {
  77418. this._parent.children.splice(index, 1);
  77419. }
  77420. }
  77421. this._parent = parent;
  77422. if (this._parent) {
  77423. this._parent.children.push(this);
  77424. }
  77425. if (updateDifferenceMatrix) {
  77426. this._updateDifferenceMatrix();
  77427. }
  77428. this.markAsDirty();
  77429. };
  77430. /**
  77431. * Gets the local matrix
  77432. * @returns a matrix
  77433. */
  77434. Bone.prototype.getLocalMatrix = function () {
  77435. this._compose();
  77436. return this._localMatrix;
  77437. };
  77438. /**
  77439. * Gets the base matrix (initial matrix which remains unchanged)
  77440. * @returns a matrix
  77441. */
  77442. Bone.prototype.getBaseMatrix = function () {
  77443. return this._baseMatrix;
  77444. };
  77445. /**
  77446. * Gets the rest pose matrix
  77447. * @returns a matrix
  77448. */
  77449. Bone.prototype.getRestPose = function () {
  77450. return this._restPose;
  77451. };
  77452. /**
  77453. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  77454. */
  77455. Bone.prototype.getWorldMatrix = function () {
  77456. return this._worldTransform;
  77457. };
  77458. /**
  77459. * Sets the local matrix to rest pose matrix
  77460. */
  77461. Bone.prototype.returnToRest = function () {
  77462. this.updateMatrix(this._restPose.clone());
  77463. };
  77464. /**
  77465. * Gets the inverse of the absolute transform matrix.
  77466. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  77467. * @returns a matrix
  77468. */
  77469. Bone.prototype.getInvertedAbsoluteTransform = function () {
  77470. return this._invertedAbsoluteTransform;
  77471. };
  77472. /**
  77473. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  77474. * @returns a matrix
  77475. */
  77476. Bone.prototype.getAbsoluteTransform = function () {
  77477. return this._absoluteTransform;
  77478. };
  77479. Object.defineProperty(Bone.prototype, "position", {
  77480. // Properties (matches AbstractMesh properties)
  77481. /** Gets or sets current position (in local space) */
  77482. get: function () {
  77483. this._decompose();
  77484. return this._localPosition;
  77485. },
  77486. set: function (newPosition) {
  77487. this._decompose();
  77488. this._localPosition.copyFrom(newPosition);
  77489. this._markAsDirtyAndCompose();
  77490. },
  77491. enumerable: true,
  77492. configurable: true
  77493. });
  77494. Object.defineProperty(Bone.prototype, "rotation", {
  77495. /** Gets or sets current rotation (in local space) */
  77496. get: function () {
  77497. return this.getRotation();
  77498. },
  77499. set: function (newRotation) {
  77500. this.setRotation(newRotation);
  77501. },
  77502. enumerable: true,
  77503. configurable: true
  77504. });
  77505. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  77506. /** Gets or sets current rotation quaternion (in local space) */
  77507. get: function () {
  77508. this._decompose();
  77509. return this._localRotation;
  77510. },
  77511. set: function (newRotation) {
  77512. this.setRotationQuaternion(newRotation);
  77513. },
  77514. enumerable: true,
  77515. configurable: true
  77516. });
  77517. Object.defineProperty(Bone.prototype, "scaling", {
  77518. /** Gets or sets current scaling (in local space) */
  77519. get: function () {
  77520. return this.getScale();
  77521. },
  77522. set: function (newScaling) {
  77523. this.setScale(newScaling);
  77524. },
  77525. enumerable: true,
  77526. configurable: true
  77527. });
  77528. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  77529. /**
  77530. * Gets the animation properties override
  77531. */
  77532. get: function () {
  77533. return this._skeleton.animationPropertiesOverride;
  77534. },
  77535. enumerable: true,
  77536. configurable: true
  77537. });
  77538. // Methods
  77539. Bone.prototype._decompose = function () {
  77540. if (!this._needToDecompose) {
  77541. return;
  77542. }
  77543. this._needToDecompose = false;
  77544. if (!this._localScaling) {
  77545. this._localScaling = BABYLON.Vector3.Zero();
  77546. this._localRotation = BABYLON.Quaternion.Zero();
  77547. this._localPosition = BABYLON.Vector3.Zero();
  77548. }
  77549. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  77550. };
  77551. Bone.prototype._compose = function () {
  77552. if (!this._needToCompose) {
  77553. return;
  77554. }
  77555. this._needToCompose = false;
  77556. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  77557. };
  77558. /**
  77559. * Update the base and local matrices
  77560. * @param matrix defines the new base or local matrix
  77561. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77562. * @param updateLocalMatrix defines if the local matrix should be updated
  77563. */
  77564. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  77565. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77566. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  77567. this._baseMatrix.copyFrom(matrix);
  77568. if (updateDifferenceMatrix) {
  77569. this._updateDifferenceMatrix();
  77570. }
  77571. if (updateLocalMatrix) {
  77572. this._localMatrix.copyFrom(matrix);
  77573. this._markAsDirtyAndDecompose();
  77574. }
  77575. else {
  77576. this.markAsDirty();
  77577. }
  77578. };
  77579. /** @hidden */
  77580. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  77581. if (updateChildren === void 0) { updateChildren = true; }
  77582. if (!rootMatrix) {
  77583. rootMatrix = this._baseMatrix;
  77584. }
  77585. if (this._parent) {
  77586. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  77587. }
  77588. else {
  77589. this._absoluteTransform.copyFrom(rootMatrix);
  77590. }
  77591. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  77592. if (updateChildren) {
  77593. for (var index = 0; index < this.children.length; index++) {
  77594. this.children[index]._updateDifferenceMatrix();
  77595. }
  77596. }
  77597. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  77598. };
  77599. /**
  77600. * Flag the bone as dirty (Forcing it to update everything)
  77601. */
  77602. Bone.prototype.markAsDirty = function () {
  77603. this._currentRenderId++;
  77604. this._childRenderId++;
  77605. this._skeleton._markAsDirty();
  77606. };
  77607. Bone.prototype._markAsDirtyAndCompose = function () {
  77608. this.markAsDirty();
  77609. this._needToCompose = true;
  77610. };
  77611. Bone.prototype._markAsDirtyAndDecompose = function () {
  77612. this.markAsDirty();
  77613. this._needToDecompose = true;
  77614. };
  77615. /**
  77616. * Copy an animation range from another bone
  77617. * @param source defines the source bone
  77618. * @param rangeName defines the range name to copy
  77619. * @param frameOffset defines the frame offset
  77620. * @param rescaleAsRequired defines if rescaling must be applied if required
  77621. * @param skelDimensionsRatio defines the scaling ratio
  77622. * @returns true if operation was successful
  77623. */
  77624. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  77625. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  77626. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  77627. // all animation may be coming from a library skeleton, so may need to create animation
  77628. if (this.animations.length === 0) {
  77629. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  77630. this.animations[0].setKeys([]);
  77631. }
  77632. // get animation info / verify there is such a range from the source bone
  77633. var sourceRange = source.animations[0].getRange(rangeName);
  77634. if (!sourceRange) {
  77635. return false;
  77636. }
  77637. var from = sourceRange.from;
  77638. var to = sourceRange.to;
  77639. var sourceKeys = source.animations[0].getKeys();
  77640. // rescaling prep
  77641. var sourceBoneLength = source.length;
  77642. var sourceParent = source.getParent();
  77643. var parent = this.getParent();
  77644. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  77645. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  77646. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  77647. var destKeys = this.animations[0].getKeys();
  77648. // loop vars declaration
  77649. var orig;
  77650. var origTranslation;
  77651. var mat;
  77652. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  77653. orig = sourceKeys[key];
  77654. if (orig.frame >= from && orig.frame <= to) {
  77655. if (rescaleAsRequired) {
  77656. mat = orig.value.clone();
  77657. // scale based on parent ratio, when bone has parent
  77658. if (parentScalingReqd) {
  77659. origTranslation = mat.getTranslation();
  77660. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  77661. // scale based on skeleton dimension ratio when root bone, and value is passed
  77662. }
  77663. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  77664. origTranslation = mat.getTranslation();
  77665. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  77666. // use original when root bone, and no data for skelDimensionsRatio
  77667. }
  77668. else {
  77669. mat = orig.value;
  77670. }
  77671. }
  77672. else {
  77673. mat = orig.value;
  77674. }
  77675. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  77676. }
  77677. }
  77678. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  77679. return true;
  77680. };
  77681. /**
  77682. * Translate the bone in local or world space
  77683. * @param vec The amount to translate the bone
  77684. * @param space The space that the translation is in
  77685. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77686. */
  77687. Bone.prototype.translate = function (vec, space, mesh) {
  77688. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77689. var lm = this.getLocalMatrix();
  77690. if (space == BABYLON.Space.LOCAL) {
  77691. lm.m[12] += vec.x;
  77692. lm.m[13] += vec.y;
  77693. lm.m[14] += vec.z;
  77694. }
  77695. else {
  77696. var wm = null;
  77697. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77698. if (mesh) {
  77699. wm = mesh.getWorldMatrix();
  77700. }
  77701. this._skeleton.computeAbsoluteTransforms();
  77702. var tmat = Bone._tmpMats[0];
  77703. var tvec = Bone._tmpVecs[0];
  77704. if (this._parent) {
  77705. if (mesh && wm) {
  77706. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77707. tmat.multiplyToRef(wm, tmat);
  77708. }
  77709. else {
  77710. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77711. }
  77712. }
  77713. tmat.m[12] = 0;
  77714. tmat.m[13] = 0;
  77715. tmat.m[14] = 0;
  77716. tmat.invert();
  77717. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  77718. lm.m[12] += tvec.x;
  77719. lm.m[13] += tvec.y;
  77720. lm.m[14] += tvec.z;
  77721. }
  77722. this._markAsDirtyAndDecompose();
  77723. };
  77724. /**
  77725. * Set the postion of the bone in local or world space
  77726. * @param position The position to set the bone
  77727. * @param space The space that the position is in
  77728. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77729. */
  77730. Bone.prototype.setPosition = function (position, space, mesh) {
  77731. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77732. var lm = this.getLocalMatrix();
  77733. if (space == BABYLON.Space.LOCAL) {
  77734. lm.m[12] = position.x;
  77735. lm.m[13] = position.y;
  77736. lm.m[14] = position.z;
  77737. }
  77738. else {
  77739. var wm = null;
  77740. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77741. if (mesh) {
  77742. wm = mesh.getWorldMatrix();
  77743. }
  77744. this._skeleton.computeAbsoluteTransforms();
  77745. var tmat = Bone._tmpMats[0];
  77746. var vec = Bone._tmpVecs[0];
  77747. if (this._parent) {
  77748. if (mesh && wm) {
  77749. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77750. tmat.multiplyToRef(wm, tmat);
  77751. }
  77752. else {
  77753. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77754. }
  77755. }
  77756. tmat.invert();
  77757. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  77758. lm.m[12] = vec.x;
  77759. lm.m[13] = vec.y;
  77760. lm.m[14] = vec.z;
  77761. }
  77762. this._markAsDirtyAndDecompose();
  77763. };
  77764. /**
  77765. * Set the absolute position of the bone (world space)
  77766. * @param position The position to set the bone
  77767. * @param mesh The mesh that this bone is attached to
  77768. */
  77769. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  77770. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  77771. };
  77772. /**
  77773. * Scale the bone on the x, y and z axes (in local space)
  77774. * @param x The amount to scale the bone on the x axis
  77775. * @param y The amount to scale the bone on the y axis
  77776. * @param z The amount to scale the bone on the z axis
  77777. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  77778. */
  77779. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  77780. if (scaleChildren === void 0) { scaleChildren = false; }
  77781. var locMat = this.getLocalMatrix();
  77782. // Apply new scaling on top of current local matrix
  77783. var scaleMat = Bone._tmpMats[0];
  77784. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  77785. scaleMat.multiplyToRef(locMat, locMat);
  77786. // Invert scaling matrix and apply the inverse to all children
  77787. scaleMat.invert();
  77788. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  77789. var child = _a[_i];
  77790. var cm = child.getLocalMatrix();
  77791. cm.multiplyToRef(scaleMat, cm);
  77792. cm.m[12] *= x;
  77793. cm.m[13] *= y;
  77794. cm.m[14] *= z;
  77795. child._markAsDirtyAndDecompose();
  77796. }
  77797. this._markAsDirtyAndDecompose();
  77798. if (scaleChildren) {
  77799. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  77800. var child = _c[_b];
  77801. child.scale(x, y, z, scaleChildren);
  77802. }
  77803. }
  77804. };
  77805. /**
  77806. * Set the bone scaling in local space
  77807. * @param scale defines the scaling vector
  77808. */
  77809. Bone.prototype.setScale = function (scale) {
  77810. this._decompose();
  77811. this._localScaling.copyFrom(scale);
  77812. this._markAsDirtyAndCompose();
  77813. };
  77814. /**
  77815. * Gets the current scaling in local space
  77816. * @returns the current scaling vector
  77817. */
  77818. Bone.prototype.getScale = function () {
  77819. this._decompose();
  77820. return this._localScaling;
  77821. };
  77822. /**
  77823. * Gets the current scaling in local space and stores it in a target vector
  77824. * @param result defines the target vector
  77825. */
  77826. Bone.prototype.getScaleToRef = function (result) {
  77827. this._decompose();
  77828. result.copyFrom(this._localScaling);
  77829. };
  77830. /**
  77831. * Set the yaw, pitch, and roll of the bone in local or world space
  77832. * @param yaw The rotation of the bone on the y axis
  77833. * @param pitch The rotation of the bone on the x axis
  77834. * @param roll The rotation of the bone on the z axis
  77835. * @param space The space that the axes of rotation are in
  77836. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77837. */
  77838. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  77839. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77840. if (space === BABYLON.Space.LOCAL) {
  77841. var quat = Bone._tmpQuat;
  77842. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  77843. this.setRotationQuaternion(quat, space, mesh);
  77844. return;
  77845. }
  77846. var rotMatInv = Bone._tmpMats[0];
  77847. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77848. return;
  77849. }
  77850. var rotMat = Bone._tmpMats[1];
  77851. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  77852. rotMatInv.multiplyToRef(rotMat, rotMat);
  77853. this._rotateWithMatrix(rotMat, space, mesh);
  77854. };
  77855. /**
  77856. * Add a rotation to the bone on an axis in local or world space
  77857. * @param axis The axis to rotate the bone on
  77858. * @param amount The amount to rotate the bone
  77859. * @param space The space that the axis is in
  77860. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77861. */
  77862. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  77863. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77864. var rmat = Bone._tmpMats[0];
  77865. rmat.m[12] = 0;
  77866. rmat.m[13] = 0;
  77867. rmat.m[14] = 0;
  77868. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  77869. this._rotateWithMatrix(rmat, space, mesh);
  77870. };
  77871. /**
  77872. * Set the rotation of the bone to a particular axis angle in local or world space
  77873. * @param axis The axis to rotate the bone on
  77874. * @param angle The angle that the bone should be rotated to
  77875. * @param space The space that the axis is in
  77876. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77877. */
  77878. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  77879. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77880. if (space === BABYLON.Space.LOCAL) {
  77881. var quat = Bone._tmpQuat;
  77882. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  77883. this.setRotationQuaternion(quat, space, mesh);
  77884. return;
  77885. }
  77886. var rotMatInv = Bone._tmpMats[0];
  77887. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77888. return;
  77889. }
  77890. var rotMat = Bone._tmpMats[1];
  77891. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  77892. rotMatInv.multiplyToRef(rotMat, rotMat);
  77893. this._rotateWithMatrix(rotMat, space, mesh);
  77894. };
  77895. /**
  77896. * Set the euler rotation of the bone in local of world space
  77897. * @param rotation The euler rotation that the bone should be set to
  77898. * @param space The space that the rotation is in
  77899. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77900. */
  77901. Bone.prototype.setRotation = function (rotation, space, mesh) {
  77902. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77903. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  77904. };
  77905. /**
  77906. * Set the quaternion rotation of the bone in local of world space
  77907. * @param quat The quaternion rotation that the bone should be set to
  77908. * @param space The space that the rotation is in
  77909. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77910. */
  77911. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  77912. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77913. if (space === BABYLON.Space.LOCAL) {
  77914. this._decompose();
  77915. this._localRotation.copyFrom(quat);
  77916. this._markAsDirtyAndCompose();
  77917. return;
  77918. }
  77919. var rotMatInv = Bone._tmpMats[0];
  77920. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77921. return;
  77922. }
  77923. var rotMat = Bone._tmpMats[1];
  77924. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  77925. rotMatInv.multiplyToRef(rotMat, rotMat);
  77926. this._rotateWithMatrix(rotMat, space, mesh);
  77927. };
  77928. /**
  77929. * Set the rotation matrix of the bone in local of world space
  77930. * @param rotMat The rotation matrix that the bone should be set to
  77931. * @param space The space that the rotation is in
  77932. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77933. */
  77934. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  77935. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77936. if (space === BABYLON.Space.LOCAL) {
  77937. var quat = Bone._tmpQuat;
  77938. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  77939. this.setRotationQuaternion(quat, space, mesh);
  77940. return;
  77941. }
  77942. var rotMatInv = Bone._tmpMats[0];
  77943. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77944. return;
  77945. }
  77946. var rotMat2 = Bone._tmpMats[1];
  77947. rotMat2.copyFrom(rotMat);
  77948. rotMatInv.multiplyToRef(rotMat, rotMat2);
  77949. this._rotateWithMatrix(rotMat2, space, mesh);
  77950. };
  77951. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  77952. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77953. var lmat = this.getLocalMatrix();
  77954. var lx = lmat.m[12];
  77955. var ly = lmat.m[13];
  77956. var lz = lmat.m[14];
  77957. var parent = this.getParent();
  77958. var parentScale = Bone._tmpMats[3];
  77959. var parentScaleInv = Bone._tmpMats[4];
  77960. if (parent && space == BABYLON.Space.WORLD) {
  77961. if (mesh) {
  77962. parentScale.copyFrom(mesh.getWorldMatrix());
  77963. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  77964. }
  77965. else {
  77966. parentScale.copyFrom(parent.getAbsoluteTransform());
  77967. }
  77968. parentScaleInv.copyFrom(parentScale);
  77969. parentScaleInv.invert();
  77970. lmat.multiplyToRef(parentScale, lmat);
  77971. lmat.multiplyToRef(rmat, lmat);
  77972. lmat.multiplyToRef(parentScaleInv, lmat);
  77973. }
  77974. else {
  77975. if (space == BABYLON.Space.WORLD && mesh) {
  77976. parentScale.copyFrom(mesh.getWorldMatrix());
  77977. parentScaleInv.copyFrom(parentScale);
  77978. parentScaleInv.invert();
  77979. lmat.multiplyToRef(parentScale, lmat);
  77980. lmat.multiplyToRef(rmat, lmat);
  77981. lmat.multiplyToRef(parentScaleInv, lmat);
  77982. }
  77983. else {
  77984. lmat.multiplyToRef(rmat, lmat);
  77985. }
  77986. }
  77987. lmat.m[12] = lx;
  77988. lmat.m[13] = ly;
  77989. lmat.m[14] = lz;
  77990. this.computeAbsoluteTransforms();
  77991. this._markAsDirtyAndDecompose();
  77992. };
  77993. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  77994. var scaleMatrix = Bone._tmpMats[2];
  77995. rotMatInv.copyFrom(this.getAbsoluteTransform());
  77996. if (mesh) {
  77997. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  77998. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  77999. }
  78000. rotMatInv.invert();
  78001. if (isNaN(rotMatInv.m[0])) {
  78002. // Matrix failed to invert.
  78003. // This can happen if scale is zero for example.
  78004. return false;
  78005. }
  78006. scaleMatrix.m[0] *= this._scalingDeterminant;
  78007. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  78008. return true;
  78009. };
  78010. /**
  78011. * Get the position of the bone in local or world space
  78012. * @param space The space that the returned position is in
  78013. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78014. * @returns The position of the bone
  78015. */
  78016. Bone.prototype.getPosition = function (space, mesh) {
  78017. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78018. if (mesh === void 0) { mesh = null; }
  78019. var pos = BABYLON.Vector3.Zero();
  78020. this.getPositionToRef(space, mesh, pos);
  78021. return pos;
  78022. };
  78023. /**
  78024. * Copy the position of the bone to a vector3 in local or world space
  78025. * @param space The space that the returned position is in
  78026. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78027. * @param result The vector3 to copy the position to
  78028. */
  78029. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  78030. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78031. if (space == BABYLON.Space.LOCAL) {
  78032. var lm = this.getLocalMatrix();
  78033. result.x = lm.m[12];
  78034. result.y = lm.m[13];
  78035. result.z = lm.m[14];
  78036. }
  78037. else {
  78038. var wm = null;
  78039. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78040. if (mesh) {
  78041. wm = mesh.getWorldMatrix();
  78042. }
  78043. this._skeleton.computeAbsoluteTransforms();
  78044. var tmat = Bone._tmpMats[0];
  78045. if (mesh && wm) {
  78046. tmat.copyFrom(this.getAbsoluteTransform());
  78047. tmat.multiplyToRef(wm, tmat);
  78048. }
  78049. else {
  78050. tmat = this.getAbsoluteTransform();
  78051. }
  78052. result.x = tmat.m[12];
  78053. result.y = tmat.m[13];
  78054. result.z = tmat.m[14];
  78055. }
  78056. };
  78057. /**
  78058. * Get the absolute position of the bone (world space)
  78059. * @param mesh The mesh that this bone is attached to
  78060. * @returns The absolute position of the bone
  78061. */
  78062. Bone.prototype.getAbsolutePosition = function (mesh) {
  78063. if (mesh === void 0) { mesh = null; }
  78064. var pos = BABYLON.Vector3.Zero();
  78065. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  78066. return pos;
  78067. };
  78068. /**
  78069. * Copy the absolute position of the bone (world space) to the result param
  78070. * @param mesh The mesh that this bone is attached to
  78071. * @param result The vector3 to copy the absolute position to
  78072. */
  78073. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  78074. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  78075. };
  78076. /**
  78077. * Compute the absolute transforms of this bone and its children
  78078. */
  78079. Bone.prototype.computeAbsoluteTransforms = function () {
  78080. this._compose();
  78081. if (this._parent) {
  78082. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78083. }
  78084. else {
  78085. this._absoluteTransform.copyFrom(this._localMatrix);
  78086. var poseMatrix = this._skeleton.getPoseMatrix();
  78087. if (poseMatrix) {
  78088. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  78089. }
  78090. }
  78091. var children = this.children;
  78092. var len = children.length;
  78093. for (var i = 0; i < len; i++) {
  78094. children[i].computeAbsoluteTransforms();
  78095. }
  78096. };
  78097. /**
  78098. * Get the world direction from an axis that is in the local space of the bone
  78099. * @param localAxis The local direction that is used to compute the world direction
  78100. * @param mesh The mesh that this bone is attached to
  78101. * @returns The world direction
  78102. */
  78103. Bone.prototype.getDirection = function (localAxis, mesh) {
  78104. if (mesh === void 0) { mesh = null; }
  78105. var result = BABYLON.Vector3.Zero();
  78106. this.getDirectionToRef(localAxis, mesh, result);
  78107. return result;
  78108. };
  78109. /**
  78110. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  78111. * @param localAxis The local direction that is used to compute the world direction
  78112. * @param mesh The mesh that this bone is attached to
  78113. * @param result The vector3 that the world direction will be copied to
  78114. */
  78115. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  78116. if (mesh === void 0) { mesh = null; }
  78117. var wm = null;
  78118. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78119. if (mesh) {
  78120. wm = mesh.getWorldMatrix();
  78121. }
  78122. this._skeleton.computeAbsoluteTransforms();
  78123. var mat = Bone._tmpMats[0];
  78124. mat.copyFrom(this.getAbsoluteTransform());
  78125. if (mesh && wm) {
  78126. mat.multiplyToRef(wm, mat);
  78127. }
  78128. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  78129. result.normalize();
  78130. };
  78131. /**
  78132. * Get the euler rotation of the bone in local or world space
  78133. * @param space The space that the rotation should be in
  78134. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78135. * @returns The euler rotation
  78136. */
  78137. Bone.prototype.getRotation = function (space, mesh) {
  78138. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78139. if (mesh === void 0) { mesh = null; }
  78140. var result = BABYLON.Vector3.Zero();
  78141. this.getRotationToRef(space, mesh, result);
  78142. return result;
  78143. };
  78144. /**
  78145. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  78146. * @param space The space that the rotation should be in
  78147. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78148. * @param result The vector3 that the rotation should be copied to
  78149. */
  78150. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  78151. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78152. if (mesh === void 0) { mesh = null; }
  78153. var quat = Bone._tmpQuat;
  78154. this.getRotationQuaternionToRef(space, mesh, quat);
  78155. quat.toEulerAnglesToRef(result);
  78156. };
  78157. /**
  78158. * Get the quaternion rotation of the bone in either local or world space
  78159. * @param space The space that the rotation should be in
  78160. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78161. * @returns The quaternion rotation
  78162. */
  78163. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  78164. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78165. if (mesh === void 0) { mesh = null; }
  78166. var result = BABYLON.Quaternion.Identity();
  78167. this.getRotationQuaternionToRef(space, mesh, result);
  78168. return result;
  78169. };
  78170. /**
  78171. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  78172. * @param space The space that the rotation should be in
  78173. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78174. * @param result The quaternion that the rotation should be copied to
  78175. */
  78176. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  78177. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78178. if (mesh === void 0) { mesh = null; }
  78179. if (space == BABYLON.Space.LOCAL) {
  78180. this._decompose();
  78181. result.copyFrom(this._localRotation);
  78182. }
  78183. else {
  78184. var mat = Bone._tmpMats[0];
  78185. var amat = this.getAbsoluteTransform();
  78186. if (mesh) {
  78187. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78188. }
  78189. else {
  78190. mat.copyFrom(amat);
  78191. }
  78192. mat.m[0] *= this._scalingDeterminant;
  78193. mat.m[1] *= this._scalingDeterminant;
  78194. mat.m[2] *= this._scalingDeterminant;
  78195. mat.decompose(undefined, result, undefined);
  78196. }
  78197. };
  78198. /**
  78199. * Get the rotation matrix of the bone in local or world space
  78200. * @param space The space that the rotation should be in
  78201. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78202. * @returns The rotation matrix
  78203. */
  78204. Bone.prototype.getRotationMatrix = function (space, mesh) {
  78205. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78206. var result = BABYLON.Matrix.Identity();
  78207. this.getRotationMatrixToRef(space, mesh, result);
  78208. return result;
  78209. };
  78210. /**
  78211. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  78212. * @param space The space that the rotation should be in
  78213. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78214. * @param result The quaternion that the rotation should be copied to
  78215. */
  78216. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  78217. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78218. if (space == BABYLON.Space.LOCAL) {
  78219. this.getLocalMatrix().getRotationMatrixToRef(result);
  78220. }
  78221. else {
  78222. var mat = Bone._tmpMats[0];
  78223. var amat = this.getAbsoluteTransform();
  78224. if (mesh) {
  78225. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78226. }
  78227. else {
  78228. mat.copyFrom(amat);
  78229. }
  78230. mat.m[0] *= this._scalingDeterminant;
  78231. mat.m[1] *= this._scalingDeterminant;
  78232. mat.m[2] *= this._scalingDeterminant;
  78233. mat.getRotationMatrixToRef(result);
  78234. }
  78235. };
  78236. /**
  78237. * Get the world position of a point that is in the local space of the bone
  78238. * @param position The local position
  78239. * @param mesh The mesh that this bone is attached to
  78240. * @returns The world position
  78241. */
  78242. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  78243. if (mesh === void 0) { mesh = null; }
  78244. var result = BABYLON.Vector3.Zero();
  78245. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  78246. return result;
  78247. };
  78248. /**
  78249. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  78250. * @param position The local position
  78251. * @param mesh The mesh that this bone is attached to
  78252. * @param result The vector3 that the world position should be copied to
  78253. */
  78254. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  78255. if (mesh === void 0) { mesh = null; }
  78256. var wm = null;
  78257. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78258. if (mesh) {
  78259. wm = mesh.getWorldMatrix();
  78260. }
  78261. this._skeleton.computeAbsoluteTransforms();
  78262. var tmat = Bone._tmpMats[0];
  78263. if (mesh && wm) {
  78264. tmat.copyFrom(this.getAbsoluteTransform());
  78265. tmat.multiplyToRef(wm, tmat);
  78266. }
  78267. else {
  78268. tmat = this.getAbsoluteTransform();
  78269. }
  78270. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78271. };
  78272. /**
  78273. * Get the local position of a point that is in world space
  78274. * @param position The world position
  78275. * @param mesh The mesh that this bone is attached to
  78276. * @returns The local position
  78277. */
  78278. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  78279. if (mesh === void 0) { mesh = null; }
  78280. var result = BABYLON.Vector3.Zero();
  78281. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  78282. return result;
  78283. };
  78284. /**
  78285. * Get the local position of a point that is in world space and copy it to the result param
  78286. * @param position The world position
  78287. * @param mesh The mesh that this bone is attached to
  78288. * @param result The vector3 that the local position should be copied to
  78289. */
  78290. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  78291. if (mesh === void 0) { mesh = null; }
  78292. var wm = null;
  78293. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78294. if (mesh) {
  78295. wm = mesh.getWorldMatrix();
  78296. }
  78297. this._skeleton.computeAbsoluteTransforms();
  78298. var tmat = Bone._tmpMats[0];
  78299. tmat.copyFrom(this.getAbsoluteTransform());
  78300. if (mesh && wm) {
  78301. tmat.multiplyToRef(wm, tmat);
  78302. }
  78303. tmat.invert();
  78304. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78305. };
  78306. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78307. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  78308. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78309. return Bone;
  78310. }(BABYLON.Node));
  78311. BABYLON.Bone = Bone;
  78312. })(BABYLON || (BABYLON = {}));
  78313. //# sourceMappingURL=babylon.bone.js.map
  78314. var BABYLON;
  78315. (function (BABYLON) {
  78316. /**
  78317. * Class used to apply inverse kinematics to bones
  78318. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  78319. */
  78320. var BoneIKController = /** @class */ (function () {
  78321. /**
  78322. * Creates a new BoneIKController
  78323. * @param mesh defines the mesh to control
  78324. * @param bone defines the bone to control
  78325. * @param options defines options to set up the controller
  78326. */
  78327. function BoneIKController(mesh, bone, options) {
  78328. /**
  78329. * Gets or sets the target position
  78330. */
  78331. this.targetPosition = BABYLON.Vector3.Zero();
  78332. /**
  78333. * Gets or sets the pole target position
  78334. */
  78335. this.poleTargetPosition = BABYLON.Vector3.Zero();
  78336. /**
  78337. * Gets or sets the pole target local offset
  78338. */
  78339. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  78340. /**
  78341. * Gets or sets the pole angle
  78342. */
  78343. this.poleAngle = 0;
  78344. /**
  78345. * 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)
  78346. */
  78347. this.slerpAmount = 1;
  78348. this._bone1Quat = BABYLON.Quaternion.Identity();
  78349. this._bone1Mat = BABYLON.Matrix.Identity();
  78350. this._bone2Ang = Math.PI;
  78351. this._maxAngle = Math.PI;
  78352. this._rightHandedSystem = false;
  78353. this._bendAxis = BABYLON.Vector3.Right();
  78354. this._slerping = false;
  78355. this._adjustRoll = 0;
  78356. this._bone2 = bone;
  78357. this._bone1 = bone.getParent();
  78358. if (!this._bone1) {
  78359. return;
  78360. }
  78361. this.mesh = mesh;
  78362. var bonePos = bone.getPosition();
  78363. if (bone.getAbsoluteTransform().determinant() > 0) {
  78364. this._rightHandedSystem = true;
  78365. this._bendAxis.x = 0;
  78366. this._bendAxis.y = 0;
  78367. this._bendAxis.z = -1;
  78368. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  78369. this._adjustRoll = Math.PI * .5;
  78370. this._bendAxis.z = 1;
  78371. }
  78372. }
  78373. if (this._bone1.length) {
  78374. var boneScale1 = this._bone1.getScale();
  78375. var boneScale2 = this._bone2.getScale();
  78376. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  78377. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  78378. }
  78379. else if (this._bone1.children[0]) {
  78380. mesh.computeWorldMatrix(true);
  78381. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  78382. var pos2 = this._bone2.getAbsolutePosition(mesh);
  78383. var pos3 = this._bone1.getAbsolutePosition(mesh);
  78384. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  78385. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  78386. }
  78387. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  78388. this.maxAngle = Math.PI;
  78389. if (options) {
  78390. if (options.targetMesh) {
  78391. this.targetMesh = options.targetMesh;
  78392. this.targetMesh.computeWorldMatrix(true);
  78393. }
  78394. if (options.poleTargetMesh) {
  78395. this.poleTargetMesh = options.poleTargetMesh;
  78396. this.poleTargetMesh.computeWorldMatrix(true);
  78397. }
  78398. else if (options.poleTargetBone) {
  78399. this.poleTargetBone = options.poleTargetBone;
  78400. }
  78401. else if (this._bone1.getParent()) {
  78402. this.poleTargetBone = this._bone1.getParent();
  78403. }
  78404. if (options.poleTargetLocalOffset) {
  78405. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  78406. }
  78407. if (options.poleAngle) {
  78408. this.poleAngle = options.poleAngle;
  78409. }
  78410. if (options.bendAxis) {
  78411. this._bendAxis.copyFrom(options.bendAxis);
  78412. }
  78413. if (options.maxAngle) {
  78414. this.maxAngle = options.maxAngle;
  78415. }
  78416. if (options.slerpAmount) {
  78417. this.slerpAmount = options.slerpAmount;
  78418. }
  78419. }
  78420. }
  78421. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  78422. /**
  78423. * Gets or sets maximum allowed angle
  78424. */
  78425. get: function () {
  78426. return this._maxAngle;
  78427. },
  78428. set: function (value) {
  78429. this._setMaxAngle(value);
  78430. },
  78431. enumerable: true,
  78432. configurable: true
  78433. });
  78434. BoneIKController.prototype._setMaxAngle = function (ang) {
  78435. if (ang < 0) {
  78436. ang = 0;
  78437. }
  78438. if (ang > Math.PI || ang == undefined) {
  78439. ang = Math.PI;
  78440. }
  78441. this._maxAngle = ang;
  78442. var a = this._bone1Length;
  78443. var b = this._bone2Length;
  78444. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  78445. };
  78446. /**
  78447. * Force the controller to update the bones
  78448. */
  78449. BoneIKController.prototype.update = function () {
  78450. var bone1 = this._bone1;
  78451. if (!bone1) {
  78452. return;
  78453. }
  78454. var target = this.targetPosition;
  78455. var poleTarget = this.poleTargetPosition;
  78456. var mat1 = BoneIKController._tmpMats[0];
  78457. var mat2 = BoneIKController._tmpMats[1];
  78458. if (this.targetMesh) {
  78459. target.copyFrom(this.targetMesh.getAbsolutePosition());
  78460. }
  78461. if (this.poleTargetBone) {
  78462. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  78463. }
  78464. else if (this.poleTargetMesh) {
  78465. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  78466. }
  78467. var bonePos = BoneIKController._tmpVecs[0];
  78468. var zaxis = BoneIKController._tmpVecs[1];
  78469. var xaxis = BoneIKController._tmpVecs[2];
  78470. var yaxis = BoneIKController._tmpVecs[3];
  78471. var upAxis = BoneIKController._tmpVecs[4];
  78472. var _tmpQuat = BoneIKController._tmpQuat;
  78473. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  78474. poleTarget.subtractToRef(bonePos, upAxis);
  78475. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  78476. upAxis.y = 1;
  78477. }
  78478. else {
  78479. upAxis.normalize();
  78480. }
  78481. target.subtractToRef(bonePos, yaxis);
  78482. yaxis.normalize();
  78483. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  78484. zaxis.normalize();
  78485. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  78486. xaxis.normalize();
  78487. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  78488. var a = this._bone1Length;
  78489. var b = this._bone2Length;
  78490. var c = BABYLON.Vector3.Distance(bonePos, target);
  78491. if (this._maxReach > 0) {
  78492. c = Math.min(this._maxReach, c);
  78493. }
  78494. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  78495. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  78496. if (acosa > 1) {
  78497. acosa = 1;
  78498. }
  78499. if (acosb > 1) {
  78500. acosb = 1;
  78501. }
  78502. if (acosa < -1) {
  78503. acosa = -1;
  78504. }
  78505. if (acosb < -1) {
  78506. acosb = -1;
  78507. }
  78508. var angA = Math.acos(acosa);
  78509. var angB = Math.acos(acosb);
  78510. var angC = -angA - angB;
  78511. if (this._rightHandedSystem) {
  78512. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  78513. mat2.multiplyToRef(mat1, mat1);
  78514. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  78515. mat2.multiplyToRef(mat1, mat1);
  78516. }
  78517. else {
  78518. var _tmpVec = BoneIKController._tmpVecs[5];
  78519. _tmpVec.copyFrom(this._bendAxis);
  78520. _tmpVec.x *= -1;
  78521. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  78522. mat2.multiplyToRef(mat1, mat1);
  78523. }
  78524. if (this.poleAngle) {
  78525. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  78526. mat1.multiplyToRef(mat2, mat1);
  78527. }
  78528. if (this._bone1) {
  78529. if (this.slerpAmount < 1) {
  78530. if (!this._slerping) {
  78531. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  78532. }
  78533. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  78534. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  78535. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  78536. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  78537. this._slerping = true;
  78538. }
  78539. else {
  78540. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  78541. this._bone1Mat.copyFrom(mat1);
  78542. this._slerping = false;
  78543. }
  78544. }
  78545. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  78546. this._bone2Ang = angC;
  78547. };
  78548. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78549. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  78550. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78551. return BoneIKController;
  78552. }());
  78553. BABYLON.BoneIKController = BoneIKController;
  78554. })(BABYLON || (BABYLON = {}));
  78555. //# sourceMappingURL=babylon.boneIKController.js.map
  78556. var BABYLON;
  78557. (function (BABYLON) {
  78558. /**
  78559. * Class used to make a bone look toward a point in space
  78560. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  78561. */
  78562. var BoneLookController = /** @class */ (function () {
  78563. /**
  78564. * Create a BoneLookController
  78565. * @param mesh the mesh that the bone belongs to
  78566. * @param bone the bone that will be looking to the target
  78567. * @param target the target Vector3 to look at
  78568. * @param settings optional settings:
  78569. * * maxYaw: the maximum angle the bone will yaw to
  78570. * * minYaw: the minimum angle the bone will yaw to
  78571. * * maxPitch: the maximum angle the bone will pitch to
  78572. * * minPitch: the minimum angle the bone will yaw to
  78573. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  78574. * * upAxis: the up axis of the coordinate system
  78575. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  78576. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  78577. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  78578. * * adjustYaw: used to make an adjustment to the yaw of the bone
  78579. * * adjustPitch: used to make an adjustment to the pitch of the bone
  78580. * * adjustRoll: used to make an adjustment to the roll of the bone
  78581. **/
  78582. function BoneLookController(mesh, bone, target, options) {
  78583. /**
  78584. * The up axis of the coordinate system that is used when the bone is rotated
  78585. */
  78586. this.upAxis = BABYLON.Vector3.Up();
  78587. /**
  78588. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  78589. */
  78590. this.upAxisSpace = BABYLON.Space.LOCAL;
  78591. /**
  78592. * Used to make an adjustment to the yaw of the bone
  78593. */
  78594. this.adjustYaw = 0;
  78595. /**
  78596. * Used to make an adjustment to the pitch of the bone
  78597. */
  78598. this.adjustPitch = 0;
  78599. /**
  78600. * Used to make an adjustment to the roll of the bone
  78601. */
  78602. this.adjustRoll = 0;
  78603. /**
  78604. * 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)
  78605. */
  78606. this.slerpAmount = 1;
  78607. this._boneQuat = BABYLON.Quaternion.Identity();
  78608. this._slerping = false;
  78609. this._firstFrameSkipped = false;
  78610. this._fowardAxis = BABYLON.Vector3.Forward();
  78611. this.mesh = mesh;
  78612. this.bone = bone;
  78613. this.target = target;
  78614. if (options) {
  78615. if (options.adjustYaw) {
  78616. this.adjustYaw = options.adjustYaw;
  78617. }
  78618. if (options.adjustPitch) {
  78619. this.adjustPitch = options.adjustPitch;
  78620. }
  78621. if (options.adjustRoll) {
  78622. this.adjustRoll = options.adjustRoll;
  78623. }
  78624. if (options.maxYaw != null) {
  78625. this.maxYaw = options.maxYaw;
  78626. }
  78627. else {
  78628. this.maxYaw = Math.PI;
  78629. }
  78630. if (options.minYaw != null) {
  78631. this.minYaw = options.minYaw;
  78632. }
  78633. else {
  78634. this.minYaw = -Math.PI;
  78635. }
  78636. if (options.maxPitch != null) {
  78637. this.maxPitch = options.maxPitch;
  78638. }
  78639. else {
  78640. this.maxPitch = Math.PI;
  78641. }
  78642. if (options.minPitch != null) {
  78643. this.minPitch = options.minPitch;
  78644. }
  78645. else {
  78646. this.minPitch = -Math.PI;
  78647. }
  78648. if (options.slerpAmount != null) {
  78649. this.slerpAmount = options.slerpAmount;
  78650. }
  78651. if (options.upAxis != null) {
  78652. this.upAxis = options.upAxis;
  78653. }
  78654. if (options.upAxisSpace != null) {
  78655. this.upAxisSpace = options.upAxisSpace;
  78656. }
  78657. if (options.yawAxis != null || options.pitchAxis != null) {
  78658. var newYawAxis = BABYLON.Axis.Y;
  78659. var newPitchAxis = BABYLON.Axis.X;
  78660. if (options.yawAxis != null) {
  78661. newYawAxis = options.yawAxis.clone();
  78662. newYawAxis.normalize();
  78663. }
  78664. if (options.pitchAxis != null) {
  78665. newPitchAxis = options.pitchAxis.clone();
  78666. newPitchAxis.normalize();
  78667. }
  78668. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  78669. this._transformYawPitch = BABYLON.Matrix.Identity();
  78670. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  78671. this._transformYawPitchInv = this._transformYawPitch.clone();
  78672. this._transformYawPitch.invert();
  78673. }
  78674. }
  78675. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  78676. this.upAxisSpace = BABYLON.Space.LOCAL;
  78677. }
  78678. }
  78679. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  78680. /**
  78681. * Gets or sets the minimum yaw angle that the bone can look to
  78682. */
  78683. get: function () {
  78684. return this._minYaw;
  78685. },
  78686. set: function (value) {
  78687. this._minYaw = value;
  78688. this._minYawSin = Math.sin(value);
  78689. this._minYawCos = Math.cos(value);
  78690. if (this._maxYaw != null) {
  78691. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78692. this._yawRange = this._maxYaw - this._minYaw;
  78693. }
  78694. },
  78695. enumerable: true,
  78696. configurable: true
  78697. });
  78698. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  78699. /**
  78700. * Gets or sets the maximum yaw angle that the bone can look to
  78701. */
  78702. get: function () {
  78703. return this._maxYaw;
  78704. },
  78705. set: function (value) {
  78706. this._maxYaw = value;
  78707. this._maxYawSin = Math.sin(value);
  78708. this._maxYawCos = Math.cos(value);
  78709. if (this._minYaw != null) {
  78710. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78711. this._yawRange = this._maxYaw - this._minYaw;
  78712. }
  78713. },
  78714. enumerable: true,
  78715. configurable: true
  78716. });
  78717. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  78718. /**
  78719. * Gets or sets the minimum pitch angle that the bone can look to
  78720. */
  78721. get: function () {
  78722. return this._minPitch;
  78723. },
  78724. set: function (value) {
  78725. this._minPitch = value;
  78726. this._minPitchTan = Math.tan(value);
  78727. },
  78728. enumerable: true,
  78729. configurable: true
  78730. });
  78731. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  78732. /**
  78733. * Gets or sets the maximum pitch angle that the bone can look to
  78734. */
  78735. get: function () {
  78736. return this._maxPitch;
  78737. },
  78738. set: function (value) {
  78739. this._maxPitch = value;
  78740. this._maxPitchTan = Math.tan(value);
  78741. },
  78742. enumerable: true,
  78743. configurable: true
  78744. });
  78745. /**
  78746. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  78747. */
  78748. BoneLookController.prototype.update = function () {
  78749. //skip the first frame when slerping so that the mesh rotation is correct
  78750. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  78751. this._firstFrameSkipped = true;
  78752. return;
  78753. }
  78754. var bone = this.bone;
  78755. var bonePos = BoneLookController._tmpVecs[0];
  78756. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  78757. var target = this.target;
  78758. var _tmpMat1 = BoneLookController._tmpMats[0];
  78759. var _tmpMat2 = BoneLookController._tmpMats[1];
  78760. var mesh = this.mesh;
  78761. var parentBone = bone.getParent();
  78762. var upAxis = BoneLookController._tmpVecs[1];
  78763. upAxis.copyFrom(this.upAxis);
  78764. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  78765. if (this._transformYawPitch) {
  78766. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  78767. }
  78768. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  78769. }
  78770. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  78771. mesh.getDirectionToRef(upAxis, upAxis);
  78772. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  78773. upAxis.normalize();
  78774. }
  78775. }
  78776. var checkYaw = false;
  78777. var checkPitch = false;
  78778. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  78779. checkYaw = true;
  78780. }
  78781. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  78782. checkPitch = true;
  78783. }
  78784. if (checkYaw || checkPitch) {
  78785. var spaceMat = BoneLookController._tmpMats[2];
  78786. var spaceMatInv = BoneLookController._tmpMats[3];
  78787. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  78788. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  78789. }
  78790. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  78791. spaceMat.copyFrom(mesh.getWorldMatrix());
  78792. }
  78793. else {
  78794. var forwardAxis = BoneLookController._tmpVecs[2];
  78795. forwardAxis.copyFrom(this._fowardAxis);
  78796. if (this._transformYawPitch) {
  78797. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  78798. }
  78799. if (parentBone) {
  78800. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  78801. }
  78802. else {
  78803. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  78804. }
  78805. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  78806. rightAxis.normalize();
  78807. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  78808. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  78809. }
  78810. spaceMat.invertToRef(spaceMatInv);
  78811. var xzlen = null;
  78812. if (checkPitch) {
  78813. var localTarget = BoneLookController._tmpVecs[3];
  78814. target.subtractToRef(bonePos, localTarget);
  78815. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78816. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78817. var pitch = Math.atan2(localTarget.y, xzlen);
  78818. var newPitch = pitch;
  78819. if (pitch > this._maxPitch) {
  78820. localTarget.y = this._maxPitchTan * xzlen;
  78821. newPitch = this._maxPitch;
  78822. }
  78823. else if (pitch < this._minPitch) {
  78824. localTarget.y = this._minPitchTan * xzlen;
  78825. newPitch = this._minPitch;
  78826. }
  78827. if (pitch != newPitch) {
  78828. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78829. localTarget.addInPlace(bonePos);
  78830. target = localTarget;
  78831. }
  78832. }
  78833. if (checkYaw) {
  78834. var localTarget = BoneLookController._tmpVecs[4];
  78835. target.subtractToRef(bonePos, localTarget);
  78836. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78837. var yaw = Math.atan2(localTarget.x, localTarget.z);
  78838. var newYaw = yaw;
  78839. if (yaw > this._maxYaw || yaw < this._minYaw) {
  78840. if (xzlen == null) {
  78841. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78842. }
  78843. if (this._yawRange > Math.PI) {
  78844. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  78845. localTarget.z = this._maxYawCos * xzlen;
  78846. localTarget.x = this._maxYawSin * xzlen;
  78847. newYaw = this._maxYaw;
  78848. }
  78849. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  78850. localTarget.z = this._minYawCos * xzlen;
  78851. localTarget.x = this._minYawSin * xzlen;
  78852. newYaw = this._minYaw;
  78853. }
  78854. }
  78855. else {
  78856. if (yaw > this._maxYaw) {
  78857. localTarget.z = this._maxYawCos * xzlen;
  78858. localTarget.x = this._maxYawSin * xzlen;
  78859. newYaw = this._maxYaw;
  78860. }
  78861. else if (yaw < this._minYaw) {
  78862. localTarget.z = this._minYawCos * xzlen;
  78863. localTarget.x = this._minYawSin * xzlen;
  78864. newYaw = this._minYaw;
  78865. }
  78866. }
  78867. }
  78868. if (this._slerping && this._yawRange > Math.PI) {
  78869. //are we going to be crossing into the min/max region?
  78870. var boneFwd = BoneLookController._tmpVecs[8];
  78871. boneFwd.copyFrom(BABYLON.Axis.Z);
  78872. if (this._transformYawPitch) {
  78873. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  78874. }
  78875. var boneRotMat = BoneLookController._tmpMats[4];
  78876. this._boneQuat.toRotationMatrix(boneRotMat);
  78877. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  78878. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  78879. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  78880. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  78881. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  78882. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  78883. if (angBtwTar > angBtwMidYaw) {
  78884. if (xzlen == null) {
  78885. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78886. }
  78887. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  78888. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  78889. if (angBtwMin < angBtwMax) {
  78890. newYaw = boneYaw + Math.PI * .75;
  78891. localTarget.z = Math.cos(newYaw) * xzlen;
  78892. localTarget.x = Math.sin(newYaw) * xzlen;
  78893. }
  78894. else {
  78895. newYaw = boneYaw - Math.PI * .75;
  78896. localTarget.z = Math.cos(newYaw) * xzlen;
  78897. localTarget.x = Math.sin(newYaw) * xzlen;
  78898. }
  78899. }
  78900. }
  78901. if (yaw != newYaw) {
  78902. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78903. localTarget.addInPlace(bonePos);
  78904. target = localTarget;
  78905. }
  78906. }
  78907. }
  78908. var zaxis = BoneLookController._tmpVecs[5];
  78909. var xaxis = BoneLookController._tmpVecs[6];
  78910. var yaxis = BoneLookController._tmpVecs[7];
  78911. var _tmpQuat = BoneLookController._tmpQuat;
  78912. target.subtractToRef(bonePos, zaxis);
  78913. zaxis.normalize();
  78914. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  78915. xaxis.normalize();
  78916. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  78917. yaxis.normalize();
  78918. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  78919. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  78920. return;
  78921. }
  78922. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  78923. return;
  78924. }
  78925. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  78926. return;
  78927. }
  78928. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  78929. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  78930. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  78931. }
  78932. if (this.slerpAmount < 1) {
  78933. if (!this._slerping) {
  78934. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  78935. }
  78936. if (this._transformYawPitch) {
  78937. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  78938. }
  78939. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  78940. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  78941. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  78942. this._slerping = true;
  78943. }
  78944. else {
  78945. if (this._transformYawPitch) {
  78946. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  78947. }
  78948. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  78949. this._slerping = false;
  78950. }
  78951. };
  78952. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  78953. var angDiff = ang2 - ang1;
  78954. angDiff %= Math.PI * 2;
  78955. if (angDiff > Math.PI) {
  78956. angDiff -= Math.PI * 2;
  78957. }
  78958. else if (angDiff < -Math.PI) {
  78959. angDiff += Math.PI * 2;
  78960. }
  78961. return angDiff;
  78962. };
  78963. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  78964. ang1 %= (2 * Math.PI);
  78965. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  78966. ang2 %= (2 * Math.PI);
  78967. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  78968. var ab = 0;
  78969. if (ang1 < ang2) {
  78970. ab = ang2 - ang1;
  78971. }
  78972. else {
  78973. ab = ang1 - ang2;
  78974. }
  78975. if (ab > Math.PI) {
  78976. ab = Math.PI * 2 - ab;
  78977. }
  78978. return ab;
  78979. };
  78980. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  78981. ang %= (2 * Math.PI);
  78982. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  78983. ang1 %= (2 * Math.PI);
  78984. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  78985. ang2 %= (2 * Math.PI);
  78986. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  78987. if (ang1 < ang2) {
  78988. if (ang > ang1 && ang < ang2) {
  78989. return true;
  78990. }
  78991. }
  78992. else {
  78993. if (ang > ang2 && ang < ang1) {
  78994. return true;
  78995. }
  78996. }
  78997. return false;
  78998. };
  78999. 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()];
  79000. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  79001. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79002. return BoneLookController;
  79003. }());
  79004. BABYLON.BoneLookController = BoneLookController;
  79005. })(BABYLON || (BABYLON = {}));
  79006. //# sourceMappingURL=babylon.boneLookController.js.map
  79007. var BABYLON;
  79008. (function (BABYLON) {
  79009. /**
  79010. * Class used to handle skinning animations
  79011. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79012. */
  79013. var Skeleton = /** @class */ (function () {
  79014. /**
  79015. * Creates a new skeleton
  79016. * @param name defines the skeleton name
  79017. * @param id defines the skeleton Id
  79018. * @param scene defines the hosting scene
  79019. */
  79020. function Skeleton(
  79021. /** defines the skeleton name */
  79022. name,
  79023. /** defines the skeleton Id */
  79024. id, scene) {
  79025. this.name = name;
  79026. this.id = id;
  79027. /**
  79028. * Gets the list of child bones
  79029. */
  79030. this.bones = new Array();
  79031. /**
  79032. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  79033. */
  79034. this.needInitialSkinMatrix = false;
  79035. this._isDirty = true;
  79036. this._meshesWithPoseMatrix = new Array();
  79037. this._identity = BABYLON.Matrix.Identity();
  79038. this._ranges = {};
  79039. this._lastAbsoluteTransformsUpdateId = -1;
  79040. /**
  79041. * Specifies if the skeleton should be serialized
  79042. */
  79043. this.doNotSerialize = false;
  79044. this._animationPropertiesOverride = null;
  79045. // Events
  79046. /**
  79047. * An observable triggered before computing the skeleton's matrices
  79048. */
  79049. this.onBeforeComputeObservable = new BABYLON.Observable();
  79050. this.bones = [];
  79051. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79052. scene.skeletons.push(this);
  79053. //make sure it will recalculate the matrix next time prepare is called.
  79054. this._isDirty = true;
  79055. }
  79056. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  79057. /**
  79058. * Gets or sets the animation properties override
  79059. */
  79060. get: function () {
  79061. if (!this._animationPropertiesOverride) {
  79062. return this._scene.animationPropertiesOverride;
  79063. }
  79064. return this._animationPropertiesOverride;
  79065. },
  79066. set: function (value) {
  79067. this._animationPropertiesOverride = value;
  79068. },
  79069. enumerable: true,
  79070. configurable: true
  79071. });
  79072. // Members
  79073. /**
  79074. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  79075. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  79076. * @returns a Float32Array containing matrices data
  79077. */
  79078. Skeleton.prototype.getTransformMatrices = function (mesh) {
  79079. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  79080. return mesh._bonesTransformMatrices;
  79081. }
  79082. if (!this._transformMatrices) {
  79083. this.prepare();
  79084. }
  79085. return this._transformMatrices;
  79086. };
  79087. /**
  79088. * Gets the current hosting scene
  79089. * @returns a scene object
  79090. */
  79091. Skeleton.prototype.getScene = function () {
  79092. return this._scene;
  79093. };
  79094. // Methods
  79095. /**
  79096. * Gets a string representing the current skeleton data
  79097. * @param fullDetails defines a boolean indicating if we want a verbose version
  79098. * @returns a string representing the current skeleton data
  79099. */
  79100. Skeleton.prototype.toString = function (fullDetails) {
  79101. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  79102. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  79103. if (fullDetails) {
  79104. ret += ", Ranges: {";
  79105. var first = true;
  79106. for (var name_1 in this._ranges) {
  79107. if (first) {
  79108. ret += ", ";
  79109. first = false;
  79110. }
  79111. ret += name_1;
  79112. }
  79113. ret += "}";
  79114. }
  79115. return ret;
  79116. };
  79117. /**
  79118. * Get bone's index searching by name
  79119. * @param name defines bone's name to search for
  79120. * @return the indice of the bone. Returns -1 if not found
  79121. */
  79122. Skeleton.prototype.getBoneIndexByName = function (name) {
  79123. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  79124. if (this.bones[boneIndex].name === name) {
  79125. return boneIndex;
  79126. }
  79127. }
  79128. return -1;
  79129. };
  79130. /**
  79131. * Creater a new animation range
  79132. * @param name defines the name of the range
  79133. * @param from defines the start key
  79134. * @param to defines the end key
  79135. */
  79136. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  79137. // check name not already in use
  79138. if (!this._ranges[name]) {
  79139. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  79140. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79141. if (this.bones[i].animations[0]) {
  79142. this.bones[i].animations[0].createRange(name, from, to);
  79143. }
  79144. }
  79145. }
  79146. };
  79147. /**
  79148. * Delete a specific animation range
  79149. * @param name defines the name of the range
  79150. * @param deleteFrames defines if frames must be removed as well
  79151. */
  79152. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  79153. if (deleteFrames === void 0) { deleteFrames = true; }
  79154. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79155. if (this.bones[i].animations[0]) {
  79156. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  79157. }
  79158. }
  79159. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  79160. };
  79161. /**
  79162. * Gets a specific animation range
  79163. * @param name defines the name of the range to look for
  79164. * @returns the requested animation range or null if not found
  79165. */
  79166. Skeleton.prototype.getAnimationRange = function (name) {
  79167. return this._ranges[name];
  79168. };
  79169. /**
  79170. * Gets the list of all animation ranges defined on this skeleton
  79171. * @returns an array
  79172. */
  79173. Skeleton.prototype.getAnimationRanges = function () {
  79174. var animationRanges = [];
  79175. var name;
  79176. var i = 0;
  79177. for (name in this._ranges) {
  79178. animationRanges[i] = this._ranges[name];
  79179. i++;
  79180. }
  79181. return animationRanges;
  79182. };
  79183. /**
  79184. * Copy animation range from a source skeleton.
  79185. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  79186. * @param source defines the source skeleton
  79187. * @param name defines the name of the range to copy
  79188. * @param rescaleAsRequired defines if rescaling must be applied if required
  79189. * @returns true if operation was successful
  79190. */
  79191. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  79192. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79193. if (this._ranges[name] || !source.getAnimationRange(name)) {
  79194. return false;
  79195. }
  79196. var ret = true;
  79197. var frameOffset = this._getHighestAnimationFrame() + 1;
  79198. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  79199. var boneDict = {};
  79200. var sourceBones = source.bones;
  79201. var nBones;
  79202. var i;
  79203. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  79204. boneDict[sourceBones[i].name] = sourceBones[i];
  79205. }
  79206. if (this.bones.length !== sourceBones.length) {
  79207. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  79208. ret = false;
  79209. }
  79210. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  79211. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  79212. var boneName = this.bones[i].name;
  79213. var sourceBone = boneDict[boneName];
  79214. if (sourceBone) {
  79215. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  79216. }
  79217. else {
  79218. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  79219. ret = false;
  79220. }
  79221. }
  79222. // do not call createAnimationRange(), since it also is done to bones, which was already done
  79223. var range = source.getAnimationRange(name);
  79224. if (range) {
  79225. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  79226. }
  79227. return ret;
  79228. };
  79229. /**
  79230. * Forces the skeleton to go to rest pose
  79231. */
  79232. Skeleton.prototype.returnToRest = function () {
  79233. for (var index = 0; index < this.bones.length; index++) {
  79234. this.bones[index].returnToRest();
  79235. }
  79236. };
  79237. Skeleton.prototype._getHighestAnimationFrame = function () {
  79238. var ret = 0;
  79239. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79240. if (this.bones[i].animations[0]) {
  79241. var highest = this.bones[i].animations[0].getHighestFrame();
  79242. if (ret < highest) {
  79243. ret = highest;
  79244. }
  79245. }
  79246. }
  79247. return ret;
  79248. };
  79249. /**
  79250. * Begin a specific animation range
  79251. * @param name defines the name of the range to start
  79252. * @param loop defines if looping must be turned on (false by default)
  79253. * @param speedRatio defines the speed ratio to apply (1 by default)
  79254. * @param onAnimationEnd defines a callback which will be called when animation will end
  79255. * @returns a new animatable
  79256. */
  79257. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  79258. var range = this.getAnimationRange(name);
  79259. if (!range) {
  79260. return null;
  79261. }
  79262. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  79263. };
  79264. /** @hidden */
  79265. Skeleton.prototype._markAsDirty = function () {
  79266. this._isDirty = true;
  79267. };
  79268. /** @hidden */
  79269. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  79270. this._meshesWithPoseMatrix.push(mesh);
  79271. };
  79272. /** @hidden */
  79273. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  79274. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  79275. if (index > -1) {
  79276. this._meshesWithPoseMatrix.splice(index, 1);
  79277. }
  79278. };
  79279. /** @hidden */
  79280. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  79281. this.onBeforeComputeObservable.notifyObservers(this);
  79282. for (var index = 0; index < this.bones.length; index++) {
  79283. var bone = this.bones[index];
  79284. var parentBone = bone.getParent();
  79285. if (parentBone) {
  79286. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  79287. }
  79288. else {
  79289. if (initialSkinMatrix) {
  79290. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  79291. }
  79292. else {
  79293. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  79294. }
  79295. }
  79296. if (bone._index !== -1) {
  79297. var mappedIndex = bone._index === null ? index : bone._index;
  79298. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  79299. }
  79300. }
  79301. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  79302. };
  79303. /**
  79304. * Build all resources required to render a skeleton
  79305. */
  79306. Skeleton.prototype.prepare = function () {
  79307. if (!this._isDirty) {
  79308. return;
  79309. }
  79310. if (this.needInitialSkinMatrix) {
  79311. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  79312. var mesh = this._meshesWithPoseMatrix[index];
  79313. var poseMatrix = mesh.getPoseMatrix();
  79314. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  79315. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79316. }
  79317. if (this._synchronizedWithMesh !== mesh) {
  79318. this._synchronizedWithMesh = mesh;
  79319. // Prepare bones
  79320. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  79321. var bone = this.bones[boneIndex];
  79322. if (!bone.getParent()) {
  79323. var matrix = bone.getBaseMatrix();
  79324. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  79325. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  79326. }
  79327. }
  79328. }
  79329. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  79330. }
  79331. }
  79332. else {
  79333. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  79334. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79335. }
  79336. this._computeTransformMatrices(this._transformMatrices, null);
  79337. }
  79338. this._isDirty = false;
  79339. this._scene._activeBones.addCount(this.bones.length, false);
  79340. };
  79341. /**
  79342. * Gets the list of animatables currently running for this skeleton
  79343. * @returns an array of animatables
  79344. */
  79345. Skeleton.prototype.getAnimatables = function () {
  79346. if (!this._animatables || this._animatables.length !== this.bones.length) {
  79347. this._animatables = [];
  79348. for (var index = 0; index < this.bones.length; index++) {
  79349. this._animatables.push(this.bones[index]);
  79350. }
  79351. }
  79352. return this._animatables;
  79353. };
  79354. /**
  79355. * Clone the current skeleton
  79356. * @param name defines the name of the new skeleton
  79357. * @param id defines the id of the enw skeleton
  79358. * @returns the new skeleton
  79359. */
  79360. Skeleton.prototype.clone = function (name, id) {
  79361. var result = new Skeleton(name, id || name, this._scene);
  79362. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79363. for (var index = 0; index < this.bones.length; index++) {
  79364. var source = this.bones[index];
  79365. var parentBone = null;
  79366. var parent_1 = source.getParent();
  79367. if (parent_1) {
  79368. var parentIndex = this.bones.indexOf(parent_1);
  79369. parentBone = result.bones[parentIndex];
  79370. }
  79371. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  79372. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  79373. }
  79374. if (this._ranges) {
  79375. result._ranges = {};
  79376. for (var rangeName in this._ranges) {
  79377. var range = this._ranges[rangeName];
  79378. if (range) {
  79379. result._ranges[rangeName] = range.clone();
  79380. }
  79381. }
  79382. }
  79383. this._isDirty = true;
  79384. return result;
  79385. };
  79386. /**
  79387. * Enable animation blending for this skeleton
  79388. * @param blendingSpeed defines the blending speed to apply
  79389. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  79390. */
  79391. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  79392. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  79393. this.bones.forEach(function (bone) {
  79394. bone.animations.forEach(function (animation) {
  79395. animation.enableBlending = true;
  79396. animation.blendingSpeed = blendingSpeed;
  79397. });
  79398. });
  79399. };
  79400. /**
  79401. * Releases all resources associated with the current skeleton
  79402. */
  79403. Skeleton.prototype.dispose = function () {
  79404. this._meshesWithPoseMatrix = [];
  79405. // Animations
  79406. this.getScene().stopAnimation(this);
  79407. // Remove from scene
  79408. this.getScene().removeSkeleton(this);
  79409. };
  79410. /**
  79411. * Serialize the skeleton in a JSON object
  79412. * @returns a JSON object
  79413. */
  79414. Skeleton.prototype.serialize = function () {
  79415. var serializationObject = {};
  79416. serializationObject.name = this.name;
  79417. serializationObject.id = this.id;
  79418. if (this.dimensionsAtRest) {
  79419. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  79420. }
  79421. serializationObject.bones = [];
  79422. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79423. for (var index = 0; index < this.bones.length; index++) {
  79424. var bone = this.bones[index];
  79425. var parent_2 = bone.getParent();
  79426. var serializedBone = {
  79427. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  79428. name: bone.name,
  79429. matrix: bone.getBaseMatrix().toArray(),
  79430. rest: bone.getRestPose().toArray()
  79431. };
  79432. serializationObject.bones.push(serializedBone);
  79433. if (bone.length) {
  79434. serializedBone.length = bone.length;
  79435. }
  79436. if (bone.animations && bone.animations.length > 0) {
  79437. serializedBone.animation = bone.animations[0].serialize();
  79438. }
  79439. serializationObject.ranges = [];
  79440. for (var name in this._ranges) {
  79441. var source = this._ranges[name];
  79442. if (!source) {
  79443. continue;
  79444. }
  79445. var range = {};
  79446. range.name = name;
  79447. range.from = source.from;
  79448. range.to = source.to;
  79449. serializationObject.ranges.push(range);
  79450. }
  79451. }
  79452. return serializationObject;
  79453. };
  79454. /**
  79455. * Creates a new skeleton from serialized data
  79456. * @param parsedSkeleton defines the serialized data
  79457. * @param scene defines the hosting scene
  79458. * @returns a new skeleton
  79459. */
  79460. Skeleton.Parse = function (parsedSkeleton, scene) {
  79461. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  79462. if (parsedSkeleton.dimensionsAtRest) {
  79463. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  79464. }
  79465. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  79466. var index;
  79467. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  79468. var parsedBone = parsedSkeleton.bones[index];
  79469. var parentBone = null;
  79470. if (parsedBone.parentBoneIndex > -1) {
  79471. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  79472. }
  79473. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  79474. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  79475. if (parsedBone.length) {
  79476. bone.length = parsedBone.length;
  79477. }
  79478. if (parsedBone.animation) {
  79479. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  79480. }
  79481. }
  79482. // placed after bones, so createAnimationRange can cascade down
  79483. if (parsedSkeleton.ranges) {
  79484. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  79485. var data = parsedSkeleton.ranges[index];
  79486. skeleton.createAnimationRange(data.name, data.from, data.to);
  79487. }
  79488. }
  79489. return skeleton;
  79490. };
  79491. /**
  79492. * Compute all node absolute transforms
  79493. * @param forceUpdate defines if computation must be done even if cache is up to date
  79494. */
  79495. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  79496. if (forceUpdate === void 0) { forceUpdate = false; }
  79497. var renderId = this._scene.getRenderId();
  79498. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  79499. this.bones[0].computeAbsoluteTransforms();
  79500. this._lastAbsoluteTransformsUpdateId = renderId;
  79501. }
  79502. };
  79503. /**
  79504. * Gets the root pose matrix
  79505. * @returns a matrix
  79506. */
  79507. Skeleton.prototype.getPoseMatrix = function () {
  79508. var poseMatrix = null;
  79509. if (this._meshesWithPoseMatrix.length > 0) {
  79510. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  79511. }
  79512. return poseMatrix;
  79513. };
  79514. /**
  79515. * Sorts bones per internal index
  79516. */
  79517. Skeleton.prototype.sortBones = function () {
  79518. var bones = new Array();
  79519. var visited = new Array(this.bones.length);
  79520. for (var index = 0; index < this.bones.length; index++) {
  79521. this._sortBones(index, bones, visited);
  79522. }
  79523. this.bones = bones;
  79524. };
  79525. Skeleton.prototype._sortBones = function (index, bones, visited) {
  79526. if (visited[index]) {
  79527. return;
  79528. }
  79529. visited[index] = true;
  79530. var bone = this.bones[index];
  79531. if (bone._index === undefined) {
  79532. bone._index = index;
  79533. }
  79534. var parentBone = bone.getParent();
  79535. if (parentBone) {
  79536. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  79537. }
  79538. bones.push(bone);
  79539. };
  79540. return Skeleton;
  79541. }());
  79542. BABYLON.Skeleton = Skeleton;
  79543. })(BABYLON || (BABYLON = {}));
  79544. //# sourceMappingURL=babylon.skeleton.js.map
  79545. var BABYLON;
  79546. (function (BABYLON) {
  79547. var SphericalPolynomial = /** @class */ (function () {
  79548. function SphericalPolynomial() {
  79549. this.x = BABYLON.Vector3.Zero();
  79550. this.y = BABYLON.Vector3.Zero();
  79551. this.z = BABYLON.Vector3.Zero();
  79552. this.xx = BABYLON.Vector3.Zero();
  79553. this.yy = BABYLON.Vector3.Zero();
  79554. this.zz = BABYLON.Vector3.Zero();
  79555. this.xy = BABYLON.Vector3.Zero();
  79556. this.yz = BABYLON.Vector3.Zero();
  79557. this.zx = BABYLON.Vector3.Zero();
  79558. }
  79559. SphericalPolynomial.prototype.addAmbient = function (color) {
  79560. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79561. this.xx = this.xx.add(colorVector);
  79562. this.yy = this.yy.add(colorVector);
  79563. this.zz = this.zz.add(colorVector);
  79564. };
  79565. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  79566. var result = new SphericalPolynomial();
  79567. result.x = harmonics.L11.scale(1.02333);
  79568. result.y = harmonics.L1_1.scale(1.02333);
  79569. result.z = harmonics.L10.scale(1.02333);
  79570. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  79571. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  79572. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  79573. result.yz = harmonics.L2_1.scale(0.858086);
  79574. result.zx = harmonics.L21.scale(0.858086);
  79575. result.xy = harmonics.L2_2.scale(0.858086);
  79576. result.scale(1.0 / Math.PI);
  79577. return result;
  79578. };
  79579. SphericalPolynomial.prototype.scale = function (scale) {
  79580. this.x = this.x.scale(scale);
  79581. this.y = this.y.scale(scale);
  79582. this.z = this.z.scale(scale);
  79583. this.xx = this.xx.scale(scale);
  79584. this.yy = this.yy.scale(scale);
  79585. this.zz = this.zz.scale(scale);
  79586. this.yz = this.yz.scale(scale);
  79587. this.zx = this.zx.scale(scale);
  79588. this.xy = this.xy.scale(scale);
  79589. };
  79590. return SphericalPolynomial;
  79591. }());
  79592. BABYLON.SphericalPolynomial = SphericalPolynomial;
  79593. var SphericalHarmonics = /** @class */ (function () {
  79594. function SphericalHarmonics() {
  79595. this.L00 = BABYLON.Vector3.Zero();
  79596. this.L1_1 = BABYLON.Vector3.Zero();
  79597. this.L10 = BABYLON.Vector3.Zero();
  79598. this.L11 = BABYLON.Vector3.Zero();
  79599. this.L2_2 = BABYLON.Vector3.Zero();
  79600. this.L2_1 = BABYLON.Vector3.Zero();
  79601. this.L20 = BABYLON.Vector3.Zero();
  79602. this.L21 = BABYLON.Vector3.Zero();
  79603. this.L22 = BABYLON.Vector3.Zero();
  79604. }
  79605. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  79606. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79607. var c = colorVector.scale(deltaSolidAngle);
  79608. this.L00 = this.L00.add(c.scale(0.282095));
  79609. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  79610. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  79611. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  79612. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  79613. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  79614. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  79615. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  79616. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  79617. };
  79618. SphericalHarmonics.prototype.scale = function (scale) {
  79619. this.L00 = this.L00.scale(scale);
  79620. this.L1_1 = this.L1_1.scale(scale);
  79621. this.L10 = this.L10.scale(scale);
  79622. this.L11 = this.L11.scale(scale);
  79623. this.L2_2 = this.L2_2.scale(scale);
  79624. this.L2_1 = this.L2_1.scale(scale);
  79625. this.L20 = this.L20.scale(scale);
  79626. this.L21 = this.L21.scale(scale);
  79627. this.L22 = this.L22.scale(scale);
  79628. };
  79629. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  79630. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  79631. //
  79632. // E_lm = A_l * L_lm
  79633. //
  79634. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  79635. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  79636. // the scaling factors are given in equation 9.
  79637. // Constant (Band 0)
  79638. this.L00 = this.L00.scale(3.141593);
  79639. // Linear (Band 1)
  79640. this.L1_1 = this.L1_1.scale(2.094395);
  79641. this.L10 = this.L10.scale(2.094395);
  79642. this.L11 = this.L11.scale(2.094395);
  79643. // Quadratic (Band 2)
  79644. this.L2_2 = this.L2_2.scale(0.785398);
  79645. this.L2_1 = this.L2_1.scale(0.785398);
  79646. this.L20 = this.L20.scale(0.785398);
  79647. this.L21 = this.L21.scale(0.785398);
  79648. this.L22 = this.L22.scale(0.785398);
  79649. };
  79650. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  79651. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  79652. // L = (1/pi) * E * rho
  79653. //
  79654. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  79655. this.scale(1.0 / Math.PI);
  79656. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  79657. // (The pixel shader must apply albedo after texture fetches, etc).
  79658. };
  79659. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  79660. var result = new SphericalHarmonics();
  79661. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  79662. result.L1_1 = polynomial.y.scale(0.977204);
  79663. result.L10 = polynomial.z.scale(0.977204);
  79664. result.L11 = polynomial.x.scale(0.977204);
  79665. result.L2_2 = polynomial.xy.scale(1.16538);
  79666. result.L2_1 = polynomial.yz.scale(1.16538);
  79667. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  79668. result.L21 = polynomial.zx.scale(1.16538);
  79669. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  79670. result.scale(Math.PI);
  79671. return result;
  79672. };
  79673. return SphericalHarmonics;
  79674. }());
  79675. BABYLON.SphericalHarmonics = SphericalHarmonics;
  79676. })(BABYLON || (BABYLON = {}));
  79677. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  79678. var BABYLON;
  79679. (function (BABYLON) {
  79680. var FileFaceOrientation = /** @class */ (function () {
  79681. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  79682. this.name = name;
  79683. this.worldAxisForNormal = worldAxisForNormal;
  79684. this.worldAxisForFileX = worldAxisForFileX;
  79685. this.worldAxisForFileY = worldAxisForFileY;
  79686. }
  79687. return FileFaceOrientation;
  79688. }());
  79689. ;
  79690. /**
  79691. * Helper class dealing with the extraction of spherical polynomial dataArray
  79692. * from a cube map.
  79693. */
  79694. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  79695. function CubeMapToSphericalPolynomialTools() {
  79696. }
  79697. /**
  79698. * Converts a texture to the according Spherical Polynomial data.
  79699. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79700. *
  79701. * @param texture The texture to extract the information from.
  79702. * @return The Spherical Polynomial data.
  79703. */
  79704. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  79705. if (!texture.isCube) {
  79706. // Only supports cube Textures currently.
  79707. return null;
  79708. }
  79709. var size = texture.getSize().width;
  79710. var right = texture.readPixels(0);
  79711. var left = texture.readPixels(1);
  79712. var up;
  79713. var down;
  79714. if (texture.isRenderTarget) {
  79715. up = texture.readPixels(3);
  79716. down = texture.readPixels(2);
  79717. }
  79718. else {
  79719. up = texture.readPixels(2);
  79720. down = texture.readPixels(3);
  79721. }
  79722. var front = texture.readPixels(4);
  79723. var back = texture.readPixels(5);
  79724. var gammaSpace = texture.gammaSpace;
  79725. // Always read as RGBA.
  79726. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  79727. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79728. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79729. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79730. }
  79731. var cubeInfo = {
  79732. size: size,
  79733. right: right,
  79734. left: left,
  79735. up: up,
  79736. down: down,
  79737. front: front,
  79738. back: back,
  79739. format: format,
  79740. type: type,
  79741. gammaSpace: gammaSpace,
  79742. };
  79743. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  79744. };
  79745. /**
  79746. * Converts a cubemap to the according Spherical Polynomial data.
  79747. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79748. *
  79749. * @param cubeInfo The Cube map to extract the information from.
  79750. * @return The Spherical Polynomial data.
  79751. */
  79752. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  79753. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  79754. var totalSolidAngle = 0.0;
  79755. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  79756. var du = 2.0 / cubeInfo.size;
  79757. var dv = du;
  79758. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  79759. var minUV = du * 0.5 - 1.0;
  79760. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  79761. var fileFace = this.FileFaces[faceIndex];
  79762. var dataArray = cubeInfo[fileFace.name];
  79763. var v = minUV;
  79764. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  79765. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  79766. // Because SP is still linear, so summation is fine in that basis.
  79767. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  79768. for (var y = 0; y < cubeInfo.size; y++) {
  79769. var u = minUV;
  79770. for (var x = 0; x < cubeInfo.size; x++) {
  79771. // World direction (not normalised)
  79772. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  79773. worldDirection.normalize();
  79774. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  79775. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  79776. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  79777. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  79778. // Handle Integer types.
  79779. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79780. r /= 255;
  79781. g /= 255;
  79782. b /= 255;
  79783. }
  79784. // Handle Gamma space textures.
  79785. if (cubeInfo.gammaSpace) {
  79786. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  79787. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  79788. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  79789. }
  79790. var color = new BABYLON.Color3(r, g, b);
  79791. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  79792. totalSolidAngle += deltaSolidAngle;
  79793. u += du;
  79794. }
  79795. v += dv;
  79796. }
  79797. }
  79798. // Solid angle for entire sphere is 4*pi
  79799. var sphereSolidAngle = 4.0 * Math.PI;
  79800. // Adjust the solid angle to allow for how many faces we processed.
  79801. var facesProcessed = 6.0;
  79802. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  79803. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  79804. // This is needed because the numerical integration over the cube uses a
  79805. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  79806. // and also to compensate for accumulative error due to float precision in the summation.
  79807. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  79808. sphericalHarmonics.scale(correctionFactor);
  79809. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  79810. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  79811. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  79812. };
  79813. CubeMapToSphericalPolynomialTools.FileFaces = [
  79814. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  79815. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  79816. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  79817. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  79818. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  79819. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  79820. ];
  79821. return CubeMapToSphericalPolynomialTools;
  79822. }());
  79823. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  79824. })(BABYLON || (BABYLON = {}));
  79825. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  79826. var BABYLON;
  79827. (function (BABYLON) {
  79828. /**
  79829. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  79830. */
  79831. var PanoramaToCubeMapTools = /** @class */ (function () {
  79832. function PanoramaToCubeMapTools() {
  79833. }
  79834. /**
  79835. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  79836. *
  79837. * @param float32Array The source data.
  79838. * @param inputWidth The width of the input panorama.
  79839. * @param inputhHeight The height of the input panorama.
  79840. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  79841. * @return The cubemap data
  79842. */
  79843. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  79844. if (!float32Array) {
  79845. throw "ConvertPanoramaToCubemap: input cannot be null";
  79846. }
  79847. if (float32Array.length != inputWidth * inputHeight * 3) {
  79848. throw "ConvertPanoramaToCubemap: input size is wrong";
  79849. }
  79850. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  79851. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  79852. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  79853. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  79854. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  79855. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  79856. return {
  79857. front: textureFront,
  79858. back: textureBack,
  79859. left: textureLeft,
  79860. right: textureRight,
  79861. up: textureUp,
  79862. down: textureDown,
  79863. size: size,
  79864. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  79865. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  79866. gammaSpace: false,
  79867. };
  79868. };
  79869. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  79870. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  79871. var textureArray = new Float32Array(buffer);
  79872. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  79873. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  79874. var dy = 1 / texSize;
  79875. var fy = 0;
  79876. for (var y = 0; y < texSize; y++) {
  79877. var xv1 = faceData[0];
  79878. var xv2 = faceData[2];
  79879. for (var x = 0; x < texSize; x++) {
  79880. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  79881. v.normalize();
  79882. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  79883. // 3 channels per pixels
  79884. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  79885. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  79886. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  79887. xv1 = xv1.add(rotDX1);
  79888. xv2 = xv2.add(rotDX2);
  79889. }
  79890. fy += dy;
  79891. }
  79892. return textureArray;
  79893. };
  79894. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  79895. var theta = Math.atan2(vDir.z, vDir.x);
  79896. var phi = Math.acos(vDir.y);
  79897. while (theta < -Math.PI)
  79898. theta += 2 * Math.PI;
  79899. while (theta > Math.PI)
  79900. theta -= 2 * Math.PI;
  79901. var dx = theta / Math.PI;
  79902. var dy = phi / Math.PI;
  79903. // recenter.
  79904. dx = dx * 0.5 + 0.5;
  79905. var px = Math.round(dx * inputWidth);
  79906. if (px < 0)
  79907. px = 0;
  79908. else if (px >= inputWidth)
  79909. px = inputWidth - 1;
  79910. var py = Math.round(dy * inputHeight);
  79911. if (py < 0)
  79912. py = 0;
  79913. else if (py >= inputHeight)
  79914. py = inputHeight - 1;
  79915. var inputY = (inputHeight - py - 1);
  79916. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  79917. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  79918. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  79919. return {
  79920. r: r,
  79921. g: g,
  79922. b: b
  79923. };
  79924. };
  79925. PanoramaToCubeMapTools.FACE_FRONT = [
  79926. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79927. new BABYLON.Vector3(1.0, -1.0, -1.0),
  79928. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  79929. new BABYLON.Vector3(1.0, 1.0, -1.0)
  79930. ];
  79931. PanoramaToCubeMapTools.FACE_BACK = [
  79932. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79933. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79934. new BABYLON.Vector3(1.0, 1.0, 1.0),
  79935. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  79936. ];
  79937. PanoramaToCubeMapTools.FACE_RIGHT = [
  79938. new BABYLON.Vector3(1.0, -1.0, -1.0),
  79939. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79940. new BABYLON.Vector3(1.0, 1.0, -1.0),
  79941. new BABYLON.Vector3(1.0, 1.0, 1.0)
  79942. ];
  79943. PanoramaToCubeMapTools.FACE_LEFT = [
  79944. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79945. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79946. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  79947. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  79948. ];
  79949. PanoramaToCubeMapTools.FACE_DOWN = [
  79950. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  79951. new BABYLON.Vector3(1.0, 1.0, -1.0),
  79952. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  79953. new BABYLON.Vector3(1.0, 1.0, 1.0)
  79954. ];
  79955. PanoramaToCubeMapTools.FACE_UP = [
  79956. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79957. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79958. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79959. new BABYLON.Vector3(1.0, -1.0, -1.0)
  79960. ];
  79961. return PanoramaToCubeMapTools;
  79962. }());
  79963. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  79964. })(BABYLON || (BABYLON = {}));
  79965. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  79966. var BABYLON;
  79967. (function (BABYLON) {
  79968. ;
  79969. /**
  79970. * This groups tools to convert HDR texture to native colors array.
  79971. */
  79972. var HDRTools = /** @class */ (function () {
  79973. function HDRTools() {
  79974. }
  79975. HDRTools.Ldexp = function (mantissa, exponent) {
  79976. if (exponent > 1023) {
  79977. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  79978. }
  79979. if (exponent < -1074) {
  79980. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  79981. }
  79982. return mantissa * Math.pow(2, exponent);
  79983. };
  79984. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  79985. if (exponent > 0) { /*nonzero pixel*/
  79986. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  79987. float32array[index + 0] = red * exponent;
  79988. float32array[index + 1] = green * exponent;
  79989. float32array[index + 2] = blue * exponent;
  79990. }
  79991. else {
  79992. float32array[index + 0] = 0;
  79993. float32array[index + 1] = 0;
  79994. float32array[index + 2] = 0;
  79995. }
  79996. };
  79997. HDRTools.readStringLine = function (uint8array, startIndex) {
  79998. var line = "";
  79999. var character = "";
  80000. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  80001. character = String.fromCharCode(uint8array[i]);
  80002. if (character == "\n") {
  80003. break;
  80004. }
  80005. line += character;
  80006. }
  80007. return line;
  80008. };
  80009. /**
  80010. * Reads header information from an RGBE texture stored in a native array.
  80011. * More information on this format are available here:
  80012. * https://en.wikipedia.org/wiki/RGBE_image_format
  80013. *
  80014. * @param uint8array The binary file stored in native array.
  80015. * @return The header information.
  80016. */
  80017. HDRTools.RGBE_ReadHeader = function (uint8array) {
  80018. var height = 0;
  80019. var width = 0;
  80020. var line = this.readStringLine(uint8array, 0);
  80021. if (line[0] != '#' || line[1] != '?') {
  80022. throw "Bad HDR Format.";
  80023. }
  80024. var endOfHeader = false;
  80025. var findFormat = false;
  80026. var lineIndex = 0;
  80027. do {
  80028. lineIndex += (line.length + 1);
  80029. line = this.readStringLine(uint8array, lineIndex);
  80030. if (line == "FORMAT=32-bit_rle_rgbe") {
  80031. findFormat = true;
  80032. }
  80033. else if (line.length == 0) {
  80034. endOfHeader = true;
  80035. }
  80036. } while (!endOfHeader);
  80037. if (!findFormat) {
  80038. throw "HDR Bad header format, unsupported FORMAT";
  80039. }
  80040. lineIndex += (line.length + 1);
  80041. line = this.readStringLine(uint8array, lineIndex);
  80042. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  80043. var match = sizeRegexp.exec(line);
  80044. // TODO. Support +Y and -X if needed.
  80045. if (!match || match.length < 3) {
  80046. throw "HDR Bad header format, no size";
  80047. }
  80048. width = parseInt(match[2]);
  80049. height = parseInt(match[1]);
  80050. if (width < 8 || width > 0x7fff) {
  80051. throw "HDR Bad header format, unsupported size";
  80052. }
  80053. lineIndex += (line.length + 1);
  80054. return {
  80055. height: height,
  80056. width: width,
  80057. dataPosition: lineIndex
  80058. };
  80059. };
  80060. /**
  80061. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  80062. * This RGBE texture needs to store the information as a panorama.
  80063. *
  80064. * More information on this format are available here:
  80065. * https://en.wikipedia.org/wiki/RGBE_image_format
  80066. *
  80067. * @param buffer The binary file stored in an array buffer.
  80068. * @param size The expected size of the extracted cubemap.
  80069. * @return The Cube Map information.
  80070. */
  80071. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  80072. var uint8array = new Uint8Array(buffer);
  80073. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  80074. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80075. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  80076. return cubeMapData;
  80077. };
  80078. /**
  80079. * Returns the pixels data extracted from an RGBE texture.
  80080. * This pixels will be stored left to right up to down in the R G B order in one array.
  80081. *
  80082. * More information on this format are available here:
  80083. * https://en.wikipedia.org/wiki/RGBE_image_format
  80084. *
  80085. * @param uint8array The binary file stored in an array buffer.
  80086. * @param hdrInfo The header information of the file.
  80087. * @return The pixels data in RGB right to left up to down order.
  80088. */
  80089. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  80090. // Keep for multi format supports.
  80091. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80092. };
  80093. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  80094. var num_scanlines = hdrInfo.height;
  80095. var scanline_width = hdrInfo.width;
  80096. var a, b, c, d, count;
  80097. var dataIndex = hdrInfo.dataPosition;
  80098. var index = 0, endIndex = 0, i = 0;
  80099. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  80100. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  80101. // 3 channels of 4 bytes per pixel in float.
  80102. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  80103. var resultArray = new Float32Array(resultBuffer);
  80104. // read in each successive scanline
  80105. while (num_scanlines > 0) {
  80106. a = uint8array[dataIndex++];
  80107. b = uint8array[dataIndex++];
  80108. c = uint8array[dataIndex++];
  80109. d = uint8array[dataIndex++];
  80110. if (a != 2 || b != 2 || (c & 0x80)) {
  80111. // this file is not run length encoded
  80112. throw "HDR Bad header format, not RLE";
  80113. }
  80114. if (((c << 8) | d) != scanline_width) {
  80115. throw "HDR Bad header format, wrong scan line width";
  80116. }
  80117. index = 0;
  80118. // read each of the four channels for the scanline into the buffer
  80119. for (i = 0; i < 4; i++) {
  80120. endIndex = (i + 1) * scanline_width;
  80121. while (index < endIndex) {
  80122. a = uint8array[dataIndex++];
  80123. b = uint8array[dataIndex++];
  80124. if (a > 128) {
  80125. // a run of the same value
  80126. count = a - 128;
  80127. if ((count == 0) || (count > endIndex - index)) {
  80128. throw "HDR Bad Format, bad scanline data (run)";
  80129. }
  80130. while (count-- > 0) {
  80131. scanLineArray[index++] = b;
  80132. }
  80133. }
  80134. else {
  80135. // a non-run
  80136. count = a;
  80137. if ((count == 0) || (count > endIndex - index)) {
  80138. throw "HDR Bad Format, bad scanline data (non-run)";
  80139. }
  80140. scanLineArray[index++] = b;
  80141. if (--count > 0) {
  80142. for (var j = 0; j < count; j++) {
  80143. scanLineArray[index++] = uint8array[dataIndex++];
  80144. }
  80145. }
  80146. }
  80147. }
  80148. }
  80149. // now convert data from buffer into floats
  80150. for (i = 0; i < scanline_width; i++) {
  80151. a = scanLineArray[i];
  80152. b = scanLineArray[i + scanline_width];
  80153. c = scanLineArray[i + 2 * scanline_width];
  80154. d = scanLineArray[i + 3 * scanline_width];
  80155. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  80156. }
  80157. num_scanlines--;
  80158. }
  80159. return resultArray;
  80160. };
  80161. return HDRTools;
  80162. }());
  80163. BABYLON.HDRTools = HDRTools;
  80164. })(BABYLON || (BABYLON = {}));
  80165. //# sourceMappingURL=babylon.hdr.js.map
  80166. var BABYLON;
  80167. (function (BABYLON) {
  80168. /**
  80169. * This represents a texture coming from an HDR input.
  80170. *
  80171. * The only supported format is currently panorama picture stored in RGBE format.
  80172. * Example of such files can be found on HDRLib: http://hdrlib.com/
  80173. */
  80174. var HDRCubeTexture = /** @class */ (function (_super) {
  80175. __extends(HDRCubeTexture, _super);
  80176. /**
  80177. * Instantiates an HDRTexture from the following parameters.
  80178. *
  80179. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  80180. * @param scene The scene the texture will be used in
  80181. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  80182. * @param noMipmap Forces to not generate the mipmap if true
  80183. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  80184. * @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)
  80185. * @param reserved Reserved flag for internal use.
  80186. */
  80187. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  80188. if (noMipmap === void 0) { noMipmap = false; }
  80189. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80190. if (gammaSpace === void 0) { gammaSpace = false; }
  80191. if (reserved === void 0) { reserved = false; }
  80192. if (onLoad === void 0) { onLoad = null; }
  80193. if (onError === void 0) { onError = null; }
  80194. var _this = _super.call(this, scene) || this;
  80195. _this._generateHarmonics = true;
  80196. _this._onLoad = null;
  80197. _this._onError = null;
  80198. /**
  80199. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  80200. */
  80201. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  80202. _this._isBlocking = true;
  80203. _this._rotationY = 0;
  80204. /**
  80205. * Gets or sets the center of the bounding box associated with the cube texture
  80206. * It must define where the camera used to render the texture was set
  80207. */
  80208. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  80209. if (!url) {
  80210. return _this;
  80211. }
  80212. _this.name = url;
  80213. _this.url = url;
  80214. _this.hasAlpha = false;
  80215. _this.isCube = true;
  80216. _this._textureMatrix = BABYLON.Matrix.Identity();
  80217. _this._onLoad = onLoad;
  80218. _this._onError = onError;
  80219. _this.gammaSpace = gammaSpace;
  80220. _this._noMipmap = noMipmap;
  80221. _this._size = size;
  80222. _this._texture = _this._getFromCache(url, _this._noMipmap);
  80223. if (!_this._texture) {
  80224. if (!scene.useDelayedTextureLoading) {
  80225. _this.loadTexture();
  80226. }
  80227. else {
  80228. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  80229. }
  80230. }
  80231. return _this;
  80232. }
  80233. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  80234. /**
  80235. * Gets wether or not the texture is blocking during loading.
  80236. */
  80237. get: function () {
  80238. return this._isBlocking;
  80239. },
  80240. /**
  80241. * Sets wether or not the texture is blocking during loading.
  80242. */
  80243. set: function (value) {
  80244. this._isBlocking = value;
  80245. },
  80246. enumerable: true,
  80247. configurable: true
  80248. });
  80249. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  80250. /**
  80251. * Gets texture matrix rotation angle around Y axis radians.
  80252. */
  80253. get: function () {
  80254. return this._rotationY;
  80255. },
  80256. /**
  80257. * Sets texture matrix rotation angle around Y axis in radians.
  80258. */
  80259. set: function (value) {
  80260. this._rotationY = value;
  80261. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  80262. },
  80263. enumerable: true,
  80264. configurable: true
  80265. });
  80266. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  80267. get: function () {
  80268. return this._boundingBoxSize;
  80269. },
  80270. /**
  80271. * Gets or sets the size of the bounding box associated with the cube texture
  80272. * When defined, the cubemap will switch to local mode
  80273. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  80274. * @example https://www.babylonjs-playground.com/#RNASML
  80275. */
  80276. set: function (value) {
  80277. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  80278. return;
  80279. }
  80280. this._boundingBoxSize = value;
  80281. var scene = this.getScene();
  80282. if (scene) {
  80283. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  80284. }
  80285. },
  80286. enumerable: true,
  80287. configurable: true
  80288. });
  80289. /**
  80290. * Occurs when the file is raw .hdr file.
  80291. */
  80292. HDRCubeTexture.prototype.loadTexture = function () {
  80293. var _this = this;
  80294. var callback = function (buffer) {
  80295. var scene = _this.getScene();
  80296. if (!scene) {
  80297. return null;
  80298. }
  80299. // Extract the raw linear data.
  80300. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  80301. // Generate harmonics if needed.
  80302. if (_this._generateHarmonics) {
  80303. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  80304. _this.sphericalPolynomial = sphericalPolynomial;
  80305. }
  80306. var results = [];
  80307. var byteArray = null;
  80308. // Push each faces.
  80309. for (var j = 0; j < 6; j++) {
  80310. // Create uintarray fallback.
  80311. if (!scene.getEngine().getCaps().textureFloat) {
  80312. // 3 channels of 1 bytes per pixel in bytes.
  80313. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  80314. byteArray = new Uint8Array(byteBuffer);
  80315. }
  80316. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  80317. // If special cases.
  80318. if (_this.gammaSpace || byteArray) {
  80319. for (var i = 0; i < _this._size * _this._size; i++) {
  80320. // Put in gamma space if requested.
  80321. if (_this.gammaSpace) {
  80322. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  80323. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  80324. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  80325. }
  80326. // Convert to int texture for fallback.
  80327. if (byteArray) {
  80328. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  80329. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  80330. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  80331. // May use luminance instead if the result is not accurate.
  80332. var max = Math.max(Math.max(r, g), b);
  80333. if (max > 255) {
  80334. var scale = 255 / max;
  80335. r *= scale;
  80336. g *= scale;
  80337. b *= scale;
  80338. }
  80339. byteArray[(i * 3) + 0] = r;
  80340. byteArray[(i * 3) + 1] = g;
  80341. byteArray[(i * 3) + 2] = b;
  80342. }
  80343. }
  80344. }
  80345. if (byteArray) {
  80346. results.push(byteArray);
  80347. }
  80348. else {
  80349. results.push(dataFace);
  80350. }
  80351. }
  80352. return results;
  80353. };
  80354. var scene = this.getScene();
  80355. if (scene) {
  80356. 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);
  80357. }
  80358. };
  80359. HDRCubeTexture.prototype.clone = function () {
  80360. var scene = this.getScene();
  80361. if (!scene) {
  80362. return this;
  80363. }
  80364. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  80365. // Base texture
  80366. newTexture.level = this.level;
  80367. newTexture.wrapU = this.wrapU;
  80368. newTexture.wrapV = this.wrapV;
  80369. newTexture.coordinatesIndex = this.coordinatesIndex;
  80370. newTexture.coordinatesMode = this.coordinatesMode;
  80371. return newTexture;
  80372. };
  80373. // Methods
  80374. HDRCubeTexture.prototype.delayLoad = function () {
  80375. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  80376. return;
  80377. }
  80378. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  80379. this._texture = this._getFromCache(this.url, this._noMipmap);
  80380. if (!this._texture) {
  80381. this.loadTexture();
  80382. }
  80383. };
  80384. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  80385. return this._textureMatrix;
  80386. };
  80387. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  80388. this._textureMatrix = value;
  80389. };
  80390. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  80391. var texture = null;
  80392. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  80393. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  80394. texture.name = parsedTexture.name;
  80395. texture.hasAlpha = parsedTexture.hasAlpha;
  80396. texture.level = parsedTexture.level;
  80397. texture.coordinatesMode = parsedTexture.coordinatesMode;
  80398. texture.isBlocking = parsedTexture.isBlocking;
  80399. }
  80400. if (texture) {
  80401. if (parsedTexture.boundingBoxPosition) {
  80402. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  80403. }
  80404. if (parsedTexture.boundingBoxSize) {
  80405. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  80406. }
  80407. if (parsedTexture.rotationY) {
  80408. texture.rotationY = parsedTexture.rotationY;
  80409. }
  80410. }
  80411. return texture;
  80412. };
  80413. HDRCubeTexture.prototype.serialize = function () {
  80414. if (!this.name) {
  80415. return null;
  80416. }
  80417. var serializationObject = {};
  80418. serializationObject.name = this.name;
  80419. serializationObject.hasAlpha = this.hasAlpha;
  80420. serializationObject.isCube = true;
  80421. serializationObject.level = this.level;
  80422. serializationObject.size = this._size;
  80423. serializationObject.coordinatesMode = this.coordinatesMode;
  80424. serializationObject.useInGammaSpace = this.gammaSpace;
  80425. serializationObject.generateHarmonics = this._generateHarmonics;
  80426. serializationObject.customType = "BABYLON.HDRCubeTexture";
  80427. serializationObject.noMipmap = this._noMipmap;
  80428. serializationObject.isBlocking = this._isBlocking;
  80429. serializationObject.rotationY = this._rotationY;
  80430. return serializationObject;
  80431. };
  80432. HDRCubeTexture._facesMapping = [
  80433. "right",
  80434. "left",
  80435. "up",
  80436. "down",
  80437. "front",
  80438. "back"
  80439. ];
  80440. return HDRCubeTexture;
  80441. }(BABYLON.BaseTexture));
  80442. BABYLON.HDRCubeTexture = HDRCubeTexture;
  80443. })(BABYLON || (BABYLON = {}));
  80444. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  80445. var BABYLON;
  80446. (function (BABYLON) {
  80447. var IndexedVector2 = /** @class */ (function (_super) {
  80448. __extends(IndexedVector2, _super);
  80449. function IndexedVector2(original, index) {
  80450. var _this = _super.call(this, original.x, original.y) || this;
  80451. _this.index = index;
  80452. return _this;
  80453. }
  80454. return IndexedVector2;
  80455. }(BABYLON.Vector2));
  80456. var PolygonPoints = /** @class */ (function () {
  80457. function PolygonPoints() {
  80458. this.elements = new Array();
  80459. }
  80460. PolygonPoints.prototype.add = function (originalPoints) {
  80461. var _this = this;
  80462. var result = new Array();
  80463. originalPoints.forEach(function (point) {
  80464. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  80465. var newPoint = new IndexedVector2(point, _this.elements.length);
  80466. result.push(newPoint);
  80467. _this.elements.push(newPoint);
  80468. }
  80469. });
  80470. return result;
  80471. };
  80472. PolygonPoints.prototype.computeBounds = function () {
  80473. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80474. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80475. this.elements.forEach(function (point) {
  80476. // x
  80477. if (point.x < lmin.x) {
  80478. lmin.x = point.x;
  80479. }
  80480. else if (point.x > lmax.x) {
  80481. lmax.x = point.x;
  80482. }
  80483. // y
  80484. if (point.y < lmin.y) {
  80485. lmin.y = point.y;
  80486. }
  80487. else if (point.y > lmax.y) {
  80488. lmax.y = point.y;
  80489. }
  80490. });
  80491. return {
  80492. min: lmin,
  80493. max: lmax,
  80494. width: lmax.x - lmin.x,
  80495. height: lmax.y - lmin.y
  80496. };
  80497. };
  80498. return PolygonPoints;
  80499. }());
  80500. var Polygon = /** @class */ (function () {
  80501. function Polygon() {
  80502. }
  80503. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  80504. return [
  80505. new BABYLON.Vector2(xmin, ymin),
  80506. new BABYLON.Vector2(xmax, ymin),
  80507. new BABYLON.Vector2(xmax, ymax),
  80508. new BABYLON.Vector2(xmin, ymax)
  80509. ];
  80510. };
  80511. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  80512. if (cx === void 0) { cx = 0; }
  80513. if (cy === void 0) { cy = 0; }
  80514. if (numberOfSides === void 0) { numberOfSides = 32; }
  80515. var result = new Array();
  80516. var angle = 0;
  80517. var increment = (Math.PI * 2) / numberOfSides;
  80518. for (var i = 0; i < numberOfSides; i++) {
  80519. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  80520. angle -= increment;
  80521. }
  80522. return result;
  80523. };
  80524. Polygon.Parse = function (input) {
  80525. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  80526. var i, result = [];
  80527. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  80528. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  80529. }
  80530. return result;
  80531. };
  80532. Polygon.StartingAt = function (x, y) {
  80533. return BABYLON.Path2.StartingAt(x, y);
  80534. };
  80535. return Polygon;
  80536. }());
  80537. BABYLON.Polygon = Polygon;
  80538. var PolygonMeshBuilder = /** @class */ (function () {
  80539. function PolygonMeshBuilder(name, contours, scene) {
  80540. this._points = new PolygonPoints();
  80541. this._outlinepoints = new PolygonPoints();
  80542. this._holes = new Array();
  80543. this._epoints = new Array();
  80544. this._eholes = new Array();
  80545. this._name = name;
  80546. this._scene = scene;
  80547. var points;
  80548. if (contours instanceof BABYLON.Path2) {
  80549. points = contours.getPoints();
  80550. }
  80551. else {
  80552. points = contours;
  80553. }
  80554. this._addToepoint(points);
  80555. this._points.add(points);
  80556. this._outlinepoints.add(points);
  80557. if (typeof earcut === 'undefined') {
  80558. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  80559. }
  80560. }
  80561. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  80562. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  80563. var p = points_1[_i];
  80564. this._epoints.push(p.x, p.y);
  80565. }
  80566. };
  80567. PolygonMeshBuilder.prototype.addHole = function (hole) {
  80568. this._points.add(hole);
  80569. var holepoints = new PolygonPoints();
  80570. holepoints.add(hole);
  80571. this._holes.push(holepoints);
  80572. this._eholes.push(this._epoints.length / 2);
  80573. this._addToepoint(hole);
  80574. return this;
  80575. };
  80576. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  80577. var _this = this;
  80578. if (updatable === void 0) { updatable = false; }
  80579. if (depth === void 0) { depth = 0; }
  80580. var result = new BABYLON.Mesh(this._name, this._scene);
  80581. var normals = new Array();
  80582. var positions = new Array();
  80583. var uvs = new Array();
  80584. var bounds = this._points.computeBounds();
  80585. this._points.elements.forEach(function (p) {
  80586. normals.push(0, 1.0, 0);
  80587. positions.push(p.x, 0, p.y);
  80588. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  80589. });
  80590. var indices = new Array();
  80591. var res = earcut(this._epoints, this._eholes, 2);
  80592. for (var i = 0; i < res.length; i++) {
  80593. indices.push(res[i]);
  80594. }
  80595. if (depth > 0) {
  80596. var positionscount = (positions.length / 3); //get the current pointcount
  80597. this._points.elements.forEach(function (p) {
  80598. normals.push(0, -1.0, 0);
  80599. positions.push(p.x, -depth, p.y);
  80600. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  80601. });
  80602. var totalCount = indices.length;
  80603. for (var i = 0; i < totalCount; i += 3) {
  80604. var i0 = indices[i + 0];
  80605. var i1 = indices[i + 1];
  80606. var i2 = indices[i + 2];
  80607. indices.push(i2 + positionscount);
  80608. indices.push(i1 + positionscount);
  80609. indices.push(i0 + positionscount);
  80610. }
  80611. //Add the sides
  80612. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  80613. this._holes.forEach(function (hole) {
  80614. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  80615. });
  80616. }
  80617. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  80618. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  80619. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  80620. result.setIndices(indices);
  80621. return result;
  80622. };
  80623. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  80624. var StartIndex = positions.length / 3;
  80625. var ulength = 0;
  80626. for (var i = 0; i < points.elements.length; i++) {
  80627. var p = points.elements[i];
  80628. var p1;
  80629. if ((i + 1) > points.elements.length - 1) {
  80630. p1 = points.elements[0];
  80631. }
  80632. else {
  80633. p1 = points.elements[i + 1];
  80634. }
  80635. positions.push(p.x, 0, p.y);
  80636. positions.push(p.x, -depth, p.y);
  80637. positions.push(p1.x, 0, p1.y);
  80638. positions.push(p1.x, -depth, p1.y);
  80639. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  80640. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  80641. var v3 = v2.subtract(v1);
  80642. var v4 = new BABYLON.Vector3(0, 1, 0);
  80643. var vn = BABYLON.Vector3.Cross(v3, v4);
  80644. vn = vn.normalize();
  80645. uvs.push(ulength / bounds.width, 0);
  80646. uvs.push(ulength / bounds.width, 1);
  80647. ulength += v3.length();
  80648. uvs.push((ulength / bounds.width), 0);
  80649. uvs.push((ulength / bounds.width), 1);
  80650. if (!flip) {
  80651. normals.push(-vn.x, -vn.y, -vn.z);
  80652. normals.push(-vn.x, -vn.y, -vn.z);
  80653. normals.push(-vn.x, -vn.y, -vn.z);
  80654. normals.push(-vn.x, -vn.y, -vn.z);
  80655. indices.push(StartIndex);
  80656. indices.push(StartIndex + 1);
  80657. indices.push(StartIndex + 2);
  80658. indices.push(StartIndex + 1);
  80659. indices.push(StartIndex + 3);
  80660. indices.push(StartIndex + 2);
  80661. }
  80662. else {
  80663. normals.push(vn.x, vn.y, vn.z);
  80664. normals.push(vn.x, vn.y, vn.z);
  80665. normals.push(vn.x, vn.y, vn.z);
  80666. normals.push(vn.x, vn.y, vn.z);
  80667. indices.push(StartIndex);
  80668. indices.push(StartIndex + 2);
  80669. indices.push(StartIndex + 1);
  80670. indices.push(StartIndex + 1);
  80671. indices.push(StartIndex + 2);
  80672. indices.push(StartIndex + 3);
  80673. }
  80674. StartIndex += 4;
  80675. }
  80676. ;
  80677. };
  80678. return PolygonMeshBuilder;
  80679. }());
  80680. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  80681. })(BABYLON || (BABYLON = {}));
  80682. //# sourceMappingURL=babylon.polygonMesh.js.map
  80683. var BABYLON;
  80684. (function (BABYLON) {
  80685. // Unique ID when we import meshes from Babylon to CSG
  80686. var currentCSGMeshId = 0;
  80687. // # class Vertex
  80688. // Represents a vertex of a polygon. Use your own vertex class instead of this
  80689. // one to provide additional features like texture coordinates and vertex
  80690. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  80691. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  80692. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  80693. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  80694. // is not used anywhere else.
  80695. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  80696. var Vertex = /** @class */ (function () {
  80697. function Vertex(pos, normal, uv) {
  80698. this.pos = pos;
  80699. this.normal = normal;
  80700. this.uv = uv;
  80701. }
  80702. Vertex.prototype.clone = function () {
  80703. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  80704. };
  80705. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  80706. // orientation of a polygon is flipped.
  80707. Vertex.prototype.flip = function () {
  80708. this.normal = this.normal.scale(-1);
  80709. };
  80710. // Create a new vertex between this vertex and `other` by linearly
  80711. // interpolating all properties using a parameter of `t`. Subclasses should
  80712. // override this to interpolate additional properties.
  80713. Vertex.prototype.interpolate = function (other, t) {
  80714. 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));
  80715. };
  80716. return Vertex;
  80717. }());
  80718. // # class Plane
  80719. // Represents a plane in 3D space.
  80720. var Plane = /** @class */ (function () {
  80721. function Plane(normal, w) {
  80722. this.normal = normal;
  80723. this.w = w;
  80724. }
  80725. Plane.FromPoints = function (a, b, c) {
  80726. var v0 = c.subtract(a);
  80727. var v1 = b.subtract(a);
  80728. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  80729. return null;
  80730. }
  80731. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  80732. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  80733. };
  80734. Plane.prototype.clone = function () {
  80735. return new Plane(this.normal.clone(), this.w);
  80736. };
  80737. Plane.prototype.flip = function () {
  80738. this.normal.scaleInPlace(-1);
  80739. this.w = -this.w;
  80740. };
  80741. // Split `polygon` by this plane if needed, then put the polygon or polygon
  80742. // fragments in the appropriate lists. Coplanar polygons go into either
  80743. // `coplanarFront` or `coplanarBack` depending on their orientation with
  80744. // respect to this plane. Polygons in front or in back of this plane go into
  80745. // either `front` or `back`.
  80746. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  80747. var COPLANAR = 0;
  80748. var FRONT = 1;
  80749. var BACK = 2;
  80750. var SPANNING = 3;
  80751. // Classify each point as well as the entire polygon into one of the above
  80752. // four classes.
  80753. var polygonType = 0;
  80754. var types = [];
  80755. var i;
  80756. var t;
  80757. for (i = 0; i < polygon.vertices.length; i++) {
  80758. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  80759. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  80760. polygonType |= type;
  80761. types.push(type);
  80762. }
  80763. // Put the polygon in the correct list, splitting it when necessary.
  80764. switch (polygonType) {
  80765. case COPLANAR:
  80766. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  80767. break;
  80768. case FRONT:
  80769. front.push(polygon);
  80770. break;
  80771. case BACK:
  80772. back.push(polygon);
  80773. break;
  80774. case SPANNING:
  80775. var f = [], b = [];
  80776. for (i = 0; i < polygon.vertices.length; i++) {
  80777. var j = (i + 1) % polygon.vertices.length;
  80778. var ti = types[i], tj = types[j];
  80779. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  80780. if (ti !== BACK)
  80781. f.push(vi);
  80782. if (ti !== FRONT)
  80783. b.push(ti !== BACK ? vi.clone() : vi);
  80784. if ((ti | tj) === SPANNING) {
  80785. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  80786. var v = vi.interpolate(vj, t);
  80787. f.push(v);
  80788. b.push(v.clone());
  80789. }
  80790. }
  80791. var poly;
  80792. if (f.length >= 3) {
  80793. poly = new Polygon(f, polygon.shared);
  80794. if (poly.plane)
  80795. front.push(poly);
  80796. }
  80797. if (b.length >= 3) {
  80798. poly = new Polygon(b, polygon.shared);
  80799. if (poly.plane)
  80800. back.push(poly);
  80801. }
  80802. break;
  80803. }
  80804. };
  80805. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  80806. // point is on the plane.
  80807. Plane.EPSILON = 1e-5;
  80808. return Plane;
  80809. }());
  80810. // # class Polygon
  80811. // Represents a convex polygon. The vertices used to initialize a polygon must
  80812. // be coplanar and form a convex loop.
  80813. //
  80814. // Each convex polygon has a `shared` property, which is shared between all
  80815. // polygons that are clones of each other or were split from the same polygon.
  80816. // This can be used to define per-polygon properties (such as surface color).
  80817. var Polygon = /** @class */ (function () {
  80818. function Polygon(vertices, shared) {
  80819. this.vertices = vertices;
  80820. this.shared = shared;
  80821. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  80822. }
  80823. Polygon.prototype.clone = function () {
  80824. var vertices = this.vertices.map(function (v) { return v.clone(); });
  80825. return new Polygon(vertices, this.shared);
  80826. };
  80827. Polygon.prototype.flip = function () {
  80828. this.vertices.reverse().map(function (v) { v.flip(); });
  80829. this.plane.flip();
  80830. };
  80831. return Polygon;
  80832. }());
  80833. // # class Node
  80834. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  80835. // by picking a polygon to split along. That polygon (and all other coplanar
  80836. // polygons) are added directly to that node and the other polygons are added to
  80837. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  80838. // no distinction between internal and leaf nodes.
  80839. var Node = /** @class */ (function () {
  80840. function Node(polygons) {
  80841. this.plane = null;
  80842. this.front = null;
  80843. this.back = null;
  80844. this.polygons = new Array();
  80845. if (polygons) {
  80846. this.build(polygons);
  80847. }
  80848. }
  80849. Node.prototype.clone = function () {
  80850. var node = new Node();
  80851. node.plane = this.plane && this.plane.clone();
  80852. node.front = this.front && this.front.clone();
  80853. node.back = this.back && this.back.clone();
  80854. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  80855. return node;
  80856. };
  80857. // Convert solid space to empty space and empty space to solid space.
  80858. Node.prototype.invert = function () {
  80859. for (var i = 0; i < this.polygons.length; i++) {
  80860. this.polygons[i].flip();
  80861. }
  80862. if (this.plane) {
  80863. this.plane.flip();
  80864. }
  80865. if (this.front) {
  80866. this.front.invert();
  80867. }
  80868. if (this.back) {
  80869. this.back.invert();
  80870. }
  80871. var temp = this.front;
  80872. this.front = this.back;
  80873. this.back = temp;
  80874. };
  80875. // Recursively remove all polygons in `polygons` that are inside this BSP
  80876. // tree.
  80877. Node.prototype.clipPolygons = function (polygons) {
  80878. if (!this.plane)
  80879. return polygons.slice();
  80880. var front = new Array(), back = new Array();
  80881. for (var i = 0; i < polygons.length; i++) {
  80882. this.plane.splitPolygon(polygons[i], front, back, front, back);
  80883. }
  80884. if (this.front) {
  80885. front = this.front.clipPolygons(front);
  80886. }
  80887. if (this.back) {
  80888. back = this.back.clipPolygons(back);
  80889. }
  80890. else {
  80891. back = [];
  80892. }
  80893. return front.concat(back);
  80894. };
  80895. // Remove all polygons in this BSP tree that are inside the other BSP tree
  80896. // `bsp`.
  80897. Node.prototype.clipTo = function (bsp) {
  80898. this.polygons = bsp.clipPolygons(this.polygons);
  80899. if (this.front)
  80900. this.front.clipTo(bsp);
  80901. if (this.back)
  80902. this.back.clipTo(bsp);
  80903. };
  80904. // Return a list of all polygons in this BSP tree.
  80905. Node.prototype.allPolygons = function () {
  80906. var polygons = this.polygons.slice();
  80907. if (this.front)
  80908. polygons = polygons.concat(this.front.allPolygons());
  80909. if (this.back)
  80910. polygons = polygons.concat(this.back.allPolygons());
  80911. return polygons;
  80912. };
  80913. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  80914. // new polygons are filtered down to the bottom of the tree and become new
  80915. // nodes there. Each set of polygons is partitioned using the first polygon
  80916. // (no heuristic is used to pick a good split).
  80917. Node.prototype.build = function (polygons) {
  80918. if (!polygons.length)
  80919. return;
  80920. if (!this.plane)
  80921. this.plane = polygons[0].plane.clone();
  80922. var front = new Array(), back = new Array();
  80923. for (var i = 0; i < polygons.length; i++) {
  80924. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  80925. }
  80926. if (front.length) {
  80927. if (!this.front)
  80928. this.front = new Node();
  80929. this.front.build(front);
  80930. }
  80931. if (back.length) {
  80932. if (!this.back)
  80933. this.back = new Node();
  80934. this.back.build(back);
  80935. }
  80936. };
  80937. return Node;
  80938. }());
  80939. var CSG = /** @class */ (function () {
  80940. function CSG() {
  80941. this.polygons = new Array();
  80942. }
  80943. // Convert BABYLON.Mesh to BABYLON.CSG
  80944. CSG.FromMesh = function (mesh) {
  80945. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  80946. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  80947. if (mesh instanceof BABYLON.Mesh) {
  80948. mesh.computeWorldMatrix(true);
  80949. matrix = mesh.getWorldMatrix();
  80950. meshPosition = mesh.position.clone();
  80951. meshRotation = mesh.rotation.clone();
  80952. if (mesh.rotationQuaternion) {
  80953. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  80954. }
  80955. meshScaling = mesh.scaling.clone();
  80956. }
  80957. else {
  80958. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  80959. }
  80960. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  80961. var subMeshes = mesh.subMeshes;
  80962. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  80963. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  80964. vertices = [];
  80965. for (var j = 0; j < 3; j++) {
  80966. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  80967. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  80968. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  80969. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  80970. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  80971. vertex = new Vertex(position, normal, uv);
  80972. vertices.push(vertex);
  80973. }
  80974. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  80975. // To handle the case of degenerated triangle
  80976. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  80977. if (polygon.plane)
  80978. polygons.push(polygon);
  80979. }
  80980. }
  80981. var csg = CSG.FromPolygons(polygons);
  80982. csg.matrix = matrix;
  80983. csg.position = meshPosition;
  80984. csg.rotation = meshRotation;
  80985. csg.scaling = meshScaling;
  80986. csg.rotationQuaternion = meshRotationQuaternion;
  80987. currentCSGMeshId++;
  80988. return csg;
  80989. };
  80990. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  80991. CSG.FromPolygons = function (polygons) {
  80992. var csg = new CSG();
  80993. csg.polygons = polygons;
  80994. return csg;
  80995. };
  80996. CSG.prototype.clone = function () {
  80997. var csg = new CSG();
  80998. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  80999. csg.copyTransformAttributes(this);
  81000. return csg;
  81001. };
  81002. CSG.prototype.union = function (csg) {
  81003. var a = new Node(this.clone().polygons);
  81004. var b = new Node(csg.clone().polygons);
  81005. a.clipTo(b);
  81006. b.clipTo(a);
  81007. b.invert();
  81008. b.clipTo(a);
  81009. b.invert();
  81010. a.build(b.allPolygons());
  81011. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81012. };
  81013. CSG.prototype.unionInPlace = function (csg) {
  81014. var a = new Node(this.polygons);
  81015. var b = new Node(csg.polygons);
  81016. a.clipTo(b);
  81017. b.clipTo(a);
  81018. b.invert();
  81019. b.clipTo(a);
  81020. b.invert();
  81021. a.build(b.allPolygons());
  81022. this.polygons = a.allPolygons();
  81023. };
  81024. CSG.prototype.subtract = function (csg) {
  81025. var a = new Node(this.clone().polygons);
  81026. var b = new Node(csg.clone().polygons);
  81027. a.invert();
  81028. a.clipTo(b);
  81029. b.clipTo(a);
  81030. b.invert();
  81031. b.clipTo(a);
  81032. b.invert();
  81033. a.build(b.allPolygons());
  81034. a.invert();
  81035. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81036. };
  81037. CSG.prototype.subtractInPlace = function (csg) {
  81038. var a = new Node(this.polygons);
  81039. var b = new Node(csg.polygons);
  81040. a.invert();
  81041. a.clipTo(b);
  81042. b.clipTo(a);
  81043. b.invert();
  81044. b.clipTo(a);
  81045. b.invert();
  81046. a.build(b.allPolygons());
  81047. a.invert();
  81048. this.polygons = a.allPolygons();
  81049. };
  81050. CSG.prototype.intersect = function (csg) {
  81051. var a = new Node(this.clone().polygons);
  81052. var b = new Node(csg.clone().polygons);
  81053. a.invert();
  81054. b.clipTo(a);
  81055. b.invert();
  81056. a.clipTo(b);
  81057. b.clipTo(a);
  81058. a.build(b.allPolygons());
  81059. a.invert();
  81060. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81061. };
  81062. CSG.prototype.intersectInPlace = function (csg) {
  81063. var a = new Node(this.polygons);
  81064. var b = new Node(csg.polygons);
  81065. a.invert();
  81066. b.clipTo(a);
  81067. b.invert();
  81068. a.clipTo(b);
  81069. b.clipTo(a);
  81070. a.build(b.allPolygons());
  81071. a.invert();
  81072. this.polygons = a.allPolygons();
  81073. };
  81074. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  81075. // not modified.
  81076. CSG.prototype.inverse = function () {
  81077. var csg = this.clone();
  81078. csg.inverseInPlace();
  81079. return csg;
  81080. };
  81081. CSG.prototype.inverseInPlace = function () {
  81082. this.polygons.map(function (p) { p.flip(); });
  81083. };
  81084. // This is used to keep meshes transformations so they can be restored
  81085. // when we build back a Babylon Mesh
  81086. // NB : All CSG operations are performed in world coordinates
  81087. CSG.prototype.copyTransformAttributes = function (csg) {
  81088. this.matrix = csg.matrix;
  81089. this.position = csg.position;
  81090. this.rotation = csg.rotation;
  81091. this.scaling = csg.scaling;
  81092. this.rotationQuaternion = csg.rotationQuaternion;
  81093. return this;
  81094. };
  81095. // Build Raw mesh from CSG
  81096. // Coordinates here are in world space
  81097. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  81098. var matrix = this.matrix.clone();
  81099. matrix.invert();
  81100. 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;
  81101. if (keepSubMeshes) {
  81102. // Sort Polygons, since subMeshes are indices range
  81103. polygons.sort(function (a, b) {
  81104. if (a.shared.meshId === b.shared.meshId) {
  81105. return a.shared.subMeshId - b.shared.subMeshId;
  81106. }
  81107. else {
  81108. return a.shared.meshId - b.shared.meshId;
  81109. }
  81110. });
  81111. }
  81112. for (var i = 0, il = polygons.length; i < il; i++) {
  81113. polygon = polygons[i];
  81114. // Building SubMeshes
  81115. if (!subMesh_dict[polygon.shared.meshId]) {
  81116. subMesh_dict[polygon.shared.meshId] = {};
  81117. }
  81118. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  81119. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  81120. indexStart: +Infinity,
  81121. indexEnd: -Infinity,
  81122. materialIndex: polygon.shared.materialIndex
  81123. };
  81124. }
  81125. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  81126. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  81127. polygonIndices[0] = 0;
  81128. polygonIndices[1] = j - 1;
  81129. polygonIndices[2] = j;
  81130. for (var k = 0; k < 3; k++) {
  81131. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  81132. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  81133. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  81134. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  81135. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  81136. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  81137. // Check if 2 points can be merged
  81138. if (!(typeof vertex_idx !== 'undefined' &&
  81139. normals[vertex_idx * 3] === localNormal.x &&
  81140. normals[vertex_idx * 3 + 1] === localNormal.y &&
  81141. normals[vertex_idx * 3 + 2] === localNormal.z &&
  81142. uvs[vertex_idx * 2] === uv.x &&
  81143. uvs[vertex_idx * 2 + 1] === uv.y)) {
  81144. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  81145. uvs.push(uv.x, uv.y);
  81146. normals.push(normal.x, normal.y, normal.z);
  81147. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  81148. }
  81149. indices.push(vertex_idx);
  81150. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  81151. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  81152. currentIndex++;
  81153. }
  81154. }
  81155. }
  81156. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  81157. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  81158. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  81159. mesh.setIndices(indices, null);
  81160. if (keepSubMeshes) {
  81161. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  81162. var materialIndexOffset = 0, materialMaxIndex;
  81163. mesh.subMeshes = new Array();
  81164. for (var m in subMesh_dict) {
  81165. materialMaxIndex = -1;
  81166. for (var sm in subMesh_dict[m]) {
  81167. subMesh_obj = subMesh_dict[m][sm];
  81168. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  81169. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  81170. }
  81171. materialIndexOffset += ++materialMaxIndex;
  81172. }
  81173. }
  81174. return mesh;
  81175. };
  81176. // Build Mesh from CSG taking material and transforms into account
  81177. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  81178. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  81179. mesh.material = material;
  81180. mesh.position.copyFrom(this.position);
  81181. mesh.rotation.copyFrom(this.rotation);
  81182. if (this.rotationQuaternion) {
  81183. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  81184. }
  81185. mesh.scaling.copyFrom(this.scaling);
  81186. mesh.computeWorldMatrix(true);
  81187. return mesh;
  81188. };
  81189. return CSG;
  81190. }());
  81191. BABYLON.CSG = CSG;
  81192. })(BABYLON || (BABYLON = {}));
  81193. //# sourceMappingURL=babylon.csg.js.map
  81194. var BABYLON;
  81195. (function (BABYLON) {
  81196. var LensFlare = /** @class */ (function () {
  81197. function LensFlare(size, position, color, imgUrl, system) {
  81198. this.size = size;
  81199. this.position = position;
  81200. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  81201. this.color = color || new BABYLON.Color3(1, 1, 1);
  81202. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  81203. this._system = system;
  81204. system.lensFlares.push(this);
  81205. }
  81206. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  81207. return new LensFlare(size, position, color, imgUrl, system);
  81208. };
  81209. LensFlare.prototype.dispose = function () {
  81210. if (this.texture) {
  81211. this.texture.dispose();
  81212. }
  81213. // Remove from scene
  81214. var index = this._system.lensFlares.indexOf(this);
  81215. this._system.lensFlares.splice(index, 1);
  81216. };
  81217. ;
  81218. return LensFlare;
  81219. }());
  81220. BABYLON.LensFlare = LensFlare;
  81221. })(BABYLON || (BABYLON = {}));
  81222. //# sourceMappingURL=babylon.lensFlare.js.map
  81223. var BABYLON;
  81224. (function (BABYLON) {
  81225. var LensFlareSystem = /** @class */ (function () {
  81226. function LensFlareSystem(name, emitter, scene) {
  81227. this.name = name;
  81228. this.lensFlares = new Array();
  81229. this.borderLimit = 300;
  81230. this.viewportBorder = 0;
  81231. this.layerMask = 0x0FFFFFFF;
  81232. this._vertexBuffers = {};
  81233. this._isEnabled = true;
  81234. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81235. this._emitter = emitter;
  81236. this.id = name;
  81237. scene.lensFlareSystems.push(this);
  81238. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  81239. var engine = scene.getEngine();
  81240. // VBO
  81241. var vertices = [];
  81242. vertices.push(1, 1);
  81243. vertices.push(-1, 1);
  81244. vertices.push(-1, -1);
  81245. vertices.push(1, -1);
  81246. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81247. // Indices
  81248. var indices = [];
  81249. indices.push(0);
  81250. indices.push(1);
  81251. indices.push(2);
  81252. indices.push(0);
  81253. indices.push(2);
  81254. indices.push(3);
  81255. this._indexBuffer = engine.createIndexBuffer(indices);
  81256. // Effects
  81257. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  81258. }
  81259. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  81260. get: function () {
  81261. return this._isEnabled;
  81262. },
  81263. set: function (value) {
  81264. this._isEnabled = value;
  81265. },
  81266. enumerable: true,
  81267. configurable: true
  81268. });
  81269. LensFlareSystem.prototype.getScene = function () {
  81270. return this._scene;
  81271. };
  81272. LensFlareSystem.prototype.getEmitter = function () {
  81273. return this._emitter;
  81274. };
  81275. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  81276. this._emitter = newEmitter;
  81277. };
  81278. LensFlareSystem.prototype.getEmitterPosition = function () {
  81279. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  81280. };
  81281. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  81282. var position = this.getEmitterPosition();
  81283. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  81284. this._positionX = position.x;
  81285. this._positionY = position.y;
  81286. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  81287. if (this.viewportBorder > 0) {
  81288. globalViewport.x -= this.viewportBorder;
  81289. globalViewport.y -= this.viewportBorder;
  81290. globalViewport.width += this.viewportBorder * 2;
  81291. globalViewport.height += this.viewportBorder * 2;
  81292. position.x += this.viewportBorder;
  81293. position.y += this.viewportBorder;
  81294. this._positionX += this.viewportBorder;
  81295. this._positionY += this.viewportBorder;
  81296. }
  81297. if (position.z > 0) {
  81298. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  81299. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  81300. return true;
  81301. }
  81302. return true;
  81303. }
  81304. return false;
  81305. };
  81306. LensFlareSystem.prototype._isVisible = function () {
  81307. if (!this._isEnabled || !this._scene.activeCamera) {
  81308. return false;
  81309. }
  81310. var emitterPosition = this.getEmitterPosition();
  81311. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  81312. var distance = direction.length();
  81313. direction.normalize();
  81314. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  81315. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  81316. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  81317. };
  81318. LensFlareSystem.prototype.render = function () {
  81319. if (!this._effect.isReady() || !this._scene.activeCamera)
  81320. return false;
  81321. var engine = this._scene.getEngine();
  81322. var viewport = this._scene.activeCamera.viewport;
  81323. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  81324. // Position
  81325. if (!this.computeEffectivePosition(globalViewport)) {
  81326. return false;
  81327. }
  81328. // Visibility
  81329. if (!this._isVisible()) {
  81330. return false;
  81331. }
  81332. // Intensity
  81333. var awayX;
  81334. var awayY;
  81335. if (this._positionX < this.borderLimit + globalViewport.x) {
  81336. awayX = this.borderLimit + globalViewport.x - this._positionX;
  81337. }
  81338. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  81339. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  81340. }
  81341. else {
  81342. awayX = 0;
  81343. }
  81344. if (this._positionY < this.borderLimit + globalViewport.y) {
  81345. awayY = this.borderLimit + globalViewport.y - this._positionY;
  81346. }
  81347. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  81348. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  81349. }
  81350. else {
  81351. awayY = 0;
  81352. }
  81353. var away = (awayX > awayY) ? awayX : awayY;
  81354. away -= this.viewportBorder;
  81355. if (away > this.borderLimit) {
  81356. away = this.borderLimit;
  81357. }
  81358. var intensity = 1.0 - (away / this.borderLimit);
  81359. if (intensity < 0) {
  81360. return false;
  81361. }
  81362. if (intensity > 1.0) {
  81363. intensity = 1.0;
  81364. }
  81365. if (this.viewportBorder > 0) {
  81366. globalViewport.x += this.viewportBorder;
  81367. globalViewport.y += this.viewportBorder;
  81368. globalViewport.width -= this.viewportBorder * 2;
  81369. globalViewport.height -= this.viewportBorder * 2;
  81370. this._positionX -= this.viewportBorder;
  81371. this._positionY -= this.viewportBorder;
  81372. }
  81373. // Position
  81374. var centerX = globalViewport.x + globalViewport.width / 2;
  81375. var centerY = globalViewport.y + globalViewport.height / 2;
  81376. var distX = centerX - this._positionX;
  81377. var distY = centerY - this._positionY;
  81378. // Effects
  81379. engine.enableEffect(this._effect);
  81380. engine.setState(false);
  81381. engine.setDepthBuffer(false);
  81382. // VBOs
  81383. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  81384. // Flares
  81385. for (var index = 0; index < this.lensFlares.length; index++) {
  81386. var flare = this.lensFlares[index];
  81387. engine.setAlphaMode(flare.alphaMode);
  81388. var x = centerX - (distX * flare.position);
  81389. var y = centerY - (distY * flare.position);
  81390. var cw = flare.size;
  81391. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  81392. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  81393. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  81394. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  81395. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  81396. // Texture
  81397. this._effect.setTexture("textureSampler", flare.texture);
  81398. // Color
  81399. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  81400. // Draw order
  81401. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81402. }
  81403. engine.setDepthBuffer(true);
  81404. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  81405. return true;
  81406. };
  81407. LensFlareSystem.prototype.dispose = function () {
  81408. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81409. if (vertexBuffer) {
  81410. vertexBuffer.dispose();
  81411. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81412. }
  81413. if (this._indexBuffer) {
  81414. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81415. this._indexBuffer = null;
  81416. }
  81417. while (this.lensFlares.length) {
  81418. this.lensFlares[0].dispose();
  81419. }
  81420. // Remove from scene
  81421. var index = this._scene.lensFlareSystems.indexOf(this);
  81422. this._scene.lensFlareSystems.splice(index, 1);
  81423. };
  81424. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  81425. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  81426. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  81427. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  81428. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  81429. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  81430. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  81431. var parsedFlare = parsedLensFlareSystem.flares[index];
  81432. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  81433. }
  81434. return lensFlareSystem;
  81435. };
  81436. LensFlareSystem.prototype.serialize = function () {
  81437. var serializationObject = {};
  81438. serializationObject.id = this.id;
  81439. serializationObject.name = this.name;
  81440. serializationObject.emitterId = this.getEmitter().id;
  81441. serializationObject.borderLimit = this.borderLimit;
  81442. serializationObject.flares = [];
  81443. for (var index = 0; index < this.lensFlares.length; index++) {
  81444. var flare = this.lensFlares[index];
  81445. serializationObject.flares.push({
  81446. size: flare.size,
  81447. position: flare.position,
  81448. color: flare.color.asArray(),
  81449. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  81450. });
  81451. }
  81452. return serializationObject;
  81453. };
  81454. return LensFlareSystem;
  81455. }());
  81456. BABYLON.LensFlareSystem = LensFlareSystem;
  81457. })(BABYLON || (BABYLON = {}));
  81458. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  81459. var BABYLON;
  81460. (function (BABYLON) {
  81461. /**
  81462. * This is a holder class for the physics joint created by the physics plugin.
  81463. * It holds a set of functions to control the underlying joint.
  81464. */
  81465. var PhysicsJoint = /** @class */ (function () {
  81466. function PhysicsJoint(type, jointData) {
  81467. this.type = type;
  81468. this.jointData = jointData;
  81469. jointData.nativeParams = jointData.nativeParams || {};
  81470. }
  81471. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  81472. get: function () {
  81473. return this._physicsJoint;
  81474. },
  81475. set: function (newJoint) {
  81476. if (this._physicsJoint) {
  81477. //remove from the wolrd
  81478. }
  81479. this._physicsJoint = newJoint;
  81480. },
  81481. enumerable: true,
  81482. configurable: true
  81483. });
  81484. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  81485. set: function (physicsPlugin) {
  81486. this._physicsPlugin = physicsPlugin;
  81487. },
  81488. enumerable: true,
  81489. configurable: true
  81490. });
  81491. /**
  81492. * Execute a function that is physics-plugin specific.
  81493. * @param {Function} func the function that will be executed.
  81494. * It accepts two parameters: the physics world and the physics joint.
  81495. */
  81496. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  81497. func(this._physicsPlugin.world, this._physicsJoint);
  81498. };
  81499. //TODO check if the native joints are the same
  81500. //Joint Types
  81501. PhysicsJoint.DistanceJoint = 0;
  81502. PhysicsJoint.HingeJoint = 1;
  81503. PhysicsJoint.BallAndSocketJoint = 2;
  81504. PhysicsJoint.WheelJoint = 3;
  81505. PhysicsJoint.SliderJoint = 4;
  81506. //OIMO
  81507. PhysicsJoint.PrismaticJoint = 5;
  81508. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  81509. PhysicsJoint.UniversalJoint = 6;
  81510. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  81511. //Cannon
  81512. //Similar to a Ball-Joint. Different in params
  81513. PhysicsJoint.PointToPointJoint = 8;
  81514. //Cannon only at the moment
  81515. PhysicsJoint.SpringJoint = 9;
  81516. PhysicsJoint.LockJoint = 10;
  81517. return PhysicsJoint;
  81518. }());
  81519. BABYLON.PhysicsJoint = PhysicsJoint;
  81520. /**
  81521. * A class representing a physics distance joint.
  81522. */
  81523. var DistanceJoint = /** @class */ (function (_super) {
  81524. __extends(DistanceJoint, _super);
  81525. function DistanceJoint(jointData) {
  81526. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  81527. }
  81528. /**
  81529. * Update the predefined distance.
  81530. */
  81531. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  81532. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  81533. };
  81534. return DistanceJoint;
  81535. }(PhysicsJoint));
  81536. BABYLON.DistanceJoint = DistanceJoint;
  81537. var MotorEnabledJoint = /** @class */ (function (_super) {
  81538. __extends(MotorEnabledJoint, _super);
  81539. function MotorEnabledJoint(type, jointData) {
  81540. return _super.call(this, type, jointData) || this;
  81541. }
  81542. /**
  81543. * Set the motor values.
  81544. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81545. * @param {number} force the force to apply
  81546. * @param {number} maxForce max force for this motor.
  81547. */
  81548. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  81549. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81550. };
  81551. /**
  81552. * Set the motor's limits.
  81553. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81554. */
  81555. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81556. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81557. };
  81558. return MotorEnabledJoint;
  81559. }(PhysicsJoint));
  81560. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  81561. /**
  81562. * This class represents a single hinge physics joint
  81563. */
  81564. var HingeJoint = /** @class */ (function (_super) {
  81565. __extends(HingeJoint, _super);
  81566. function HingeJoint(jointData) {
  81567. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  81568. }
  81569. /**
  81570. * Set the motor values.
  81571. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81572. * @param {number} force the force to apply
  81573. * @param {number} maxForce max force for this motor.
  81574. */
  81575. HingeJoint.prototype.setMotor = function (force, maxForce) {
  81576. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81577. };
  81578. /**
  81579. * Set the motor's limits.
  81580. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81581. */
  81582. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81583. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81584. };
  81585. return HingeJoint;
  81586. }(MotorEnabledJoint));
  81587. BABYLON.HingeJoint = HingeJoint;
  81588. /**
  81589. * This class represents a dual hinge physics joint (same as wheel joint)
  81590. */
  81591. var Hinge2Joint = /** @class */ (function (_super) {
  81592. __extends(Hinge2Joint, _super);
  81593. function Hinge2Joint(jointData) {
  81594. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  81595. }
  81596. /**
  81597. * Set the motor values.
  81598. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81599. * @param {number} force the force to apply
  81600. * @param {number} maxForce max force for this motor.
  81601. * @param {motorIndex} the motor's index, 0 or 1.
  81602. */
  81603. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  81604. if (motorIndex === void 0) { motorIndex = 0; }
  81605. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  81606. };
  81607. /**
  81608. * Set the motor limits.
  81609. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81610. * @param {number} upperLimit the upper limit
  81611. * @param {number} lowerLimit lower limit
  81612. * @param {motorIndex} the motor's index, 0 or 1.
  81613. */
  81614. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  81615. if (motorIndex === void 0) { motorIndex = 0; }
  81616. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  81617. };
  81618. return Hinge2Joint;
  81619. }(MotorEnabledJoint));
  81620. BABYLON.Hinge2Joint = Hinge2Joint;
  81621. })(BABYLON || (BABYLON = {}));
  81622. //# sourceMappingURL=babylon.physicsJoint.js.map
  81623. var BABYLON;
  81624. (function (BABYLON) {
  81625. var PhysicsImpostor = /** @class */ (function () {
  81626. function PhysicsImpostor(object, type, _options, _scene) {
  81627. if (_options === void 0) { _options = { mass: 0 }; }
  81628. var _this = this;
  81629. this.object = object;
  81630. this.type = type;
  81631. this._options = _options;
  81632. this._scene = _scene;
  81633. this._bodyUpdateRequired = false;
  81634. this._onBeforePhysicsStepCallbacks = new Array();
  81635. this._onAfterPhysicsStepCallbacks = new Array();
  81636. this._onPhysicsCollideCallbacks = [];
  81637. this._deltaPosition = BABYLON.Vector3.Zero();
  81638. this._isDisposed = false;
  81639. //temp variables for parent rotation calculations
  81640. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  81641. this._tmpQuat = new BABYLON.Quaternion();
  81642. this._tmpQuat2 = new BABYLON.Quaternion();
  81643. /**
  81644. * this function is executed by the physics engine.
  81645. */
  81646. this.beforeStep = function () {
  81647. if (!_this._physicsEngine) {
  81648. return;
  81649. }
  81650. _this.object.translate(_this._deltaPosition, -1);
  81651. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  81652. _this.object.computeWorldMatrix(false);
  81653. if (_this.object.parent && _this.object.rotationQuaternion) {
  81654. _this.getParentsRotation();
  81655. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  81656. }
  81657. else {
  81658. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  81659. }
  81660. if (!_this._options.disableBidirectionalTransformation) {
  81661. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  81662. }
  81663. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  81664. func(_this);
  81665. });
  81666. };
  81667. /**
  81668. * this function is executed by the physics engine.
  81669. */
  81670. this.afterStep = function () {
  81671. if (!_this._physicsEngine) {
  81672. return;
  81673. }
  81674. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  81675. func(_this);
  81676. });
  81677. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  81678. // object has now its world rotation. needs to be converted to local.
  81679. if (_this.object.parent && _this.object.rotationQuaternion) {
  81680. _this.getParentsRotation();
  81681. _this._tmpQuat.conjugateInPlace();
  81682. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  81683. }
  81684. // take the position set and make it the absolute position of this object.
  81685. _this.object.setAbsolutePosition(_this.object.position);
  81686. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  81687. _this.object.translate(_this._deltaPosition, 1);
  81688. };
  81689. /**
  81690. * Legacy collision detection event support
  81691. */
  81692. this.onCollideEvent = null;
  81693. //event and body object due to cannon's event-based architecture.
  81694. this.onCollide = function (e) {
  81695. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  81696. return;
  81697. }
  81698. if (!_this._physicsEngine) {
  81699. return;
  81700. }
  81701. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  81702. if (otherImpostor) {
  81703. // Legacy collision detection event support
  81704. if (_this.onCollideEvent) {
  81705. _this.onCollideEvent(_this, otherImpostor);
  81706. }
  81707. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  81708. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  81709. }).forEach(function (obj) {
  81710. obj.callback(_this, otherImpostor);
  81711. });
  81712. }
  81713. };
  81714. //sanity check!
  81715. if (!this.object) {
  81716. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  81717. return;
  81718. }
  81719. //legacy support for old syntax.
  81720. if (!this._scene && object.getScene) {
  81721. this._scene = object.getScene();
  81722. }
  81723. if (!this._scene) {
  81724. return;
  81725. }
  81726. this._physicsEngine = this._scene.getPhysicsEngine();
  81727. if (!this._physicsEngine) {
  81728. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  81729. }
  81730. else {
  81731. //set the object's quaternion, if not set
  81732. if (!this.object.rotationQuaternion) {
  81733. if (this.object.rotation) {
  81734. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  81735. }
  81736. else {
  81737. this.object.rotationQuaternion = new BABYLON.Quaternion();
  81738. }
  81739. }
  81740. //default options params
  81741. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  81742. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  81743. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  81744. this._joints = [];
  81745. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  81746. if (!this.object.parent || this._options.ignoreParent) {
  81747. this._init();
  81748. }
  81749. else if (this.object.parent.physicsImpostor) {
  81750. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  81751. }
  81752. }
  81753. }
  81754. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  81755. get: function () {
  81756. return this._isDisposed;
  81757. },
  81758. enumerable: true,
  81759. configurable: true
  81760. });
  81761. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  81762. get: function () {
  81763. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  81764. },
  81765. set: function (value) {
  81766. this.setMass(value);
  81767. },
  81768. enumerable: true,
  81769. configurable: true
  81770. });
  81771. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  81772. get: function () {
  81773. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  81774. },
  81775. set: function (value) {
  81776. if (!this._physicsEngine) {
  81777. return;
  81778. }
  81779. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  81780. },
  81781. enumerable: true,
  81782. configurable: true
  81783. });
  81784. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  81785. get: function () {
  81786. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  81787. },
  81788. set: function (value) {
  81789. if (!this._physicsEngine) {
  81790. return;
  81791. }
  81792. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  81793. },
  81794. enumerable: true,
  81795. configurable: true
  81796. });
  81797. /**
  81798. * This function will completly initialize this impostor.
  81799. * It will create a new body - but only if this mesh has no parent.
  81800. * If it has, this impostor will not be used other than to define the impostor
  81801. * of the child mesh.
  81802. */
  81803. PhysicsImpostor.prototype._init = function () {
  81804. if (!this._physicsEngine) {
  81805. return;
  81806. }
  81807. this._physicsEngine.removeImpostor(this);
  81808. this.physicsBody = null;
  81809. this._parent = this._parent || this._getPhysicsParent();
  81810. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  81811. this._physicsEngine.addImpostor(this);
  81812. }
  81813. };
  81814. PhysicsImpostor.prototype._getPhysicsParent = function () {
  81815. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  81816. var parentMesh = this.object.parent;
  81817. return parentMesh.physicsImpostor;
  81818. }
  81819. return null;
  81820. };
  81821. /**
  81822. * Should a new body be generated.
  81823. */
  81824. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  81825. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  81826. };
  81827. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  81828. this.forceUpdate();
  81829. };
  81830. /**
  81831. * Force a regeneration of this or the parent's impostor's body.
  81832. * Use under cautious - This will remove all joints already implemented.
  81833. */
  81834. PhysicsImpostor.prototype.forceUpdate = function () {
  81835. this._init();
  81836. if (this.parent && !this._options.ignoreParent) {
  81837. this.parent.forceUpdate();
  81838. }
  81839. };
  81840. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  81841. /*public get mesh(): AbstractMesh {
  81842. return this._mesh;
  81843. }*/
  81844. /**
  81845. * Gets the body that holds this impostor. Either its own, or its parent.
  81846. */
  81847. get: function () {
  81848. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  81849. },
  81850. /**
  81851. * Set the physics body. Used mainly by the physics engine/plugin
  81852. */
  81853. set: function (physicsBody) {
  81854. if (this._physicsBody && this._physicsEngine) {
  81855. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  81856. }
  81857. this._physicsBody = physicsBody;
  81858. this.resetUpdateFlags();
  81859. },
  81860. enumerable: true,
  81861. configurable: true
  81862. });
  81863. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  81864. get: function () {
  81865. return !this._options.ignoreParent && this._parent ? this._parent : null;
  81866. },
  81867. set: function (value) {
  81868. this._parent = value;
  81869. },
  81870. enumerable: true,
  81871. configurable: true
  81872. });
  81873. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  81874. this._bodyUpdateRequired = false;
  81875. };
  81876. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  81877. if (this.object.getBoundingInfo) {
  81878. var q = this.object.rotationQuaternion;
  81879. //reset rotation
  81880. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  81881. //calculate the world matrix with no rotation
  81882. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  81883. var boundingInfo = this.object.getBoundingInfo();
  81884. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  81885. //bring back the rotation
  81886. this.object.rotationQuaternion = q;
  81887. //calculate the world matrix with the new rotation
  81888. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  81889. return size;
  81890. }
  81891. else {
  81892. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  81893. }
  81894. };
  81895. PhysicsImpostor.prototype.getObjectCenter = function () {
  81896. if (this.object.getBoundingInfo) {
  81897. var boundingInfo = this.object.getBoundingInfo();
  81898. return boundingInfo.boundingBox.centerWorld;
  81899. }
  81900. else {
  81901. return this.object.position;
  81902. }
  81903. };
  81904. /**
  81905. * Get a specific parametes from the options parameter.
  81906. */
  81907. PhysicsImpostor.prototype.getParam = function (paramName) {
  81908. return this._options[paramName];
  81909. };
  81910. /**
  81911. * Sets a specific parameter in the options given to the physics plugin
  81912. */
  81913. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  81914. this._options[paramName] = value;
  81915. this._bodyUpdateRequired = true;
  81916. };
  81917. /**
  81918. * Specifically change the body's mass option. Won't recreate the physics body object
  81919. */
  81920. PhysicsImpostor.prototype.setMass = function (mass) {
  81921. if (this.getParam("mass") !== mass) {
  81922. this.setParam("mass", mass);
  81923. }
  81924. if (this._physicsEngine) {
  81925. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  81926. }
  81927. };
  81928. PhysicsImpostor.prototype.getLinearVelocity = function () {
  81929. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  81930. };
  81931. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  81932. if (this._physicsEngine) {
  81933. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  81934. }
  81935. };
  81936. PhysicsImpostor.prototype.getAngularVelocity = function () {
  81937. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  81938. };
  81939. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  81940. if (this._physicsEngine) {
  81941. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  81942. }
  81943. };
  81944. /**
  81945. * Execute a function with the physics plugin native code.
  81946. * Provide a function the will have two variables - the world object and the physics body object.
  81947. */
  81948. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  81949. if (this._physicsEngine) {
  81950. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  81951. }
  81952. };
  81953. /**
  81954. * Register a function that will be executed before the physics world is stepping forward.
  81955. */
  81956. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  81957. this._onBeforePhysicsStepCallbacks.push(func);
  81958. };
  81959. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  81960. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  81961. if (index > -1) {
  81962. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  81963. }
  81964. else {
  81965. BABYLON.Tools.Warn("Function to remove was not found");
  81966. }
  81967. };
  81968. /**
  81969. * Register a function that will be executed after the physics step
  81970. */
  81971. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  81972. this._onAfterPhysicsStepCallbacks.push(func);
  81973. };
  81974. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  81975. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  81976. if (index > -1) {
  81977. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  81978. }
  81979. else {
  81980. BABYLON.Tools.Warn("Function to remove was not found");
  81981. }
  81982. };
  81983. /**
  81984. * register a function that will be executed when this impostor collides against a different body.
  81985. */
  81986. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  81987. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  81988. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  81989. };
  81990. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  81991. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  81992. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  81993. if (index > -1) {
  81994. this._onPhysicsCollideCallbacks.splice(index, 1);
  81995. }
  81996. else {
  81997. BABYLON.Tools.Warn("Function to remove was not found");
  81998. }
  81999. };
  82000. PhysicsImpostor.prototype.getParentsRotation = function () {
  82001. var parent = this.object.parent;
  82002. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  82003. while (parent) {
  82004. if (parent.rotationQuaternion) {
  82005. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  82006. }
  82007. else {
  82008. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  82009. }
  82010. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  82011. parent = parent.parent;
  82012. }
  82013. return this._tmpQuat;
  82014. };
  82015. /**
  82016. * Apply a force
  82017. */
  82018. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  82019. if (this._physicsEngine) {
  82020. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  82021. }
  82022. return this;
  82023. };
  82024. /**
  82025. * Apply an impulse
  82026. */
  82027. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  82028. if (this._physicsEngine) {
  82029. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  82030. }
  82031. return this;
  82032. };
  82033. /**
  82034. * A help function to create a joint.
  82035. */
  82036. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  82037. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  82038. this.addJoint(otherImpostor, joint);
  82039. return this;
  82040. };
  82041. /**
  82042. * Add a joint to this impostor with a different impostor.
  82043. */
  82044. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  82045. this._joints.push({
  82046. otherImpostor: otherImpostor,
  82047. joint: joint
  82048. });
  82049. if (this._physicsEngine) {
  82050. this._physicsEngine.addJoint(this, otherImpostor, joint);
  82051. }
  82052. return this;
  82053. };
  82054. /**
  82055. * Will keep this body still, in a sleep mode.
  82056. */
  82057. PhysicsImpostor.prototype.sleep = function () {
  82058. if (this._physicsEngine) {
  82059. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  82060. }
  82061. return this;
  82062. };
  82063. /**
  82064. * Wake the body up.
  82065. */
  82066. PhysicsImpostor.prototype.wakeUp = function () {
  82067. if (this._physicsEngine) {
  82068. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  82069. }
  82070. return this;
  82071. };
  82072. PhysicsImpostor.prototype.clone = function (newObject) {
  82073. if (!newObject)
  82074. return null;
  82075. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  82076. };
  82077. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  82078. var _this = this;
  82079. //no dispose if no physics engine is available.
  82080. if (!this._physicsEngine) {
  82081. return;
  82082. }
  82083. this._joints.forEach(function (j) {
  82084. if (_this._physicsEngine) {
  82085. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  82086. }
  82087. });
  82088. //dispose the physics body
  82089. this._physicsEngine.removeImpostor(this);
  82090. if (this.parent) {
  82091. this.parent.forceUpdate();
  82092. }
  82093. else {
  82094. /*this._object.getChildMeshes().forEach(function(mesh) {
  82095. if (mesh.physicsImpostor) {
  82096. if (disposeChildren) {
  82097. mesh.physicsImpostor.dispose();
  82098. mesh.physicsImpostor = null;
  82099. }
  82100. }
  82101. })*/
  82102. }
  82103. this._isDisposed = true;
  82104. };
  82105. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  82106. this._deltaPosition.copyFrom(position);
  82107. };
  82108. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  82109. if (!this._deltaRotation) {
  82110. this._deltaRotation = new BABYLON.Quaternion();
  82111. }
  82112. this._deltaRotation.copyFrom(rotation);
  82113. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  82114. };
  82115. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  82116. if (this._physicsEngine) {
  82117. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  82118. }
  82119. return this;
  82120. };
  82121. PhysicsImpostor.prototype.getRadius = function () {
  82122. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  82123. };
  82124. /**
  82125. * Sync a bone with this impostor
  82126. * @param bone The bone to sync to the impostor.
  82127. * @param boneMesh The mesh that the bone is influencing.
  82128. * @param jointPivot The pivot of the joint / bone in local space.
  82129. * @param distToJoint Optional distance from the impostor to the joint.
  82130. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82131. */
  82132. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  82133. var tempVec = PhysicsImpostor._tmpVecs[0];
  82134. var mesh = this.object;
  82135. if (mesh.rotationQuaternion) {
  82136. if (adjustRotation) {
  82137. var tempQuat = PhysicsImpostor._tmpQuat;
  82138. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  82139. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  82140. }
  82141. else {
  82142. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  82143. }
  82144. }
  82145. tempVec.x = 0;
  82146. tempVec.y = 0;
  82147. tempVec.z = 0;
  82148. if (jointPivot) {
  82149. tempVec.x = jointPivot.x;
  82150. tempVec.y = jointPivot.y;
  82151. tempVec.z = jointPivot.z;
  82152. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  82153. if (distToJoint === undefined || distToJoint === null) {
  82154. distToJoint = jointPivot.length();
  82155. }
  82156. tempVec.x *= distToJoint;
  82157. tempVec.y *= distToJoint;
  82158. tempVec.z *= distToJoint;
  82159. }
  82160. if (bone.getParent()) {
  82161. tempVec.addInPlace(mesh.getAbsolutePosition());
  82162. bone.setAbsolutePosition(tempVec, boneMesh);
  82163. }
  82164. else {
  82165. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  82166. boneMesh.position.x -= tempVec.x;
  82167. boneMesh.position.y -= tempVec.y;
  82168. boneMesh.position.z -= tempVec.z;
  82169. }
  82170. };
  82171. /**
  82172. * Sync impostor to a bone
  82173. * @param bone The bone that the impostor will be synced to.
  82174. * @param boneMesh The mesh that the bone is influencing.
  82175. * @param jointPivot The pivot of the joint / bone in local space.
  82176. * @param distToJoint Optional distance from the impostor to the joint.
  82177. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82178. * @param boneAxis Optional vector3 axis the bone is aligned with
  82179. */
  82180. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  82181. var mesh = this.object;
  82182. if (mesh.rotationQuaternion) {
  82183. if (adjustRotation) {
  82184. var tempQuat = PhysicsImpostor._tmpQuat;
  82185. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  82186. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  82187. }
  82188. else {
  82189. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  82190. }
  82191. }
  82192. var pos = PhysicsImpostor._tmpVecs[0];
  82193. var boneDir = PhysicsImpostor._tmpVecs[1];
  82194. if (!boneAxis) {
  82195. boneAxis = PhysicsImpostor._tmpVecs[2];
  82196. boneAxis.x = 0;
  82197. boneAxis.y = 1;
  82198. boneAxis.z = 0;
  82199. }
  82200. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  82201. bone.getAbsolutePositionToRef(boneMesh, pos);
  82202. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  82203. distToJoint = jointPivot.length();
  82204. }
  82205. if (distToJoint !== undefined && distToJoint !== null) {
  82206. pos.x += boneDir.x * distToJoint;
  82207. pos.y += boneDir.y * distToJoint;
  82208. pos.z += boneDir.z * distToJoint;
  82209. }
  82210. mesh.setAbsolutePosition(pos);
  82211. };
  82212. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  82213. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  82214. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82215. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  82216. //Impostor types
  82217. PhysicsImpostor.NoImpostor = 0;
  82218. PhysicsImpostor.SphereImpostor = 1;
  82219. PhysicsImpostor.BoxImpostor = 2;
  82220. PhysicsImpostor.PlaneImpostor = 3;
  82221. PhysicsImpostor.MeshImpostor = 4;
  82222. PhysicsImpostor.CylinderImpostor = 7;
  82223. PhysicsImpostor.ParticleImpostor = 8;
  82224. PhysicsImpostor.HeightmapImpostor = 9;
  82225. return PhysicsImpostor;
  82226. }());
  82227. BABYLON.PhysicsImpostor = PhysicsImpostor;
  82228. })(BABYLON || (BABYLON = {}));
  82229. //# sourceMappingURL=babylon.physicsImpostor.js.map
  82230. var BABYLON;
  82231. (function (BABYLON) {
  82232. var PhysicsEngine = /** @class */ (function () {
  82233. function PhysicsEngine(gravity, _physicsPlugin) {
  82234. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  82235. this._physicsPlugin = _physicsPlugin;
  82236. //new methods and parameters
  82237. this._impostors = [];
  82238. this._joints = [];
  82239. if (!this._physicsPlugin.isSupported()) {
  82240. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  82241. + "Please make sure it is included.");
  82242. }
  82243. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  82244. this.setGravity(gravity);
  82245. this.setTimeStep();
  82246. }
  82247. PhysicsEngine.prototype.setGravity = function (gravity) {
  82248. this.gravity = gravity;
  82249. this._physicsPlugin.setGravity(this.gravity);
  82250. };
  82251. /**
  82252. * Set the time step of the physics engine.
  82253. * default is 1/60.
  82254. * To slow it down, enter 1/600 for example.
  82255. * To speed it up, 1/30
  82256. * @param {number} newTimeStep the new timestep to apply to this world.
  82257. */
  82258. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  82259. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  82260. this._physicsPlugin.setTimeStep(newTimeStep);
  82261. };
  82262. /**
  82263. * Get the time step of the physics engine.
  82264. */
  82265. PhysicsEngine.prototype.getTimeStep = function () {
  82266. return this._physicsPlugin.getTimeStep();
  82267. };
  82268. PhysicsEngine.prototype.dispose = function () {
  82269. this._impostors.forEach(function (impostor) {
  82270. impostor.dispose();
  82271. });
  82272. this._physicsPlugin.dispose();
  82273. };
  82274. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  82275. return this._physicsPlugin.name;
  82276. };
  82277. /**
  82278. * Adding a new impostor for the impostor tracking.
  82279. * This will be done by the impostor itself.
  82280. * @param {PhysicsImpostor} impostor the impostor to add
  82281. */
  82282. PhysicsEngine.prototype.addImpostor = function (impostor) {
  82283. impostor.uniqueId = this._impostors.push(impostor);
  82284. //if no parent, generate the body
  82285. if (!impostor.parent) {
  82286. this._physicsPlugin.generatePhysicsBody(impostor);
  82287. }
  82288. };
  82289. /**
  82290. * Remove an impostor from the engine.
  82291. * This impostor and its mesh will not longer be updated by the physics engine.
  82292. * @param {PhysicsImpostor} impostor the impostor to remove
  82293. */
  82294. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  82295. var index = this._impostors.indexOf(impostor);
  82296. if (index > -1) {
  82297. var removed = this._impostors.splice(index, 1);
  82298. //Is it needed?
  82299. if (removed.length) {
  82300. //this will also remove it from the world.
  82301. removed[0].physicsBody = null;
  82302. }
  82303. }
  82304. };
  82305. /**
  82306. * Add a joint to the physics engine
  82307. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  82308. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  82309. * @param {PhysicsJoint} the joint that will connect both impostors.
  82310. */
  82311. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  82312. var impostorJoint = {
  82313. mainImpostor: mainImpostor,
  82314. connectedImpostor: connectedImpostor,
  82315. joint: joint
  82316. };
  82317. joint.physicsPlugin = this._physicsPlugin;
  82318. this._joints.push(impostorJoint);
  82319. this._physicsPlugin.generateJoint(impostorJoint);
  82320. };
  82321. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  82322. var matchingJoints = this._joints.filter(function (impostorJoint) {
  82323. return (impostorJoint.connectedImpostor === connectedImpostor
  82324. && impostorJoint.joint === joint
  82325. && impostorJoint.mainImpostor === mainImpostor);
  82326. });
  82327. if (matchingJoints.length) {
  82328. this._physicsPlugin.removeJoint(matchingJoints[0]);
  82329. //TODO remove it from the list as well
  82330. }
  82331. };
  82332. /**
  82333. * Called by the scene. no need to call it.
  82334. */
  82335. PhysicsEngine.prototype._step = function (delta) {
  82336. var _this = this;
  82337. //check if any mesh has no body / requires an update
  82338. this._impostors.forEach(function (impostor) {
  82339. if (impostor.isBodyInitRequired()) {
  82340. _this._physicsPlugin.generatePhysicsBody(impostor);
  82341. }
  82342. });
  82343. if (delta > 0.1) {
  82344. delta = 0.1;
  82345. }
  82346. else if (delta <= 0) {
  82347. delta = 1.0 / 60.0;
  82348. }
  82349. this._physicsPlugin.executeStep(delta, this._impostors);
  82350. };
  82351. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  82352. return this._physicsPlugin;
  82353. };
  82354. PhysicsEngine.prototype.getImpostors = function () {
  82355. return this._impostors;
  82356. };
  82357. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  82358. for (var i = 0; i < this._impostors.length; ++i) {
  82359. if (this._impostors[i].object === object) {
  82360. return this._impostors[i];
  82361. }
  82362. }
  82363. return null;
  82364. };
  82365. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  82366. for (var i = 0; i < this._impostors.length; ++i) {
  82367. if (this._impostors[i].physicsBody === body) {
  82368. return this._impostors[i];
  82369. }
  82370. }
  82371. return null;
  82372. };
  82373. // Statics
  82374. PhysicsEngine.Epsilon = 0.001;
  82375. return PhysicsEngine;
  82376. }());
  82377. BABYLON.PhysicsEngine = PhysicsEngine;
  82378. })(BABYLON || (BABYLON = {}));
  82379. //# sourceMappingURL=babylon.physicsEngine.js.map
  82380. var BABYLON;
  82381. (function (BABYLON) {
  82382. var PhysicsHelper = /** @class */ (function () {
  82383. function PhysicsHelper(scene) {
  82384. this._scene = scene;
  82385. this._physicsEngine = this._scene.getPhysicsEngine();
  82386. if (!this._physicsEngine) {
  82387. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  82388. }
  82389. }
  82390. /**
  82391. * @param {Vector3} origin the origin of the explosion
  82392. * @param {number} radius the explosion radius
  82393. * @param {number} strength the explosion strength
  82394. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82395. */
  82396. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  82397. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82398. if (!this._physicsEngine) {
  82399. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  82400. return null;
  82401. }
  82402. var impostors = this._physicsEngine.getImpostors();
  82403. if (impostors.length === 0) {
  82404. return null;
  82405. }
  82406. var event = new PhysicsRadialExplosionEvent(this._scene);
  82407. impostors.forEach(function (impostor) {
  82408. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82409. if (!impostorForceAndContactPoint) {
  82410. return;
  82411. }
  82412. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82413. });
  82414. event.dispose(false);
  82415. return event;
  82416. };
  82417. /**
  82418. * @param {Vector3} origin the origin of the explosion
  82419. * @param {number} radius the explosion radius
  82420. * @param {number} strength the explosion strength
  82421. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82422. */
  82423. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  82424. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82425. if (!this._physicsEngine) {
  82426. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82427. return null;
  82428. }
  82429. var impostors = this._physicsEngine.getImpostors();
  82430. if (impostors.length === 0) {
  82431. return null;
  82432. }
  82433. var event = new PhysicsRadialExplosionEvent(this._scene);
  82434. impostors.forEach(function (impostor) {
  82435. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82436. if (!impostorForceAndContactPoint) {
  82437. return;
  82438. }
  82439. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82440. });
  82441. event.dispose(false);
  82442. return event;
  82443. };
  82444. /**
  82445. * @param {Vector3} origin the origin of the explosion
  82446. * @param {number} radius the explosion radius
  82447. * @param {number} strength the explosion strength
  82448. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82449. */
  82450. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  82451. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82452. if (!this._physicsEngine) {
  82453. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82454. return null;
  82455. }
  82456. var impostors = this._physicsEngine.getImpostors();
  82457. if (impostors.length === 0) {
  82458. return null;
  82459. }
  82460. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  82461. event.dispose(false);
  82462. return event;
  82463. };
  82464. /**
  82465. * @param {Vector3} origin the origin of the updraft
  82466. * @param {number} radius the radius of the updraft
  82467. * @param {number} strength the strength of the updraft
  82468. * @param {number} height the height of the updraft
  82469. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  82470. */
  82471. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  82472. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  82473. if (!this._physicsEngine) {
  82474. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82475. return null;
  82476. }
  82477. if (this._physicsEngine.getImpostors().length === 0) {
  82478. return null;
  82479. }
  82480. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  82481. event.dispose(false);
  82482. return event;
  82483. };
  82484. /**
  82485. * @param {Vector3} origin the of the vortex
  82486. * @param {number} radius the radius of the vortex
  82487. * @param {number} strength the strength of the vortex
  82488. * @param {number} height the height of the vortex
  82489. */
  82490. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  82491. if (!this._physicsEngine) {
  82492. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82493. return null;
  82494. }
  82495. if (this._physicsEngine.getImpostors().length === 0) {
  82496. return null;
  82497. }
  82498. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  82499. event.dispose(false);
  82500. return event;
  82501. };
  82502. return PhysicsHelper;
  82503. }());
  82504. BABYLON.PhysicsHelper = PhysicsHelper;
  82505. /***** Radial explosion *****/
  82506. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  82507. function PhysicsRadialExplosionEvent(scene) {
  82508. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  82509. this._rays = [];
  82510. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  82511. this._scene = scene;
  82512. }
  82513. /**
  82514. * Returns the data related to the radial explosion event (sphere & rays).
  82515. * @returns {PhysicsRadialExplosionEventData}
  82516. */
  82517. PhysicsRadialExplosionEvent.prototype.getData = function () {
  82518. this._dataFetched = true;
  82519. return {
  82520. sphere: this._sphere,
  82521. rays: this._rays,
  82522. };
  82523. };
  82524. /**
  82525. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  82526. * @param impostor
  82527. * @param {Vector3} origin the origin of the explosion
  82528. * @param {number} radius the explosion radius
  82529. * @param {number} strength the explosion strength
  82530. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  82531. * @returns {Nullable<PhysicsForceAndContactPoint>}
  82532. */
  82533. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  82534. if (impostor.mass === 0) {
  82535. return null;
  82536. }
  82537. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  82538. return null;
  82539. }
  82540. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82541. return null;
  82542. }
  82543. var impostorObjectCenter = impostor.getObjectCenter();
  82544. var direction = impostorObjectCenter.subtract(origin);
  82545. var ray = new BABYLON.Ray(origin, direction, radius);
  82546. this._rays.push(ray);
  82547. var hit = ray.intersectsMesh(impostor.object);
  82548. var contactPoint = hit.pickedPoint;
  82549. if (!contactPoint) {
  82550. return null;
  82551. }
  82552. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  82553. if (distanceFromOrigin > radius) {
  82554. return null;
  82555. }
  82556. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  82557. ? strength
  82558. : strength * (1 - (distanceFromOrigin / radius));
  82559. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82560. return { force: force, contactPoint: contactPoint };
  82561. };
  82562. /**
  82563. * Disposes the sphere.
  82564. * @param {bolean} force
  82565. */
  82566. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  82567. var _this = this;
  82568. if (force === void 0) { force = true; }
  82569. if (force) {
  82570. this._sphere.dispose();
  82571. }
  82572. else {
  82573. setTimeout(function () {
  82574. if (!_this._dataFetched) {
  82575. _this._sphere.dispose();
  82576. }
  82577. }, 0);
  82578. }
  82579. };
  82580. /*** Helpers ***/
  82581. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  82582. if (!this._sphere) {
  82583. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  82584. this._sphere.isVisible = false;
  82585. }
  82586. };
  82587. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  82588. var impostorObject = impostor.object;
  82589. this._prepareSphere();
  82590. this._sphere.position = origin;
  82591. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  82592. this._sphere._updateBoundingInfo();
  82593. this._sphere.computeWorldMatrix(true);
  82594. return this._sphere.intersectsMesh(impostorObject, true);
  82595. };
  82596. return PhysicsRadialExplosionEvent;
  82597. }());
  82598. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  82599. /***** Gravitational Field *****/
  82600. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  82601. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  82602. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82603. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82604. this._physicsHelper = physicsHelper;
  82605. this._scene = scene;
  82606. this._origin = origin;
  82607. this._radius = radius;
  82608. this._strength = strength;
  82609. this._falloff = falloff;
  82610. this._tickCallback = this._tick.bind(this);
  82611. }
  82612. /**
  82613. * Returns the data related to the gravitational field event (sphere).
  82614. * @returns {PhysicsGravitationalFieldEventData}
  82615. */
  82616. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  82617. this._dataFetched = true;
  82618. return {
  82619. sphere: this._sphere,
  82620. };
  82621. };
  82622. /**
  82623. * Enables the gravitational field.
  82624. */
  82625. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  82626. this._tickCallback.call(this);
  82627. this._scene.registerBeforeRender(this._tickCallback);
  82628. };
  82629. /**
  82630. * Disables the gravitational field.
  82631. */
  82632. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  82633. this._scene.unregisterBeforeRender(this._tickCallback);
  82634. };
  82635. /**
  82636. * Disposes the sphere.
  82637. * @param {bolean} force
  82638. */
  82639. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  82640. var _this = this;
  82641. if (force === void 0) { force = true; }
  82642. if (force) {
  82643. this._sphere.dispose();
  82644. }
  82645. else {
  82646. setTimeout(function () {
  82647. if (!_this._dataFetched) {
  82648. _this._sphere.dispose();
  82649. }
  82650. }, 0);
  82651. }
  82652. };
  82653. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  82654. // Since the params won't change, we fetch the event only once
  82655. if (this._sphere) {
  82656. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82657. }
  82658. else {
  82659. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82660. if (radialExplosionEvent) {
  82661. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  82662. }
  82663. }
  82664. };
  82665. return PhysicsGravitationalFieldEvent;
  82666. }());
  82667. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  82668. /***** Updraft *****/
  82669. var PhysicsUpdraftEvent = /** @class */ (function () {
  82670. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  82671. this._scene = _scene;
  82672. this._origin = _origin;
  82673. this._radius = _radius;
  82674. this._strength = _strength;
  82675. this._height = _height;
  82676. this._updraftMode = _updraftMode;
  82677. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82678. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  82679. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82680. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82681. this._physicsEngine = this._scene.getPhysicsEngine();
  82682. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82683. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82684. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82685. this._originDirection = this._origin.subtract(this._originTop).normalize();
  82686. }
  82687. this._tickCallback = this._tick.bind(this);
  82688. }
  82689. /**
  82690. * Returns the data related to the updraft event (cylinder).
  82691. * @returns {PhysicsUpdraftEventData}
  82692. */
  82693. PhysicsUpdraftEvent.prototype.getData = function () {
  82694. this._dataFetched = true;
  82695. return {
  82696. cylinder: this._cylinder,
  82697. };
  82698. };
  82699. /**
  82700. * Enables the updraft.
  82701. */
  82702. PhysicsUpdraftEvent.prototype.enable = function () {
  82703. this._tickCallback.call(this);
  82704. this._scene.registerBeforeRender(this._tickCallback);
  82705. };
  82706. /**
  82707. * Disables the cortex.
  82708. */
  82709. PhysicsUpdraftEvent.prototype.disable = function () {
  82710. this._scene.unregisterBeforeRender(this._tickCallback);
  82711. };
  82712. /**
  82713. * Disposes the sphere.
  82714. * @param {bolean} force
  82715. */
  82716. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  82717. var _this = this;
  82718. if (force === void 0) { force = true; }
  82719. if (force) {
  82720. this._cylinder.dispose();
  82721. }
  82722. else {
  82723. setTimeout(function () {
  82724. if (!_this._dataFetched) {
  82725. _this._cylinder.dispose();
  82726. }
  82727. }, 0);
  82728. }
  82729. };
  82730. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82731. if (impostor.mass === 0) {
  82732. return null;
  82733. }
  82734. if (!this._intersectsWithCylinder(impostor)) {
  82735. return null;
  82736. }
  82737. var impostorObjectCenter = impostor.getObjectCenter();
  82738. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82739. var direction = this._originDirection;
  82740. }
  82741. else {
  82742. var direction = impostorObjectCenter.subtract(this._originTop);
  82743. }
  82744. var multiplier = this._strength * -1;
  82745. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82746. return { force: force, contactPoint: impostorObjectCenter };
  82747. };
  82748. PhysicsUpdraftEvent.prototype._tick = function () {
  82749. var _this = this;
  82750. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82751. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82752. if (!impostorForceAndContactPoint) {
  82753. return;
  82754. }
  82755. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82756. });
  82757. };
  82758. /*** Helpers ***/
  82759. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  82760. if (!this._cylinder) {
  82761. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  82762. height: this._height,
  82763. diameter: this._radius * 2,
  82764. }, this._scene);
  82765. this._cylinder.isVisible = false;
  82766. }
  82767. };
  82768. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  82769. var impostorObject = impostor.object;
  82770. this._prepareCylinder();
  82771. this._cylinder.position = this._cylinderPosition;
  82772. return this._cylinder.intersectsMesh(impostorObject, true);
  82773. };
  82774. return PhysicsUpdraftEvent;
  82775. }());
  82776. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  82777. /***** Vortex *****/
  82778. var PhysicsVortexEvent = /** @class */ (function () {
  82779. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  82780. this._scene = _scene;
  82781. this._origin = _origin;
  82782. this._radius = _radius;
  82783. this._strength = _strength;
  82784. this._height = _height;
  82785. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82786. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  82787. this._updraftMultiplier = 0.02;
  82788. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82789. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82790. this._physicsEngine = this._scene.getPhysicsEngine();
  82791. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82792. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82793. this._tickCallback = this._tick.bind(this);
  82794. }
  82795. /**
  82796. * Returns the data related to the vortex event (cylinder).
  82797. * @returns {PhysicsVortexEventData}
  82798. */
  82799. PhysicsVortexEvent.prototype.getData = function () {
  82800. this._dataFetched = true;
  82801. return {
  82802. cylinder: this._cylinder,
  82803. };
  82804. };
  82805. /**
  82806. * Enables the vortex.
  82807. */
  82808. PhysicsVortexEvent.prototype.enable = function () {
  82809. this._tickCallback.call(this);
  82810. this._scene.registerBeforeRender(this._tickCallback);
  82811. };
  82812. /**
  82813. * Disables the cortex.
  82814. */
  82815. PhysicsVortexEvent.prototype.disable = function () {
  82816. this._scene.unregisterBeforeRender(this._tickCallback);
  82817. };
  82818. /**
  82819. * Disposes the sphere.
  82820. * @param {bolean} force
  82821. */
  82822. PhysicsVortexEvent.prototype.dispose = function (force) {
  82823. var _this = this;
  82824. if (force === void 0) { force = true; }
  82825. if (force) {
  82826. this._cylinder.dispose();
  82827. }
  82828. else {
  82829. setTimeout(function () {
  82830. if (!_this._dataFetched) {
  82831. _this._cylinder.dispose();
  82832. }
  82833. }, 0);
  82834. }
  82835. };
  82836. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82837. if (impostor.mass === 0) {
  82838. return null;
  82839. }
  82840. if (!this._intersectsWithCylinder(impostor)) {
  82841. return null;
  82842. }
  82843. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82844. return null;
  82845. }
  82846. var impostorObjectCenter = impostor.getObjectCenter();
  82847. 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)
  82848. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  82849. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  82850. var hit = ray.intersectsMesh(impostor.object);
  82851. var contactPoint = hit.pickedPoint;
  82852. if (!contactPoint) {
  82853. return null;
  82854. }
  82855. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  82856. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  82857. var directionToOrigin = contactPoint.normalize();
  82858. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  82859. directionToOrigin = directionToOrigin.negate();
  82860. }
  82861. // TODO: find a more physically based solution
  82862. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  82863. var forceX = directionToOrigin.x * this._strength / 8;
  82864. var forceY = directionToOrigin.y * this._updraftMultiplier;
  82865. var forceZ = directionToOrigin.z * this._strength / 8;
  82866. }
  82867. else {
  82868. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  82869. var forceY = this._originTop.y * this._updraftMultiplier;
  82870. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  82871. }
  82872. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  82873. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  82874. return { force: force, contactPoint: impostorObjectCenter };
  82875. };
  82876. PhysicsVortexEvent.prototype._tick = function () {
  82877. var _this = this;
  82878. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82879. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82880. if (!impostorForceAndContactPoint) {
  82881. return;
  82882. }
  82883. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82884. });
  82885. };
  82886. /*** Helpers ***/
  82887. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  82888. if (!this._cylinder) {
  82889. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  82890. height: this._height,
  82891. diameter: this._radius * 2,
  82892. }, this._scene);
  82893. this._cylinder.isVisible = false;
  82894. }
  82895. };
  82896. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  82897. var impostorObject = impostor.object;
  82898. this._prepareCylinder();
  82899. this._cylinder.position = this._cylinderPosition;
  82900. return this._cylinder.intersectsMesh(impostorObject, true);
  82901. };
  82902. return PhysicsVortexEvent;
  82903. }());
  82904. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  82905. /***** Enums *****/
  82906. /**
  82907. * The strenght of the force in correspondence to the distance of the affected object
  82908. */
  82909. var PhysicsRadialImpulseFalloff;
  82910. (function (PhysicsRadialImpulseFalloff) {
  82911. /** Defines that impulse is constant in strength across it's whole radius */
  82912. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  82913. /** DEfines that impulse gets weaker if it's further from the origin */
  82914. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  82915. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  82916. /**
  82917. * The strenght of the force in correspondence to the distance of the affected object
  82918. */
  82919. var PhysicsUpdraftMode;
  82920. (function (PhysicsUpdraftMode) {
  82921. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  82922. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  82923. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  82924. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  82925. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  82926. })(BABYLON || (BABYLON = {}));
  82927. //# sourceMappingURL=babylon.physicsHelper.js.map
  82928. var BABYLON;
  82929. (function (BABYLON) {
  82930. var CannonJSPlugin = /** @class */ (function () {
  82931. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  82932. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  82933. if (iterations === void 0) { iterations = 10; }
  82934. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  82935. this.name = "CannonJSPlugin";
  82936. this._physicsMaterials = new Array();
  82937. this._fixedTimeStep = 1 / 60;
  82938. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  82939. this.BJSCANNON = CANNON;
  82940. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  82941. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  82942. this._tmpPosition = BABYLON.Vector3.Zero();
  82943. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  82944. this._tmpUnityRotation = new BABYLON.Quaternion();
  82945. if (!this.isSupported()) {
  82946. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  82947. return;
  82948. }
  82949. this._extendNamespace();
  82950. this.world = new this.BJSCANNON.World();
  82951. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  82952. this.world.solver.iterations = iterations;
  82953. }
  82954. CannonJSPlugin.prototype.setGravity = function (gravity) {
  82955. this.world.gravity.copy(gravity);
  82956. };
  82957. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  82958. this._fixedTimeStep = timeStep;
  82959. };
  82960. CannonJSPlugin.prototype.getTimeStep = function () {
  82961. return this._fixedTimeStep;
  82962. };
  82963. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  82964. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  82965. };
  82966. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  82967. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  82968. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  82969. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  82970. };
  82971. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  82972. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  82973. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  82974. impostor.physicsBody.applyForce(impulse, worldPoint);
  82975. };
  82976. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  82977. //parent-child relationship. Does this impostor has a parent impostor?
  82978. if (impostor.parent) {
  82979. if (impostor.physicsBody) {
  82980. this.removePhysicsBody(impostor);
  82981. //TODO is that needed?
  82982. impostor.forceUpdate();
  82983. }
  82984. return;
  82985. }
  82986. //should a new body be created for this impostor?
  82987. if (impostor.isBodyInitRequired()) {
  82988. var shape = this._createShape(impostor);
  82989. //unregister events, if body is being changed
  82990. var oldBody = impostor.physicsBody;
  82991. if (oldBody) {
  82992. this.removePhysicsBody(impostor);
  82993. }
  82994. //create the body and material
  82995. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  82996. var bodyCreationObject = {
  82997. mass: impostor.getParam("mass"),
  82998. material: material
  82999. };
  83000. // A simple extend, in case native options were used.
  83001. var nativeOptions = impostor.getParam("nativeOptions");
  83002. for (var key in nativeOptions) {
  83003. if (nativeOptions.hasOwnProperty(key)) {
  83004. bodyCreationObject[key] = nativeOptions[key];
  83005. }
  83006. }
  83007. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  83008. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  83009. this.world.addEventListener("preStep", impostor.beforeStep);
  83010. this.world.addEventListener("postStep", impostor.afterStep);
  83011. impostor.physicsBody.addShape(shape);
  83012. this.world.add(impostor.physicsBody);
  83013. //try to keep the body moving in the right direction by taking old properties.
  83014. //Should be tested!
  83015. if (oldBody) {
  83016. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  83017. impostor.physicsBody[param].copy(oldBody[param]);
  83018. });
  83019. }
  83020. this._processChildMeshes(impostor);
  83021. }
  83022. //now update the body's transformation
  83023. this._updatePhysicsBodyTransformation(impostor);
  83024. };
  83025. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  83026. var _this = this;
  83027. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  83028. var currentRotation = mainImpostor.object.rotationQuaternion;
  83029. if (meshChildren.length) {
  83030. var processMesh = function (localPosition, mesh) {
  83031. if (!currentRotation || !mesh.rotationQuaternion) {
  83032. return;
  83033. }
  83034. var childImpostor = mesh.getPhysicsImpostor();
  83035. if (childImpostor) {
  83036. var parent = childImpostor.parent;
  83037. if (parent !== mainImpostor) {
  83038. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  83039. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  83040. if (childImpostor.physicsBody) {
  83041. _this.removePhysicsBody(childImpostor);
  83042. childImpostor.physicsBody = null;
  83043. }
  83044. childImpostor.parent = mainImpostor;
  83045. childImpostor.resetUpdateFlags();
  83046. 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));
  83047. //Add the mass of the children.
  83048. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  83049. }
  83050. }
  83051. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  83052. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  83053. };
  83054. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  83055. }
  83056. };
  83057. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83058. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  83059. this.world.removeEventListener("preStep", impostor.beforeStep);
  83060. this.world.removeEventListener("postStep", impostor.afterStep);
  83061. this.world.remove(impostor.physicsBody);
  83062. };
  83063. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83064. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83065. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83066. if (!mainBody || !connectedBody) {
  83067. return;
  83068. }
  83069. var constraint;
  83070. var jointData = impostorJoint.joint.jointData;
  83071. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  83072. var constraintData = {
  83073. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  83074. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  83075. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  83076. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  83077. maxForce: jointData.nativeParams.maxForce,
  83078. collideConnected: !!jointData.collision
  83079. };
  83080. switch (impostorJoint.joint.type) {
  83081. case BABYLON.PhysicsJoint.HingeJoint:
  83082. case BABYLON.PhysicsJoint.Hinge2Joint:
  83083. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  83084. break;
  83085. case BABYLON.PhysicsJoint.DistanceJoint:
  83086. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  83087. break;
  83088. case BABYLON.PhysicsJoint.SpringJoint:
  83089. var springData = jointData;
  83090. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  83091. restLength: springData.length,
  83092. stiffness: springData.stiffness,
  83093. damping: springData.damping,
  83094. localAnchorA: constraintData.pivotA,
  83095. localAnchorB: constraintData.pivotB
  83096. });
  83097. break;
  83098. case BABYLON.PhysicsJoint.LockJoint:
  83099. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  83100. break;
  83101. case BABYLON.PhysicsJoint.PointToPointJoint:
  83102. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83103. default:
  83104. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  83105. break;
  83106. }
  83107. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  83108. constraint.collideConnected = !!jointData.collision;
  83109. impostorJoint.joint.physicsJoint = constraint;
  83110. //don't add spring as constraint, as it is not one.
  83111. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  83112. this.world.addConstraint(constraint);
  83113. }
  83114. else {
  83115. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  83116. constraint.applyForce();
  83117. });
  83118. }
  83119. };
  83120. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83121. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  83122. };
  83123. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  83124. var index;
  83125. var mat;
  83126. for (index = 0; index < this._physicsMaterials.length; index++) {
  83127. mat = this._physicsMaterials[index];
  83128. if (mat.friction === friction && mat.restitution === restitution) {
  83129. return mat;
  83130. }
  83131. }
  83132. var currentMat = new this.BJSCANNON.Material(name);
  83133. currentMat.friction = friction;
  83134. currentMat.restitution = restitution;
  83135. this._physicsMaterials.push(currentMat);
  83136. return currentMat;
  83137. };
  83138. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  83139. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  83140. };
  83141. CannonJSPlugin.prototype._createShape = function (impostor) {
  83142. var object = impostor.object;
  83143. var returnValue;
  83144. var extendSize = impostor.getObjectExtendSize();
  83145. switch (impostor.type) {
  83146. case BABYLON.PhysicsImpostor.SphereImpostor:
  83147. var radiusX = extendSize.x;
  83148. var radiusY = extendSize.y;
  83149. var radiusZ = extendSize.z;
  83150. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  83151. break;
  83152. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  83153. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83154. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  83155. break;
  83156. case BABYLON.PhysicsImpostor.BoxImpostor:
  83157. var box = extendSize.scale(0.5);
  83158. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  83159. break;
  83160. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83161. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  83162. returnValue = new this.BJSCANNON.Plane();
  83163. break;
  83164. case BABYLON.PhysicsImpostor.MeshImpostor:
  83165. // should transform the vertex data to world coordinates!!
  83166. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  83167. var rawFaces = object.getIndices ? object.getIndices() : [];
  83168. if (!rawVerts)
  83169. return;
  83170. // get only scale! so the object could transform correctly.
  83171. var oldPosition = object.position.clone();
  83172. var oldRotation = object.rotation && object.rotation.clone();
  83173. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  83174. object.position.copyFromFloats(0, 0, 0);
  83175. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83176. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83177. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83178. var transform = object.computeWorldMatrix(true);
  83179. // convert rawVerts to object space
  83180. var temp = new Array();
  83181. var index;
  83182. for (index = 0; index < rawVerts.length; index += 3) {
  83183. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  83184. }
  83185. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  83186. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  83187. //now set back the transformation!
  83188. object.position.copyFrom(oldPosition);
  83189. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  83190. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  83191. break;
  83192. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  83193. var oldPosition2 = object.position.clone();
  83194. var oldRotation2 = object.rotation && object.rotation.clone();
  83195. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  83196. object.position.copyFromFloats(0, 0, 0);
  83197. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83198. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83199. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83200. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  83201. returnValue = this._createHeightmap(object);
  83202. object.position.copyFrom(oldPosition2);
  83203. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  83204. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  83205. object.computeWorldMatrix(true);
  83206. break;
  83207. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83208. returnValue = new this.BJSCANNON.Particle();
  83209. break;
  83210. }
  83211. return returnValue;
  83212. };
  83213. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  83214. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  83215. var transform = object.computeWorldMatrix(true);
  83216. // convert rawVerts to object space
  83217. var temp = new Array();
  83218. var index;
  83219. for (index = 0; index < pos.length; index += 3) {
  83220. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  83221. }
  83222. pos = temp;
  83223. var matrix = new Array();
  83224. //For now pointDepth will not be used and will be automatically calculated.
  83225. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  83226. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  83227. var boundingInfo = object.getBoundingInfo();
  83228. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  83229. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  83230. var elementSize = dim * 2 / arraySize;
  83231. for (var i = 0; i < pos.length; i = i + 3) {
  83232. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  83233. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  83234. var y = -pos[i + 2] + minY;
  83235. if (!matrix[x]) {
  83236. matrix[x] = [];
  83237. }
  83238. if (!matrix[x][z]) {
  83239. matrix[x][z] = y;
  83240. }
  83241. matrix[x][z] = Math.max(y, matrix[x][z]);
  83242. }
  83243. for (var x = 0; x <= arraySize; ++x) {
  83244. if (!matrix[x]) {
  83245. var loc = 1;
  83246. while (!matrix[(x + loc) % arraySize]) {
  83247. loc++;
  83248. }
  83249. matrix[x] = matrix[(x + loc) % arraySize].slice();
  83250. //console.log("missing x", x);
  83251. }
  83252. for (var z = 0; z <= arraySize; ++z) {
  83253. if (!matrix[x][z]) {
  83254. var loc = 1;
  83255. var newValue;
  83256. while (newValue === undefined) {
  83257. newValue = matrix[x][(z + loc++) % arraySize];
  83258. }
  83259. matrix[x][z] = newValue;
  83260. }
  83261. }
  83262. }
  83263. var shape = new this.BJSCANNON.Heightfield(matrix, {
  83264. elementSize: elementSize
  83265. });
  83266. //For future reference, needed for body transformation
  83267. shape.minY = minY;
  83268. return shape;
  83269. };
  83270. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  83271. var object = impostor.object;
  83272. //make sure it is updated...
  83273. object.computeWorldMatrix && object.computeWorldMatrix(true);
  83274. // The delta between the mesh position and the mesh bounding box center
  83275. var bInfo = object.getBoundingInfo();
  83276. if (!bInfo)
  83277. return;
  83278. var center = impostor.getObjectCenter();
  83279. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  83280. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  83281. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  83282. this._tmpPosition.copyFrom(center);
  83283. var quaternion = object.rotationQuaternion;
  83284. if (!quaternion) {
  83285. return;
  83286. }
  83287. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  83288. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  83289. //-90 DEG in X, precalculated
  83290. quaternion = quaternion.multiply(this._minus90X);
  83291. //Invert! (Precalculated, 90 deg in X)
  83292. //No need to clone. this will never change.
  83293. impostor.setDeltaRotation(this._plus90X);
  83294. }
  83295. //If it is a heightfield, if should be centered.
  83296. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  83297. var mesh = object;
  83298. var boundingInfo = mesh.getBoundingInfo();
  83299. //calculate the correct body position:
  83300. var rotationQuaternion = mesh.rotationQuaternion;
  83301. mesh.rotationQuaternion = this._tmpUnityRotation;
  83302. mesh.computeWorldMatrix(true);
  83303. //get original center with no rotation
  83304. var c = center.clone();
  83305. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  83306. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  83307. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  83308. mesh.setPreTransformMatrix(p);
  83309. mesh.computeWorldMatrix(true);
  83310. //calculate the translation
  83311. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  83312. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  83313. //add it inverted to the delta
  83314. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  83315. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  83316. //rotation is back
  83317. mesh.rotationQuaternion = rotationQuaternion;
  83318. mesh.setPreTransformMatrix(oldPivot);
  83319. mesh.computeWorldMatrix(true);
  83320. }
  83321. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  83322. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  83323. //this._tmpPosition.copyFrom(object.position);
  83324. }
  83325. impostor.setDeltaPosition(this._tmpDeltaPosition);
  83326. //Now update the impostor object
  83327. impostor.physicsBody.position.copy(this._tmpPosition);
  83328. impostor.physicsBody.quaternion.copy(quaternion);
  83329. };
  83330. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83331. impostor.object.position.copyFrom(impostor.physicsBody.position);
  83332. if (impostor.object.rotationQuaternion) {
  83333. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  83334. }
  83335. };
  83336. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83337. impostor.physicsBody.position.copy(newPosition);
  83338. impostor.physicsBody.quaternion.copy(newRotation);
  83339. };
  83340. CannonJSPlugin.prototype.isSupported = function () {
  83341. return this.BJSCANNON !== undefined;
  83342. };
  83343. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83344. impostor.physicsBody.velocity.copy(velocity);
  83345. };
  83346. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83347. impostor.physicsBody.angularVelocity.copy(velocity);
  83348. };
  83349. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83350. var v = impostor.physicsBody.velocity;
  83351. if (!v) {
  83352. return null;
  83353. }
  83354. return new BABYLON.Vector3(v.x, v.y, v.z);
  83355. };
  83356. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83357. var v = impostor.physicsBody.angularVelocity;
  83358. if (!v) {
  83359. return null;
  83360. }
  83361. return new BABYLON.Vector3(v.x, v.y, v.z);
  83362. };
  83363. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83364. impostor.physicsBody.mass = mass;
  83365. impostor.physicsBody.updateMassProperties();
  83366. };
  83367. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  83368. return impostor.physicsBody.mass;
  83369. };
  83370. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  83371. return impostor.physicsBody.material.friction;
  83372. };
  83373. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83374. impostor.physicsBody.material.friction = friction;
  83375. };
  83376. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83377. return impostor.physicsBody.material.restitution;
  83378. };
  83379. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83380. impostor.physicsBody.material.restitution = restitution;
  83381. };
  83382. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  83383. impostor.physicsBody.sleep();
  83384. };
  83385. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  83386. impostor.physicsBody.wakeUp();
  83387. };
  83388. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83389. joint.physicsJoint.distance = maxDistance;
  83390. };
  83391. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83392. // if (!motorIndex) {
  83393. // joint.physicsJoint.enableMotor();
  83394. // }
  83395. // }
  83396. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83397. // if (!motorIndex) {
  83398. // joint.physicsJoint.disableMotor();
  83399. // }
  83400. // }
  83401. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83402. if (!motorIndex) {
  83403. joint.physicsJoint.enableMotor();
  83404. joint.physicsJoint.setMotorSpeed(speed);
  83405. if (maxForce) {
  83406. this.setLimit(joint, maxForce);
  83407. }
  83408. }
  83409. };
  83410. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  83411. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  83412. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  83413. };
  83414. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83415. var body = impostor.physicsBody;
  83416. mesh.position.x = body.position.x;
  83417. mesh.position.y = body.position.y;
  83418. mesh.position.z = body.position.z;
  83419. if (mesh.rotationQuaternion) {
  83420. mesh.rotationQuaternion.x = body.quaternion.x;
  83421. mesh.rotationQuaternion.y = body.quaternion.y;
  83422. mesh.rotationQuaternion.z = body.quaternion.z;
  83423. mesh.rotationQuaternion.w = body.quaternion.w;
  83424. }
  83425. };
  83426. CannonJSPlugin.prototype.getRadius = function (impostor) {
  83427. var shape = impostor.physicsBody.shapes[0];
  83428. return shape.boundingSphereRadius;
  83429. };
  83430. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83431. var shape = impostor.physicsBody.shapes[0];
  83432. result.x = shape.halfExtents.x * 2;
  83433. result.y = shape.halfExtents.y * 2;
  83434. result.z = shape.halfExtents.z * 2;
  83435. };
  83436. CannonJSPlugin.prototype.dispose = function () {
  83437. };
  83438. CannonJSPlugin.prototype._extendNamespace = function () {
  83439. //this will force cannon to execute at least one step when using interpolation
  83440. var step_tmp1 = new this.BJSCANNON.Vec3();
  83441. var Engine = this.BJSCANNON;
  83442. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  83443. maxSubSteps = maxSubSteps || 10;
  83444. timeSinceLastCalled = timeSinceLastCalled || 0;
  83445. if (timeSinceLastCalled === 0) {
  83446. this.internalStep(dt);
  83447. this.time += dt;
  83448. }
  83449. else {
  83450. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  83451. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  83452. var t0 = performance.now();
  83453. for (var i = 0; i !== internalSteps; i++) {
  83454. this.internalStep(dt);
  83455. if (performance.now() - t0 > dt * 1000) {
  83456. break;
  83457. }
  83458. }
  83459. this.time += timeSinceLastCalled;
  83460. var h = this.time % dt;
  83461. var h_div_dt = h / dt;
  83462. var interpvelo = step_tmp1;
  83463. var bodies = this.bodies;
  83464. for (var j = 0; j !== bodies.length; j++) {
  83465. var b = bodies[j];
  83466. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  83467. b.position.vsub(b.previousPosition, interpvelo);
  83468. interpvelo.scale(h_div_dt, interpvelo);
  83469. b.position.vadd(interpvelo, b.interpolatedPosition);
  83470. }
  83471. else {
  83472. b.interpolatedPosition.copy(b.position);
  83473. b.interpolatedQuaternion.copy(b.quaternion);
  83474. }
  83475. }
  83476. }
  83477. };
  83478. };
  83479. return CannonJSPlugin;
  83480. }());
  83481. BABYLON.CannonJSPlugin = CannonJSPlugin;
  83482. })(BABYLON || (BABYLON = {}));
  83483. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  83484. var BABYLON;
  83485. (function (BABYLON) {
  83486. var OimoJSPlugin = /** @class */ (function () {
  83487. function OimoJSPlugin(iterations) {
  83488. this.name = "OimoJSPlugin";
  83489. this._tmpImpostorsArray = [];
  83490. this._tmpPositionVector = BABYLON.Vector3.Zero();
  83491. this.BJSOIMO = OIMO;
  83492. this.world = new this.BJSOIMO.World({
  83493. iterations: iterations
  83494. });
  83495. this.world.clear();
  83496. }
  83497. OimoJSPlugin.prototype.setGravity = function (gravity) {
  83498. this.world.gravity.copy(gravity);
  83499. };
  83500. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  83501. this.world.timeStep = timeStep;
  83502. };
  83503. OimoJSPlugin.prototype.getTimeStep = function () {
  83504. return this.world.timeStep;
  83505. };
  83506. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  83507. var _this = this;
  83508. impostors.forEach(function (impostor) {
  83509. impostor.beforeStep();
  83510. });
  83511. this.world.step();
  83512. impostors.forEach(function (impostor) {
  83513. impostor.afterStep();
  83514. //update the ordered impostors array
  83515. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  83516. });
  83517. //check for collisions
  83518. var contact = this.world.contacts;
  83519. while (contact !== null) {
  83520. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  83521. contact = contact.next;
  83522. continue;
  83523. }
  83524. //is this body colliding with any other? get the impostor
  83525. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  83526. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  83527. if (!mainImpostor || !collidingImpostor) {
  83528. contact = contact.next;
  83529. continue;
  83530. }
  83531. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  83532. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  83533. contact = contact.next;
  83534. }
  83535. };
  83536. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83537. var mass = impostor.physicsBody.mass;
  83538. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  83539. };
  83540. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83541. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  83542. this.applyImpulse(impostor, force, contactPoint);
  83543. };
  83544. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83545. var _this = this;
  83546. //parent-child relationship. Does this impostor has a parent impostor?
  83547. if (impostor.parent) {
  83548. if (impostor.physicsBody) {
  83549. this.removePhysicsBody(impostor);
  83550. //TODO is that needed?
  83551. impostor.forceUpdate();
  83552. }
  83553. return;
  83554. }
  83555. if (impostor.isBodyInitRequired()) {
  83556. var bodyConfig = {
  83557. name: impostor.uniqueId,
  83558. //Oimo must have mass, also for static objects.
  83559. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  83560. size: [],
  83561. type: [],
  83562. pos: [],
  83563. posShape: [],
  83564. rot: [],
  83565. rotShape: [],
  83566. move: impostor.getParam("mass") !== 0,
  83567. density: impostor.getParam("mass"),
  83568. friction: impostor.getParam("friction"),
  83569. restitution: impostor.getParam("restitution"),
  83570. //Supporting older versions of Oimo
  83571. world: this.world
  83572. };
  83573. var impostors = [impostor];
  83574. var addToArray = function (parent) {
  83575. if (!parent.getChildMeshes)
  83576. return;
  83577. parent.getChildMeshes().forEach(function (m) {
  83578. if (m.physicsImpostor) {
  83579. impostors.push(m.physicsImpostor);
  83580. //m.physicsImpostor._init();
  83581. }
  83582. });
  83583. };
  83584. addToArray(impostor.object);
  83585. var checkWithEpsilon_1 = function (value) {
  83586. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  83587. };
  83588. impostors.forEach(function (i) {
  83589. if (!i.object.rotationQuaternion) {
  83590. return;
  83591. }
  83592. //get the correct bounding box
  83593. var oldQuaternion = i.object.rotationQuaternion;
  83594. var rot = oldQuaternion.toEulerAngles();
  83595. var extendSize = i.getObjectExtendSize();
  83596. var radToDeg = 57.295779513082320876;
  83597. if (i === impostor) {
  83598. var center = impostor.getObjectCenter();
  83599. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  83600. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  83601. //Can also use Array.prototype.push.apply
  83602. bodyConfig.pos.push(center.x);
  83603. bodyConfig.pos.push(center.y);
  83604. bodyConfig.pos.push(center.z);
  83605. bodyConfig.posShape.push(0, 0, 0);
  83606. //tmp solution
  83607. bodyConfig.rot.push(rot.x * radToDeg);
  83608. bodyConfig.rot.push(rot.y * radToDeg);
  83609. bodyConfig.rot.push(rot.z * radToDeg);
  83610. bodyConfig.rotShape.push(0, 0, 0);
  83611. }
  83612. else {
  83613. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  83614. bodyConfig.posShape.push(localPosition.x);
  83615. bodyConfig.posShape.push(localPosition.y);
  83616. bodyConfig.posShape.push(localPosition.z);
  83617. bodyConfig.pos.push(0, 0, 0);
  83618. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  83619. bodyConfig.rot.push(0);
  83620. bodyConfig.rot.push(0);
  83621. bodyConfig.rot.push(0);
  83622. bodyConfig.rotShape.push(rot.x * radToDeg);
  83623. bodyConfig.rotShape.push(rot.y * radToDeg);
  83624. bodyConfig.rotShape.push(rot.z * radToDeg);
  83625. }
  83626. // register mesh
  83627. switch (i.type) {
  83628. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83629. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  83630. case BABYLON.PhysicsImpostor.SphereImpostor:
  83631. var radiusX = extendSize.x;
  83632. var radiusY = extendSize.y;
  83633. var radiusZ = extendSize.z;
  83634. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  83635. bodyConfig.type.push('sphere');
  83636. //due to the way oimo works with compounds, add 3 times
  83637. bodyConfig.size.push(size);
  83638. bodyConfig.size.push(size);
  83639. bodyConfig.size.push(size);
  83640. break;
  83641. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83642. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  83643. var sizeY = checkWithEpsilon_1(extendSize.y);
  83644. bodyConfig.type.push('cylinder');
  83645. bodyConfig.size.push(sizeX);
  83646. bodyConfig.size.push(sizeY);
  83647. //due to the way oimo works with compounds, add one more value.
  83648. bodyConfig.size.push(sizeY);
  83649. break;
  83650. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83651. case BABYLON.PhysicsImpostor.BoxImpostor:
  83652. default:
  83653. var sizeX = checkWithEpsilon_1(extendSize.x);
  83654. var sizeY = checkWithEpsilon_1(extendSize.y);
  83655. var sizeZ = checkWithEpsilon_1(extendSize.z);
  83656. bodyConfig.type.push('box');
  83657. //if (i === impostor) {
  83658. bodyConfig.size.push(sizeX);
  83659. bodyConfig.size.push(sizeY);
  83660. bodyConfig.size.push(sizeZ);
  83661. //} else {
  83662. // bodyConfig.size.push(0,0,0);
  83663. //}
  83664. break;
  83665. }
  83666. //actually not needed, but hey...
  83667. i.object.rotationQuaternion = oldQuaternion;
  83668. });
  83669. impostor.physicsBody = this.world.add(bodyConfig);
  83670. }
  83671. else {
  83672. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  83673. }
  83674. impostor.setDeltaPosition(this._tmpPositionVector);
  83675. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  83676. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  83677. };
  83678. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83679. //impostor.physicsBody.dispose();
  83680. //Same as : (older oimo versions)
  83681. this.world.removeRigidBody(impostor.physicsBody);
  83682. };
  83683. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83684. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83685. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83686. if (!mainBody || !connectedBody) {
  83687. return;
  83688. }
  83689. var jointData = impostorJoint.joint.jointData;
  83690. var options = jointData.nativeParams || {};
  83691. var type;
  83692. var nativeJointData = {
  83693. body1: mainBody,
  83694. body2: connectedBody,
  83695. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  83696. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  83697. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  83698. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  83699. min: options.min,
  83700. max: options.max,
  83701. collision: options.collision || jointData.collision,
  83702. spring: options.spring,
  83703. //supporting older version of Oimo
  83704. world: this.world
  83705. };
  83706. switch (impostorJoint.joint.type) {
  83707. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83708. type = "jointBall";
  83709. break;
  83710. case BABYLON.PhysicsJoint.SpringJoint:
  83711. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  83712. var springData = jointData;
  83713. nativeJointData.min = springData.length || nativeJointData.min;
  83714. //Max should also be set, just make sure it is at least min
  83715. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  83716. case BABYLON.PhysicsJoint.DistanceJoint:
  83717. type = "jointDistance";
  83718. nativeJointData.max = jointData.maxDistance;
  83719. break;
  83720. case BABYLON.PhysicsJoint.PrismaticJoint:
  83721. type = "jointPrisme";
  83722. break;
  83723. case BABYLON.PhysicsJoint.SliderJoint:
  83724. type = "jointSlide";
  83725. break;
  83726. case BABYLON.PhysicsJoint.WheelJoint:
  83727. type = "jointWheel";
  83728. break;
  83729. case BABYLON.PhysicsJoint.HingeJoint:
  83730. default:
  83731. type = "jointHinge";
  83732. break;
  83733. }
  83734. nativeJointData.type = type;
  83735. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  83736. };
  83737. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83738. //Bug in Oimo prevents us from disposing a joint in the playground
  83739. //joint.joint.physicsJoint.dispose();
  83740. //So we will bruteforce it!
  83741. try {
  83742. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  83743. }
  83744. catch (e) {
  83745. BABYLON.Tools.Warn(e);
  83746. }
  83747. };
  83748. OimoJSPlugin.prototype.isSupported = function () {
  83749. return this.BJSOIMO !== undefined;
  83750. };
  83751. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83752. if (!impostor.physicsBody.sleeping) {
  83753. //TODO check that
  83754. /*if (impostor.physicsBody.shapes.next) {
  83755. var parentShape = this._getLastShape(impostor.physicsBody);
  83756. impostor.object.position.copyFrom(parentShape.position);
  83757. console.log(parentShape.position);
  83758. } else {*/
  83759. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  83760. //}
  83761. if (impostor.object.rotationQuaternion) {
  83762. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  83763. }
  83764. }
  83765. };
  83766. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83767. var body = impostor.physicsBody;
  83768. body.position.copy(newPosition);
  83769. body.orientation.copy(newRotation);
  83770. body.syncShapes();
  83771. body.awake();
  83772. };
  83773. /*private _getLastShape(body: any): any {
  83774. var lastShape = body.shapes;
  83775. while (lastShape.next) {
  83776. lastShape = lastShape.next;
  83777. }
  83778. return lastShape;
  83779. }*/
  83780. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83781. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  83782. };
  83783. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83784. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  83785. };
  83786. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83787. var v = impostor.physicsBody.linearVelocity;
  83788. if (!v) {
  83789. return null;
  83790. }
  83791. return new BABYLON.Vector3(v.x, v.y, v.z);
  83792. };
  83793. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83794. var v = impostor.physicsBody.angularVelocity;
  83795. if (!v) {
  83796. return null;
  83797. }
  83798. return new BABYLON.Vector3(v.x, v.y, v.z);
  83799. };
  83800. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83801. var staticBody = mass === 0;
  83802. //this will actually set the body's density and not its mass.
  83803. //But this is how oimo treats the mass variable.
  83804. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  83805. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  83806. };
  83807. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  83808. return impostor.physicsBody.shapes.density;
  83809. };
  83810. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  83811. return impostor.physicsBody.shapes.friction;
  83812. };
  83813. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83814. impostor.physicsBody.shapes.friction = friction;
  83815. };
  83816. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83817. return impostor.physicsBody.shapes.restitution;
  83818. };
  83819. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83820. impostor.physicsBody.shapes.restitution = restitution;
  83821. };
  83822. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  83823. impostor.physicsBody.sleep();
  83824. };
  83825. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  83826. impostor.physicsBody.awake();
  83827. };
  83828. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83829. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  83830. if (minDistance !== void 0) {
  83831. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  83832. }
  83833. };
  83834. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83835. //TODO separate rotational and transational motors.
  83836. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83837. if (motor) {
  83838. motor.setMotor(speed, maxForce);
  83839. }
  83840. };
  83841. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  83842. //TODO separate rotational and transational motors.
  83843. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83844. if (motor) {
  83845. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  83846. }
  83847. };
  83848. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83849. var body = impostor.physicsBody;
  83850. mesh.position.x = body.position.x;
  83851. mesh.position.y = body.position.y;
  83852. mesh.position.z = body.position.z;
  83853. if (mesh.rotationQuaternion) {
  83854. mesh.rotationQuaternion.x = body.orientation.x;
  83855. mesh.rotationQuaternion.y = body.orientation.y;
  83856. mesh.rotationQuaternion.z = body.orientation.z;
  83857. mesh.rotationQuaternion.w = body.orientation.s;
  83858. }
  83859. };
  83860. OimoJSPlugin.prototype.getRadius = function (impostor) {
  83861. return impostor.physicsBody.shapes.radius;
  83862. };
  83863. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83864. var shape = impostor.physicsBody.shapes;
  83865. result.x = shape.halfWidth * 2;
  83866. result.y = shape.halfHeight * 2;
  83867. result.z = shape.halfDepth * 2;
  83868. };
  83869. OimoJSPlugin.prototype.dispose = function () {
  83870. this.world.clear();
  83871. };
  83872. return OimoJSPlugin;
  83873. }());
  83874. BABYLON.OimoJSPlugin = OimoJSPlugin;
  83875. })(BABYLON || (BABYLON = {}));
  83876. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  83877. var BABYLON;
  83878. (function (BABYLON) {
  83879. /*
  83880. * Based on jsTGALoader - Javascript loader for TGA file
  83881. * By Vincent Thibault
  83882. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  83883. */
  83884. var TGATools = /** @class */ (function () {
  83885. function TGATools() {
  83886. }
  83887. TGATools.GetTGAHeader = function (data) {
  83888. var offset = 0;
  83889. var header = {
  83890. id_length: data[offset++],
  83891. colormap_type: data[offset++],
  83892. image_type: data[offset++],
  83893. colormap_index: data[offset++] | data[offset++] << 8,
  83894. colormap_length: data[offset++] | data[offset++] << 8,
  83895. colormap_size: data[offset++],
  83896. origin: [
  83897. data[offset++] | data[offset++] << 8,
  83898. data[offset++] | data[offset++] << 8
  83899. ],
  83900. width: data[offset++] | data[offset++] << 8,
  83901. height: data[offset++] | data[offset++] << 8,
  83902. pixel_size: data[offset++],
  83903. flags: data[offset++]
  83904. };
  83905. return header;
  83906. };
  83907. TGATools.UploadContent = function (gl, data) {
  83908. // Not enough data to contain header ?
  83909. if (data.length < 19) {
  83910. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  83911. return;
  83912. }
  83913. // Read Header
  83914. var offset = 18;
  83915. var header = TGATools.GetTGAHeader(data);
  83916. // Assume it's a valid Targa file.
  83917. if (header.id_length + offset > data.length) {
  83918. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  83919. return;
  83920. }
  83921. // Skip not needed data
  83922. offset += header.id_length;
  83923. var use_rle = false;
  83924. var use_pal = false;
  83925. var use_grey = false;
  83926. // Get some informations.
  83927. switch (header.image_type) {
  83928. case TGATools._TYPE_RLE_INDEXED:
  83929. use_rle = true;
  83930. case TGATools._TYPE_INDEXED:
  83931. use_pal = true;
  83932. break;
  83933. case TGATools._TYPE_RLE_RGB:
  83934. use_rle = true;
  83935. case TGATools._TYPE_RGB:
  83936. // use_rgb = true;
  83937. break;
  83938. case TGATools._TYPE_RLE_GREY:
  83939. use_rle = true;
  83940. case TGATools._TYPE_GREY:
  83941. use_grey = true;
  83942. break;
  83943. }
  83944. var pixel_data;
  83945. // var numAlphaBits = header.flags & 0xf;
  83946. var pixel_size = header.pixel_size >> 3;
  83947. var pixel_total = header.width * header.height * pixel_size;
  83948. // Read palettes
  83949. var palettes;
  83950. if (use_pal) {
  83951. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  83952. }
  83953. // Read LRE
  83954. if (use_rle) {
  83955. pixel_data = new Uint8Array(pixel_total);
  83956. var c, count, i;
  83957. var localOffset = 0;
  83958. var pixels = new Uint8Array(pixel_size);
  83959. while (offset < pixel_total && localOffset < pixel_total) {
  83960. c = data[offset++];
  83961. count = (c & 0x7f) + 1;
  83962. // RLE pixels
  83963. if (c & 0x80) {
  83964. // Bind pixel tmp array
  83965. for (i = 0; i < pixel_size; ++i) {
  83966. pixels[i] = data[offset++];
  83967. }
  83968. // Copy pixel array
  83969. for (i = 0; i < count; ++i) {
  83970. pixel_data.set(pixels, localOffset + i * pixel_size);
  83971. }
  83972. localOffset += pixel_size * count;
  83973. }
  83974. // Raw pixels
  83975. else {
  83976. count *= pixel_size;
  83977. for (i = 0; i < count; ++i) {
  83978. pixel_data[localOffset + i] = data[offset++];
  83979. }
  83980. localOffset += count;
  83981. }
  83982. }
  83983. }
  83984. // RAW Pixels
  83985. else {
  83986. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  83987. }
  83988. // Load to texture
  83989. var x_start, y_start, x_step, y_step, y_end, x_end;
  83990. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  83991. default:
  83992. case TGATools._ORIGIN_UL:
  83993. x_start = 0;
  83994. x_step = 1;
  83995. x_end = header.width;
  83996. y_start = 0;
  83997. y_step = 1;
  83998. y_end = header.height;
  83999. break;
  84000. case TGATools._ORIGIN_BL:
  84001. x_start = 0;
  84002. x_step = 1;
  84003. x_end = header.width;
  84004. y_start = header.height - 1;
  84005. y_step = -1;
  84006. y_end = -1;
  84007. break;
  84008. case TGATools._ORIGIN_UR:
  84009. x_start = header.width - 1;
  84010. x_step = -1;
  84011. x_end = -1;
  84012. y_start = 0;
  84013. y_step = 1;
  84014. y_end = header.height;
  84015. break;
  84016. case TGATools._ORIGIN_BR:
  84017. x_start = header.width - 1;
  84018. x_step = -1;
  84019. x_end = -1;
  84020. y_start = header.height - 1;
  84021. y_step = -1;
  84022. y_end = -1;
  84023. break;
  84024. }
  84025. // Load the specify method
  84026. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  84027. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  84028. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  84029. };
  84030. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84031. var image = pixel_data, colormap = palettes;
  84032. var width = header.width, height = header.height;
  84033. var color, i = 0, x, y;
  84034. var imageData = new Uint8Array(width * height * 4);
  84035. for (y = y_start; y !== y_end; y += y_step) {
  84036. for (x = x_start; x !== x_end; x += x_step, i++) {
  84037. color = image[i];
  84038. imageData[(x + width * y) * 4 + 3] = 255;
  84039. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  84040. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  84041. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  84042. }
  84043. }
  84044. return imageData;
  84045. };
  84046. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84047. var image = pixel_data;
  84048. var width = header.width, height = header.height;
  84049. var color, i = 0, x, y;
  84050. var imageData = new Uint8Array(width * height * 4);
  84051. for (y = y_start; y !== y_end; y += y_step) {
  84052. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84053. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  84054. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  84055. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  84056. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  84057. imageData[(x + width * y) * 4 + 0] = r;
  84058. imageData[(x + width * y) * 4 + 1] = g;
  84059. imageData[(x + width * y) * 4 + 2] = b;
  84060. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  84061. }
  84062. }
  84063. return imageData;
  84064. };
  84065. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84066. var image = pixel_data;
  84067. var width = header.width, height = header.height;
  84068. var i = 0, x, y;
  84069. var imageData = new Uint8Array(width * height * 4);
  84070. for (y = y_start; y !== y_end; y += y_step) {
  84071. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  84072. imageData[(x + width * y) * 4 + 3] = 255;
  84073. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84074. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84075. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84076. }
  84077. }
  84078. return imageData;
  84079. };
  84080. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84081. var image = pixel_data;
  84082. var width = header.width, height = header.height;
  84083. var i = 0, x, y;
  84084. var imageData = new Uint8Array(width * height * 4);
  84085. for (y = y_start; y !== y_end; y += y_step) {
  84086. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  84087. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84088. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84089. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84090. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  84091. }
  84092. }
  84093. return imageData;
  84094. };
  84095. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84096. var image = pixel_data;
  84097. var width = header.width, height = header.height;
  84098. var color, i = 0, x, y;
  84099. var imageData = new Uint8Array(width * height * 4);
  84100. for (y = y_start; y !== y_end; y += y_step) {
  84101. for (x = x_start; x !== x_end; x += x_step, i++) {
  84102. color = image[i];
  84103. imageData[(x + width * y) * 4 + 0] = color;
  84104. imageData[(x + width * y) * 4 + 1] = color;
  84105. imageData[(x + width * y) * 4 + 2] = color;
  84106. imageData[(x + width * y) * 4 + 3] = 255;
  84107. }
  84108. }
  84109. return imageData;
  84110. };
  84111. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84112. var image = pixel_data;
  84113. var width = header.width, height = header.height;
  84114. var i = 0, x, y;
  84115. var imageData = new Uint8Array(width * height * 4);
  84116. for (y = y_start; y !== y_end; y += y_step) {
  84117. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84118. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  84119. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  84120. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84121. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  84122. }
  84123. }
  84124. return imageData;
  84125. };
  84126. //private static _TYPE_NO_DATA = 0;
  84127. TGATools._TYPE_INDEXED = 1;
  84128. TGATools._TYPE_RGB = 2;
  84129. TGATools._TYPE_GREY = 3;
  84130. TGATools._TYPE_RLE_INDEXED = 9;
  84131. TGATools._TYPE_RLE_RGB = 10;
  84132. TGATools._TYPE_RLE_GREY = 11;
  84133. TGATools._ORIGIN_MASK = 0x30;
  84134. TGATools._ORIGIN_SHIFT = 0x04;
  84135. TGATools._ORIGIN_BL = 0x00;
  84136. TGATools._ORIGIN_BR = 0x01;
  84137. TGATools._ORIGIN_UL = 0x02;
  84138. TGATools._ORIGIN_UR = 0x03;
  84139. return TGATools;
  84140. }());
  84141. BABYLON.TGATools = TGATools;
  84142. })(BABYLON || (BABYLON = {}));
  84143. //# sourceMappingURL=babylon.tga.js.map
  84144. var BABYLON;
  84145. (function (BABYLON) {
  84146. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  84147. // All values and structures referenced from:
  84148. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  84149. var DDS_MAGIC = 0x20534444;
  84150. var
  84151. //DDSD_CAPS = 0x1,
  84152. //DDSD_HEIGHT = 0x2,
  84153. //DDSD_WIDTH = 0x4,
  84154. //DDSD_PITCH = 0x8,
  84155. //DDSD_PIXELFORMAT = 0x1000,
  84156. DDSD_MIPMAPCOUNT = 0x20000;
  84157. //DDSD_LINEARSIZE = 0x80000,
  84158. //DDSD_DEPTH = 0x800000;
  84159. // var DDSCAPS_COMPLEX = 0x8,
  84160. // DDSCAPS_MIPMAP = 0x400000,
  84161. // DDSCAPS_TEXTURE = 0x1000;
  84162. var DDSCAPS2_CUBEMAP = 0x200;
  84163. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  84164. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  84165. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  84166. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  84167. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  84168. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  84169. // DDSCAPS2_VOLUME = 0x200000;
  84170. var
  84171. //DDPF_ALPHAPIXELS = 0x1,
  84172. //DDPF_ALPHA = 0x2,
  84173. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  84174. //DDPF_YUV = 0x200,
  84175. DDPF_LUMINANCE = 0x20000;
  84176. function FourCCToInt32(value) {
  84177. return value.charCodeAt(0) +
  84178. (value.charCodeAt(1) << 8) +
  84179. (value.charCodeAt(2) << 16) +
  84180. (value.charCodeAt(3) << 24);
  84181. }
  84182. function Int32ToFourCC(value) {
  84183. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  84184. }
  84185. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  84186. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  84187. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  84188. var FOURCC_DX10 = FourCCToInt32("DX10");
  84189. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  84190. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  84191. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  84192. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  84193. var headerLengthInt = 31; // The header length in 32 bit ints
  84194. // Offsets into the header array
  84195. var off_magic = 0;
  84196. var off_size = 1;
  84197. var off_flags = 2;
  84198. var off_height = 3;
  84199. var off_width = 4;
  84200. var off_mipmapCount = 7;
  84201. var off_pfFlags = 20;
  84202. var off_pfFourCC = 21;
  84203. var off_RGBbpp = 22;
  84204. var off_RMask = 23;
  84205. var off_GMask = 24;
  84206. var off_BMask = 25;
  84207. var off_AMask = 26;
  84208. // var off_caps1 = 27;
  84209. var off_caps2 = 28;
  84210. // var off_caps3 = 29;
  84211. // var off_caps4 = 30;
  84212. var off_dxgiFormat = 32;
  84213. ;
  84214. var DDSTools = /** @class */ (function () {
  84215. function DDSTools() {
  84216. }
  84217. DDSTools.GetDDSInfo = function (arrayBuffer) {
  84218. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84219. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  84220. var mipmapCount = 1;
  84221. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  84222. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84223. }
  84224. var fourCC = header[off_pfFourCC];
  84225. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  84226. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84227. switch (fourCC) {
  84228. case FOURCC_D3DFMT_R16G16B16A16F:
  84229. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84230. break;
  84231. case FOURCC_D3DFMT_R32G32B32A32F:
  84232. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84233. break;
  84234. case FOURCC_DX10:
  84235. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  84236. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84237. break;
  84238. }
  84239. }
  84240. return {
  84241. width: header[off_width],
  84242. height: header[off_height],
  84243. mipmapCount: mipmapCount,
  84244. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  84245. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  84246. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  84247. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  84248. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  84249. dxgiFormat: dxgiFormat,
  84250. textureType: textureType
  84251. };
  84252. };
  84253. DDSTools._ToHalfFloat = function (value) {
  84254. if (!DDSTools._FloatView) {
  84255. DDSTools._FloatView = new Float32Array(1);
  84256. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  84257. }
  84258. DDSTools._FloatView[0] = value;
  84259. var x = DDSTools._Int32View[0];
  84260. var bits = (x >> 16) & 0x8000; /* Get the sign */
  84261. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  84262. var e = (x >> 23) & 0xff; /* Using int is faster here */
  84263. /* If zero, or denormal, or exponent underflows too much for a denormal
  84264. * half, return signed zero. */
  84265. if (e < 103) {
  84266. return bits;
  84267. }
  84268. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  84269. if (e > 142) {
  84270. bits |= 0x7c00;
  84271. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  84272. * not Inf, so make sure we set one mantissa bit too. */
  84273. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  84274. return bits;
  84275. }
  84276. /* If exponent underflows but not too much, return a denormal */
  84277. if (e < 113) {
  84278. m |= 0x0800;
  84279. /* Extra rounding may overflow and set mantissa to 0 and exponent
  84280. * to 1, which is OK. */
  84281. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  84282. return bits;
  84283. }
  84284. bits |= ((e - 112) << 10) | (m >> 1);
  84285. bits += m & 1;
  84286. return bits;
  84287. };
  84288. DDSTools._FromHalfFloat = function (value) {
  84289. var s = (value & 0x8000) >> 15;
  84290. var e = (value & 0x7C00) >> 10;
  84291. var f = value & 0x03FF;
  84292. if (e === 0) {
  84293. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  84294. }
  84295. else if (e == 0x1F) {
  84296. return f ? NaN : ((s ? -1 : 1) * Infinity);
  84297. }
  84298. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  84299. };
  84300. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84301. var destArray = new Float32Array(dataLength);
  84302. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84303. var index = 0;
  84304. for (var y = 0; y < height; y++) {
  84305. for (var x = 0; x < width; x++) {
  84306. var srcPos = (x + y * width) * 4;
  84307. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  84308. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  84309. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  84310. if (DDSTools.StoreLODInAlphaChannel) {
  84311. destArray[index + 3] = lod;
  84312. }
  84313. else {
  84314. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  84315. }
  84316. index += 4;
  84317. }
  84318. }
  84319. return destArray;
  84320. };
  84321. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84322. if (DDSTools.StoreLODInAlphaChannel) {
  84323. var destArray = new Uint16Array(dataLength);
  84324. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84325. var index = 0;
  84326. for (var y = 0; y < height; y++) {
  84327. for (var x = 0; x < width; x++) {
  84328. var srcPos = (x + y * width) * 4;
  84329. destArray[index] = srcData[srcPos];
  84330. destArray[index + 1] = srcData[srcPos + 1];
  84331. destArray[index + 2] = srcData[srcPos + 2];
  84332. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  84333. index += 4;
  84334. }
  84335. }
  84336. return destArray;
  84337. }
  84338. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  84339. };
  84340. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84341. if (DDSTools.StoreLODInAlphaChannel) {
  84342. var destArray = new Float32Array(dataLength);
  84343. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84344. var index = 0;
  84345. for (var y = 0; y < height; y++) {
  84346. for (var x = 0; x < width; x++) {
  84347. var srcPos = (x + y * width) * 4;
  84348. destArray[index] = srcData[srcPos];
  84349. destArray[index + 1] = srcData[srcPos + 1];
  84350. destArray[index + 2] = srcData[srcPos + 2];
  84351. destArray[index + 3] = lod;
  84352. index += 4;
  84353. }
  84354. }
  84355. return destArray;
  84356. }
  84357. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  84358. };
  84359. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84360. var destArray = new Uint8Array(dataLength);
  84361. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84362. var index = 0;
  84363. for (var y = 0; y < height; y++) {
  84364. for (var x = 0; x < width; x++) {
  84365. var srcPos = (x + y * width) * 4;
  84366. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  84367. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  84368. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  84369. if (DDSTools.StoreLODInAlphaChannel) {
  84370. destArray[index + 3] = lod;
  84371. }
  84372. else {
  84373. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  84374. }
  84375. index += 4;
  84376. }
  84377. }
  84378. return destArray;
  84379. };
  84380. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84381. var destArray = new Uint8Array(dataLength);
  84382. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84383. var index = 0;
  84384. for (var y = 0; y < height; y++) {
  84385. for (var x = 0; x < width; x++) {
  84386. var srcPos = (x + y * width) * 4;
  84387. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  84388. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  84389. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  84390. if (DDSTools.StoreLODInAlphaChannel) {
  84391. destArray[index + 3] = lod;
  84392. }
  84393. else {
  84394. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  84395. }
  84396. index += 4;
  84397. }
  84398. }
  84399. return destArray;
  84400. };
  84401. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  84402. var byteArray = new Uint8Array(dataLength);
  84403. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84404. var index = 0;
  84405. for (var y = 0; y < height; y++) {
  84406. for (var x = 0; x < width; x++) {
  84407. var srcPos = (x + y * width) * 4;
  84408. byteArray[index] = srcData[srcPos + rOffset];
  84409. byteArray[index + 1] = srcData[srcPos + gOffset];
  84410. byteArray[index + 2] = srcData[srcPos + bOffset];
  84411. byteArray[index + 3] = srcData[srcPos + aOffset];
  84412. index += 4;
  84413. }
  84414. }
  84415. return byteArray;
  84416. };
  84417. DDSTools._ExtractLongWordOrder = function (value) {
  84418. if (value === 0 || value === 255 || value === -16777216) {
  84419. return 0;
  84420. }
  84421. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  84422. };
  84423. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  84424. var byteArray = new Uint8Array(dataLength);
  84425. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84426. var index = 0;
  84427. for (var y = 0; y < height; y++) {
  84428. for (var x = 0; x < width; x++) {
  84429. var srcPos = (x + y * width) * 3;
  84430. byteArray[index] = srcData[srcPos + rOffset];
  84431. byteArray[index + 1] = srcData[srcPos + gOffset];
  84432. byteArray[index + 2] = srcData[srcPos + bOffset];
  84433. index += 3;
  84434. }
  84435. }
  84436. return byteArray;
  84437. };
  84438. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  84439. var byteArray = new Uint8Array(dataLength);
  84440. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84441. var index = 0;
  84442. for (var y = 0; y < height; y++) {
  84443. for (var x = 0; x < width; x++) {
  84444. var srcPos = (x + y * width);
  84445. byteArray[index] = srcData[srcPos];
  84446. index++;
  84447. }
  84448. }
  84449. return byteArray;
  84450. };
  84451. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  84452. if (lodIndex === void 0) { lodIndex = -1; }
  84453. var sphericalPolynomialFaces = null;
  84454. if (info.sphericalPolynomial) {
  84455. sphericalPolynomialFaces = new Array();
  84456. }
  84457. var ext = engine.getCaps().s3tc;
  84458. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84459. var fourCC, width, height, dataLength = 0, dataOffset;
  84460. var byteArray, mipmapCount, mip;
  84461. var internalFormat = 0;
  84462. var format = 0;
  84463. var blockBytes = 1;
  84464. if (header[off_magic] !== DDS_MAGIC) {
  84465. BABYLON.Tools.Error("Invalid magic number in DDS header");
  84466. return;
  84467. }
  84468. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  84469. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  84470. return;
  84471. }
  84472. if (info.isCompressed && !ext) {
  84473. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  84474. return;
  84475. }
  84476. var bpp = header[off_RGBbpp];
  84477. dataOffset = header[off_size] + 4;
  84478. var computeFormats = false;
  84479. if (info.isFourCC) {
  84480. fourCC = header[off_pfFourCC];
  84481. switch (fourCC) {
  84482. case FOURCC_DXT1:
  84483. blockBytes = 8;
  84484. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  84485. break;
  84486. case FOURCC_DXT3:
  84487. blockBytes = 16;
  84488. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  84489. break;
  84490. case FOURCC_DXT5:
  84491. blockBytes = 16;
  84492. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  84493. break;
  84494. case FOURCC_D3DFMT_R16G16B16A16F:
  84495. computeFormats = true;
  84496. break;
  84497. case FOURCC_D3DFMT_R32G32B32A32F:
  84498. computeFormats = true;
  84499. break;
  84500. case FOURCC_DX10:
  84501. // There is an additionnal header so dataOffset need to be changed
  84502. dataOffset += 5 * 4; // 5 uints
  84503. var supported = false;
  84504. switch (info.dxgiFormat) {
  84505. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  84506. computeFormats = true;
  84507. supported = true;
  84508. break;
  84509. case DXGI_FORMAT_B8G8R8X8_UNORM:
  84510. info.isRGB = true;
  84511. info.isFourCC = false;
  84512. bpp = 32;
  84513. supported = true;
  84514. break;
  84515. }
  84516. if (supported) {
  84517. break;
  84518. }
  84519. default:
  84520. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  84521. return;
  84522. }
  84523. }
  84524. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  84525. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  84526. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  84527. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  84528. if (computeFormats) {
  84529. format = engine._getWebGLTextureType(info.textureType);
  84530. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84531. }
  84532. mipmapCount = 1;
  84533. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  84534. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84535. }
  84536. for (var face = 0; face < faces; face++) {
  84537. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  84538. width = header[off_width];
  84539. height = header[off_height];
  84540. for (mip = 0; mip < mipmapCount; ++mip) {
  84541. if (lodIndex === -1 || lodIndex === mip) {
  84542. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  84543. var i = (lodIndex === -1) ? mip : 0;
  84544. if (!info.isCompressed && info.isFourCC) {
  84545. dataLength = width * height * 4;
  84546. var floatArray = null;
  84547. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  84548. if (bpp === 128) {
  84549. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84550. if (sphericalPolynomialFaces && i == 0) {
  84551. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84552. }
  84553. }
  84554. else if (bpp === 64) {
  84555. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84556. if (sphericalPolynomialFaces && i == 0) {
  84557. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84558. }
  84559. }
  84560. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84561. format = engine._getWebGLTextureType(info.textureType);
  84562. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84563. }
  84564. else {
  84565. if (bpp === 128) {
  84566. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84567. if (sphericalPolynomialFaces && i == 0) {
  84568. sphericalPolynomialFaces.push(floatArray);
  84569. }
  84570. }
  84571. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  84572. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84573. if (sphericalPolynomialFaces && i == 0) {
  84574. sphericalPolynomialFaces.push(floatArray);
  84575. }
  84576. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84577. format = engine._getWebGLTextureType(info.textureType);
  84578. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84579. }
  84580. else { // 64
  84581. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84582. if (sphericalPolynomialFaces && i == 0) {
  84583. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84584. }
  84585. }
  84586. }
  84587. if (floatArray) {
  84588. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  84589. }
  84590. }
  84591. else if (info.isRGB) {
  84592. if (bpp === 24) {
  84593. dataLength = width * height * 3;
  84594. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  84595. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  84596. }
  84597. else { // 32
  84598. dataLength = width * height * 4;
  84599. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  84600. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  84601. }
  84602. }
  84603. else if (info.isLuminance) {
  84604. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  84605. var unpaddedRowSize = width;
  84606. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  84607. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  84608. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  84609. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  84610. }
  84611. else {
  84612. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  84613. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  84614. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  84615. }
  84616. }
  84617. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  84618. width *= 0.5;
  84619. height *= 0.5;
  84620. width = Math.max(1.0, width);
  84621. height = Math.max(1.0, height);
  84622. }
  84623. if (currentFace !== undefined) {
  84624. // Loading a single face
  84625. break;
  84626. }
  84627. }
  84628. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  84629. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  84630. size: header[off_width],
  84631. right: sphericalPolynomialFaces[0],
  84632. left: sphericalPolynomialFaces[1],
  84633. up: sphericalPolynomialFaces[2],
  84634. down: sphericalPolynomialFaces[3],
  84635. front: sphericalPolynomialFaces[4],
  84636. back: sphericalPolynomialFaces[5],
  84637. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  84638. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  84639. gammaSpace: false,
  84640. });
  84641. }
  84642. else {
  84643. info.sphericalPolynomial = undefined;
  84644. }
  84645. };
  84646. DDSTools.StoreLODInAlphaChannel = false;
  84647. return DDSTools;
  84648. }());
  84649. BABYLON.DDSTools = DDSTools;
  84650. })(BABYLON || (BABYLON = {}));
  84651. //# sourceMappingURL=babylon.dds.js.map
  84652. var BABYLON;
  84653. (function (BABYLON) {
  84654. /**
  84655. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  84656. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  84657. */
  84658. var KhronosTextureContainer = /** @class */ (function () {
  84659. /**
  84660. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  84661. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  84662. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  84663. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  84664. */
  84665. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  84666. this.arrayBuffer = arrayBuffer;
  84667. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  84668. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  84669. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  84670. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  84671. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  84672. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  84673. BABYLON.Tools.Error("texture missing KTX identifier");
  84674. return;
  84675. }
  84676. // load the reset of the header in native 32 bit int
  84677. var header = new Int32Array(this.arrayBuffer, 12, 13);
  84678. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  84679. var oppositeEndianess = header[0] === 0x01020304;
  84680. // read all the header elements in order they exist in the file, without modification (sans endainness)
  84681. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  84682. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  84683. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  84684. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  84685. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  84686. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  84687. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  84688. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  84689. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  84690. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  84691. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  84692. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  84693. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  84694. if (this.glType !== 0) {
  84695. BABYLON.Tools.Error("only compressed formats currently supported");
  84696. return;
  84697. }
  84698. else {
  84699. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  84700. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  84701. }
  84702. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  84703. BABYLON.Tools.Error("only 2D textures currently supported");
  84704. return;
  84705. }
  84706. if (this.numberOfArrayElements !== 0) {
  84707. BABYLON.Tools.Error("texture arrays not currently supported");
  84708. return;
  84709. }
  84710. if (this.numberOfFaces !== facesExpected) {
  84711. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  84712. return;
  84713. }
  84714. // we now have a completely validated file, so could use existence of loadType as success
  84715. // would need to make this more elaborate & adjust checks above to support more than one load type
  84716. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  84717. }
  84718. // not as fast hardware based, but will probably never need to use
  84719. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  84720. return ((val & 0xFF) << 24)
  84721. | ((val & 0xFF00) << 8)
  84722. | ((val >> 8) & 0xFF00)
  84723. | ((val >> 24) & 0xFF);
  84724. };
  84725. /**
  84726. * It is assumed that the texture has already been created & is currently bound
  84727. */
  84728. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  84729. switch (this.loadType) {
  84730. case KhronosTextureContainer.COMPRESSED_2D:
  84731. this._upload2DCompressedLevels(gl, loadMipmaps);
  84732. break;
  84733. case KhronosTextureContainer.TEX_2D:
  84734. case KhronosTextureContainer.COMPRESSED_3D:
  84735. case KhronosTextureContainer.TEX_3D:
  84736. }
  84737. };
  84738. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  84739. // initialize width & height for level 1
  84740. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  84741. var width = this.pixelWidth;
  84742. var height = this.pixelHeight;
  84743. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  84744. for (var level = 0; level < mipmapCount; level++) {
  84745. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  84746. for (var face = 0; face < this.numberOfFaces; face++) {
  84747. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  84748. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  84749. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  84750. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  84751. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  84752. }
  84753. width = Math.max(1.0, width * 0.5);
  84754. height = Math.max(1.0, height * 0.5);
  84755. }
  84756. };
  84757. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  84758. // load types
  84759. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  84760. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  84761. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  84762. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  84763. return KhronosTextureContainer;
  84764. }());
  84765. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  84766. })(BABYLON || (BABYLON = {}));
  84767. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  84768. var BABYLON;
  84769. (function (BABYLON) {
  84770. var Debug;
  84771. (function (Debug) {
  84772. /**
  84773. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  84774. */
  84775. var SkeletonViewer = /** @class */ (function () {
  84776. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  84777. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  84778. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  84779. this.skeleton = skeleton;
  84780. this.mesh = mesh;
  84781. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  84782. this.renderingGroupId = renderingGroupId;
  84783. this.color = BABYLON.Color3.White();
  84784. this._debugLines = new Array();
  84785. this._isEnabled = false;
  84786. this._scene = scene;
  84787. this.update();
  84788. this._renderFunction = this.update.bind(this);
  84789. }
  84790. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  84791. get: function () {
  84792. return this._isEnabled;
  84793. },
  84794. set: function (value) {
  84795. if (this._isEnabled === value) {
  84796. return;
  84797. }
  84798. this._isEnabled = value;
  84799. if (value) {
  84800. this._scene.registerBeforeRender(this._renderFunction);
  84801. }
  84802. else {
  84803. this._scene.unregisterBeforeRender(this._renderFunction);
  84804. }
  84805. },
  84806. enumerable: true,
  84807. configurable: true
  84808. });
  84809. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  84810. if (x === void 0) { x = 0; }
  84811. if (y === void 0) { y = 0; }
  84812. if (z === void 0) { z = 0; }
  84813. var tmat = BABYLON.Tmp.Matrix[0];
  84814. var parentBone = bone.getParent();
  84815. tmat.copyFrom(bone.getLocalMatrix());
  84816. if (x !== 0 || y !== 0 || z !== 0) {
  84817. var tmat2 = BABYLON.Tmp.Matrix[1];
  84818. BABYLON.Matrix.IdentityToRef(tmat2);
  84819. tmat2.m[12] = x;
  84820. tmat2.m[13] = y;
  84821. tmat2.m[14] = z;
  84822. tmat2.multiplyToRef(tmat, tmat);
  84823. }
  84824. if (parentBone) {
  84825. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  84826. }
  84827. tmat.multiplyToRef(meshMat, tmat);
  84828. position.x = tmat.m[12];
  84829. position.y = tmat.m[13];
  84830. position.z = tmat.m[14];
  84831. };
  84832. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  84833. var len = bones.length;
  84834. var meshPos = this.mesh.position;
  84835. for (var i = 0; i < len; i++) {
  84836. var bone = bones[i];
  84837. var points = this._debugLines[i];
  84838. if (!points) {
  84839. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84840. this._debugLines[i] = points;
  84841. }
  84842. this._getBonePosition(points[0], bone, meshMat);
  84843. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  84844. points[0].subtractInPlace(meshPos);
  84845. points[1].subtractInPlace(meshPos);
  84846. }
  84847. };
  84848. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  84849. var len = bones.length;
  84850. var boneNum = 0;
  84851. var meshPos = this.mesh.position;
  84852. for (var i = len - 1; i >= 0; i--) {
  84853. var childBone = bones[i];
  84854. var parentBone = childBone.getParent();
  84855. if (!parentBone) {
  84856. continue;
  84857. }
  84858. var points = this._debugLines[boneNum];
  84859. if (!points) {
  84860. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84861. this._debugLines[boneNum] = points;
  84862. }
  84863. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  84864. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  84865. points[0].subtractInPlace(meshPos);
  84866. points[1].subtractInPlace(meshPos);
  84867. boneNum++;
  84868. }
  84869. };
  84870. SkeletonViewer.prototype.update = function () {
  84871. if (this.autoUpdateBonesMatrices) {
  84872. this.skeleton.computeAbsoluteTransforms();
  84873. }
  84874. if (this.skeleton.bones[0].length === undefined) {
  84875. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  84876. }
  84877. else {
  84878. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  84879. }
  84880. if (!this._debugMesh) {
  84881. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  84882. this._debugMesh.renderingGroupId = this.renderingGroupId;
  84883. }
  84884. else {
  84885. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  84886. }
  84887. this._debugMesh.position.copyFrom(this.mesh.position);
  84888. this._debugMesh.color = this.color;
  84889. };
  84890. SkeletonViewer.prototype.dispose = function () {
  84891. if (this._debugMesh) {
  84892. this.isEnabled = false;
  84893. this._debugMesh.dispose();
  84894. this._debugMesh = null;
  84895. }
  84896. };
  84897. return SkeletonViewer;
  84898. }());
  84899. Debug.SkeletonViewer = SkeletonViewer;
  84900. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84901. })(BABYLON || (BABYLON = {}));
  84902. //# sourceMappingURL=babylon.skeletonViewer.js.map
  84903. /**
  84904. * Module Debug contains the (visual) components to debug a scene correctly
  84905. */
  84906. var BABYLON;
  84907. (function (BABYLON) {
  84908. var Debug;
  84909. (function (Debug) {
  84910. /**
  84911. * The Axes viewer will show 3 axes in a specific point in space
  84912. */
  84913. var AxesViewer = /** @class */ (function () {
  84914. function AxesViewer(scene, scaleLines) {
  84915. if (scaleLines === void 0) { scaleLines = 1; }
  84916. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84917. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84918. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84919. this.scaleLines = 1;
  84920. this.scaleLines = scaleLines;
  84921. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  84922. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  84923. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  84924. this._xmesh.renderingGroupId = 2;
  84925. this._ymesh.renderingGroupId = 2;
  84926. this._zmesh.renderingGroupId = 2;
  84927. this._xmesh.material.checkReadyOnlyOnce = true;
  84928. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  84929. this._ymesh.material.checkReadyOnlyOnce = true;
  84930. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  84931. this._zmesh.material.checkReadyOnlyOnce = true;
  84932. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  84933. this.scene = scene;
  84934. }
  84935. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  84936. var scaleLines = this.scaleLines;
  84937. if (this._xmesh) {
  84938. this._xmesh.position.copyFrom(position);
  84939. }
  84940. if (this._ymesh) {
  84941. this._ymesh.position.copyFrom(position);
  84942. }
  84943. if (this._zmesh) {
  84944. this._zmesh.position.copyFrom(position);
  84945. }
  84946. var point2 = this._xline[1];
  84947. point2.x = xaxis.x * scaleLines;
  84948. point2.y = xaxis.y * scaleLines;
  84949. point2.z = xaxis.z * scaleLines;
  84950. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  84951. point2 = this._yline[1];
  84952. point2.x = yaxis.x * scaleLines;
  84953. point2.y = yaxis.y * scaleLines;
  84954. point2.z = yaxis.z * scaleLines;
  84955. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  84956. point2 = this._zline[1];
  84957. point2.x = zaxis.x * scaleLines;
  84958. point2.y = zaxis.y * scaleLines;
  84959. point2.z = zaxis.z * scaleLines;
  84960. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  84961. };
  84962. AxesViewer.prototype.dispose = function () {
  84963. if (this._xmesh) {
  84964. this._xmesh.dispose();
  84965. }
  84966. if (this._ymesh) {
  84967. this._ymesh.dispose();
  84968. }
  84969. if (this._zmesh) {
  84970. this._zmesh.dispose();
  84971. }
  84972. this._xmesh = null;
  84973. this._ymesh = null;
  84974. this._zmesh = null;
  84975. this.scene = null;
  84976. };
  84977. return AxesViewer;
  84978. }());
  84979. Debug.AxesViewer = AxesViewer;
  84980. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84981. })(BABYLON || (BABYLON = {}));
  84982. //# sourceMappingURL=babylon.axesViewer.js.map
  84983. var BABYLON;
  84984. (function (BABYLON) {
  84985. var Debug;
  84986. (function (Debug) {
  84987. /**
  84988. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  84989. */
  84990. var BoneAxesViewer = /** @class */ (function (_super) {
  84991. __extends(BoneAxesViewer, _super);
  84992. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  84993. if (scaleLines === void 0) { scaleLines = 1; }
  84994. var _this = _super.call(this, scene, scaleLines) || this;
  84995. _this.pos = BABYLON.Vector3.Zero();
  84996. _this.xaxis = BABYLON.Vector3.Zero();
  84997. _this.yaxis = BABYLON.Vector3.Zero();
  84998. _this.zaxis = BABYLON.Vector3.Zero();
  84999. _this.mesh = mesh;
  85000. _this.bone = bone;
  85001. return _this;
  85002. }
  85003. BoneAxesViewer.prototype.update = function () {
  85004. if (!this.mesh || !this.bone) {
  85005. return;
  85006. }
  85007. var bone = this.bone;
  85008. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  85009. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  85010. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  85011. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  85012. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  85013. };
  85014. BoneAxesViewer.prototype.dispose = function () {
  85015. if (this.mesh) {
  85016. this.mesh = null;
  85017. this.bone = null;
  85018. _super.prototype.dispose.call(this);
  85019. }
  85020. };
  85021. return BoneAxesViewer;
  85022. }(Debug.AxesViewer));
  85023. Debug.BoneAxesViewer = BoneAxesViewer;
  85024. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85025. })(BABYLON || (BABYLON = {}));
  85026. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  85027. var BABYLON;
  85028. (function (BABYLON) {
  85029. var RayHelper = /** @class */ (function () {
  85030. function RayHelper(ray) {
  85031. this.ray = ray;
  85032. }
  85033. RayHelper.CreateAndShow = function (ray, scene, color) {
  85034. var helper = new RayHelper(ray);
  85035. helper.show(scene, color);
  85036. return helper;
  85037. };
  85038. RayHelper.prototype.show = function (scene, color) {
  85039. if (!this._renderFunction && this.ray) {
  85040. var ray = this.ray;
  85041. this._renderFunction = this._render.bind(this);
  85042. this._scene = scene;
  85043. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  85044. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  85045. if (this._renderFunction) {
  85046. this._scene.registerBeforeRender(this._renderFunction);
  85047. }
  85048. }
  85049. if (color && this._renderLine) {
  85050. this._renderLine.color.copyFrom(color);
  85051. }
  85052. };
  85053. RayHelper.prototype.hide = function () {
  85054. if (this._renderFunction && this._scene) {
  85055. this._scene.unregisterBeforeRender(this._renderFunction);
  85056. this._scene = null;
  85057. this._renderFunction = null;
  85058. if (this._renderLine) {
  85059. this._renderLine.dispose();
  85060. this._renderLine = null;
  85061. }
  85062. this._renderPoints = [];
  85063. }
  85064. };
  85065. RayHelper.prototype._render = function () {
  85066. var ray = this.ray;
  85067. if (!ray) {
  85068. return;
  85069. }
  85070. var point = this._renderPoints[1];
  85071. var len = Math.min(ray.length, 1000000);
  85072. point.copyFrom(ray.direction);
  85073. point.scaleInPlace(len);
  85074. point.addInPlace(ray.origin);
  85075. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  85076. };
  85077. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  85078. this._attachedToMesh = mesh;
  85079. var ray = this.ray;
  85080. if (!ray) {
  85081. return;
  85082. }
  85083. if (!ray.direction) {
  85084. ray.direction = BABYLON.Vector3.Zero();
  85085. }
  85086. if (!ray.origin) {
  85087. ray.origin = BABYLON.Vector3.Zero();
  85088. }
  85089. if (length) {
  85090. ray.length = length;
  85091. }
  85092. if (!meshSpaceOrigin) {
  85093. meshSpaceOrigin = BABYLON.Vector3.Zero();
  85094. }
  85095. if (!meshSpaceDirection) {
  85096. // -1 so that this will work with Mesh.lookAt
  85097. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  85098. }
  85099. if (!this._meshSpaceDirection) {
  85100. this._meshSpaceDirection = meshSpaceDirection.clone();
  85101. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  85102. }
  85103. else {
  85104. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  85105. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  85106. }
  85107. if (!this._updateToMeshFunction) {
  85108. this._updateToMeshFunction = this._updateToMesh.bind(this);
  85109. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  85110. }
  85111. this._updateToMesh();
  85112. };
  85113. RayHelper.prototype.detachFromMesh = function () {
  85114. if (this._attachedToMesh) {
  85115. if (this._updateToMeshFunction) {
  85116. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  85117. }
  85118. this._attachedToMesh = null;
  85119. this._updateToMeshFunction = null;
  85120. }
  85121. };
  85122. RayHelper.prototype._updateToMesh = function () {
  85123. var ray = this.ray;
  85124. if (!this._attachedToMesh || !ray) {
  85125. return;
  85126. }
  85127. if (this._attachedToMesh._isDisposed) {
  85128. this.detachFromMesh();
  85129. return;
  85130. }
  85131. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  85132. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  85133. };
  85134. RayHelper.prototype.dispose = function () {
  85135. this.hide();
  85136. this.detachFromMesh();
  85137. this.ray = null;
  85138. };
  85139. return RayHelper;
  85140. }());
  85141. BABYLON.RayHelper = RayHelper;
  85142. })(BABYLON || (BABYLON = {}));
  85143. //# sourceMappingURL=babylon.rayHelper.js.map
  85144. var BABYLON;
  85145. (function (BABYLON) {
  85146. // load the inspector using require, if not present in the global namespace.
  85147. var DebugLayer = /** @class */ (function () {
  85148. function DebugLayer(scene) {
  85149. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85150. this._scene = scene;
  85151. // load inspector using require, if it doesn't exist on the global namespace.
  85152. }
  85153. /** Creates the inspector window. */
  85154. DebugLayer.prototype._createInspector = function (config) {
  85155. if (config === void 0) { config = {}; }
  85156. var popup = config.popup || false;
  85157. var initialTab = config.initialTab || 0;
  85158. var parentElement = config.parentElement || null;
  85159. if (!this._inspector) {
  85160. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85161. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  85162. } // else nothing to do,; instance is already existing
  85163. };
  85164. DebugLayer.prototype.isVisible = function () {
  85165. if (!this._inspector) {
  85166. return false;
  85167. }
  85168. return true;
  85169. };
  85170. DebugLayer.prototype.hide = function () {
  85171. if (this._inspector) {
  85172. try {
  85173. this._inspector.dispose();
  85174. }
  85175. catch (e) {
  85176. // If the inspector has been removed directly from the inspector tool
  85177. }
  85178. this._inspector = null;
  85179. }
  85180. };
  85181. DebugLayer.prototype.show = function (config) {
  85182. if (config === void 0) { config = {}; }
  85183. if (typeof this.BJSINSPECTOR == 'undefined') {
  85184. // Load inspector and add it to the DOM
  85185. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  85186. }
  85187. else {
  85188. // Otherwise creates the inspector
  85189. this._createInspector(config);
  85190. }
  85191. };
  85192. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  85193. return DebugLayer;
  85194. }());
  85195. BABYLON.DebugLayer = DebugLayer;
  85196. })(BABYLON || (BABYLON = {}));
  85197. //# sourceMappingURL=babylon.debugLayer.js.map
  85198. var BABYLON;
  85199. (function (BABYLON) {
  85200. var Debug;
  85201. (function (Debug) {
  85202. /**
  85203. * Used to show the physics impostor around the specific mesh.
  85204. */
  85205. var PhysicsViewer = /** @class */ (function () {
  85206. function PhysicsViewer(scene) {
  85207. this._impostors = [];
  85208. this._meshes = [];
  85209. this._numMeshes = 0;
  85210. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85211. var physicEngine = this._scene.getPhysicsEngine();
  85212. if (physicEngine) {
  85213. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  85214. }
  85215. }
  85216. PhysicsViewer.prototype._updateDebugMeshes = function () {
  85217. var plugin = this._physicsEnginePlugin;
  85218. for (var i = 0; i < this._numMeshes; i++) {
  85219. var impostor = this._impostors[i];
  85220. if (!impostor) {
  85221. continue;
  85222. }
  85223. if (impostor.isDisposed) {
  85224. this.hideImpostor(this._impostors[i--]);
  85225. }
  85226. else {
  85227. var mesh = this._meshes[i];
  85228. if (mesh && plugin) {
  85229. plugin.syncMeshWithImpostor(mesh, impostor);
  85230. }
  85231. }
  85232. }
  85233. };
  85234. PhysicsViewer.prototype.showImpostor = function (impostor) {
  85235. if (!this._scene) {
  85236. return;
  85237. }
  85238. for (var i = 0; i < this._numMeshes; i++) {
  85239. if (this._impostors[i] == impostor) {
  85240. return;
  85241. }
  85242. }
  85243. var debugMesh = this._getDebugMesh(impostor, this._scene);
  85244. if (debugMesh) {
  85245. this._impostors[this._numMeshes] = impostor;
  85246. this._meshes[this._numMeshes] = debugMesh;
  85247. if (this._numMeshes === 0) {
  85248. this._renderFunction = this._updateDebugMeshes.bind(this);
  85249. this._scene.registerBeforeRender(this._renderFunction);
  85250. }
  85251. this._numMeshes++;
  85252. }
  85253. };
  85254. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  85255. if (!impostor || !this._scene) {
  85256. return;
  85257. }
  85258. var removed = false;
  85259. for (var i = 0; i < this._numMeshes; i++) {
  85260. if (this._impostors[i] == impostor) {
  85261. var mesh = this._meshes[i];
  85262. if (!mesh) {
  85263. continue;
  85264. }
  85265. this._scene.removeMesh(mesh);
  85266. mesh.dispose();
  85267. this._numMeshes--;
  85268. if (this._numMeshes > 0) {
  85269. this._meshes[i] = this._meshes[this._numMeshes];
  85270. this._impostors[i] = this._impostors[this._numMeshes];
  85271. this._meshes[this._numMeshes] = null;
  85272. this._impostors[this._numMeshes] = null;
  85273. }
  85274. else {
  85275. this._meshes[0] = null;
  85276. this._impostors[0] = null;
  85277. }
  85278. removed = true;
  85279. break;
  85280. }
  85281. }
  85282. if (removed && this._numMeshes === 0) {
  85283. this._scene.unregisterBeforeRender(this._renderFunction);
  85284. }
  85285. };
  85286. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  85287. if (!this._debugMaterial) {
  85288. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  85289. this._debugMaterial.wireframe = true;
  85290. }
  85291. return this._debugMaterial;
  85292. };
  85293. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  85294. if (!this._debugBoxMesh) {
  85295. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  85296. this._debugBoxMesh.renderingGroupId = 1;
  85297. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85298. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  85299. scene.removeMesh(this._debugBoxMesh);
  85300. }
  85301. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  85302. };
  85303. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  85304. if (!this._debugSphereMesh) {
  85305. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  85306. this._debugSphereMesh.renderingGroupId = 1;
  85307. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85308. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  85309. scene.removeMesh(this._debugSphereMesh);
  85310. }
  85311. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  85312. };
  85313. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  85314. var mesh = null;
  85315. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  85316. mesh = this._getDebugBoxMesh(scene);
  85317. impostor.getBoxSizeToRef(mesh.scaling);
  85318. }
  85319. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  85320. mesh = this._getDebugSphereMesh(scene);
  85321. var radius = impostor.getRadius();
  85322. mesh.scaling.x = radius * 2;
  85323. mesh.scaling.y = radius * 2;
  85324. mesh.scaling.z = radius * 2;
  85325. }
  85326. return mesh;
  85327. };
  85328. PhysicsViewer.prototype.dispose = function () {
  85329. for (var i = 0; i < this._numMeshes; i++) {
  85330. this.hideImpostor(this._impostors[i]);
  85331. }
  85332. if (this._debugBoxMesh) {
  85333. this._debugBoxMesh.dispose();
  85334. }
  85335. if (this._debugSphereMesh) {
  85336. this._debugSphereMesh.dispose();
  85337. }
  85338. if (this._debugMaterial) {
  85339. this._debugMaterial.dispose();
  85340. }
  85341. this._impostors.length = 0;
  85342. this._scene = null;
  85343. this._physicsEnginePlugin = null;
  85344. };
  85345. return PhysicsViewer;
  85346. }());
  85347. Debug.PhysicsViewer = PhysicsViewer;
  85348. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85349. })(BABYLON || (BABYLON = {}));
  85350. //# sourceMappingURL=babylon.physicsViewer.js.map
  85351. var BABYLON;
  85352. (function (BABYLON) {
  85353. var BoundingBoxRenderer = /** @class */ (function () {
  85354. function BoundingBoxRenderer(scene) {
  85355. this.frontColor = new BABYLON.Color3(1, 1, 1);
  85356. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  85357. this.showBackLines = true;
  85358. this.renderList = new BABYLON.SmartArray(32);
  85359. this._vertexBuffers = {};
  85360. this._scene = scene;
  85361. }
  85362. BoundingBoxRenderer.prototype._prepareRessources = function () {
  85363. if (this._colorShader) {
  85364. return;
  85365. }
  85366. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  85367. attributes: [BABYLON.VertexBuffer.PositionKind],
  85368. uniforms: ["world", "viewProjection", "color"]
  85369. });
  85370. var engine = this._scene.getEngine();
  85371. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  85372. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  85373. this._createIndexBuffer();
  85374. };
  85375. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  85376. var engine = this._scene.getEngine();
  85377. 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]);
  85378. };
  85379. BoundingBoxRenderer.prototype._rebuild = function () {
  85380. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85381. if (vb) {
  85382. vb._rebuild();
  85383. }
  85384. this._createIndexBuffer();
  85385. };
  85386. BoundingBoxRenderer.prototype.reset = function () {
  85387. this.renderList.reset();
  85388. };
  85389. BoundingBoxRenderer.prototype.render = function () {
  85390. if (this.renderList.length === 0) {
  85391. return;
  85392. }
  85393. this._prepareRessources();
  85394. if (!this._colorShader.isReady()) {
  85395. return;
  85396. }
  85397. var engine = this._scene.getEngine();
  85398. engine.setDepthWrite(false);
  85399. this._colorShader._preBind();
  85400. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  85401. var boundingBox = this.renderList.data[boundingBoxIndex];
  85402. var min = boundingBox.minimum;
  85403. var max = boundingBox.maximum;
  85404. var diff = max.subtract(min);
  85405. var median = min.add(diff.scale(0.5));
  85406. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85407. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85408. .multiply(boundingBox.getWorldMatrix());
  85409. // VBOs
  85410. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85411. if (this.showBackLines) {
  85412. // Back
  85413. engine.setDepthFunctionToGreaterOrEqual();
  85414. this._scene.resetCachedMaterial();
  85415. this._colorShader.setColor4("color", this.backColor.toColor4());
  85416. this._colorShader.bind(worldMatrix);
  85417. // Draw order
  85418. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85419. }
  85420. // Front
  85421. engine.setDepthFunctionToLess();
  85422. this._scene.resetCachedMaterial();
  85423. this._colorShader.setColor4("color", this.frontColor.toColor4());
  85424. this._colorShader.bind(worldMatrix);
  85425. // Draw order
  85426. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85427. }
  85428. this._colorShader.unbind();
  85429. engine.setDepthFunctionToLessOrEqual();
  85430. engine.setDepthWrite(true);
  85431. };
  85432. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  85433. this._prepareRessources();
  85434. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  85435. return;
  85436. }
  85437. var engine = this._scene.getEngine();
  85438. engine.setDepthWrite(false);
  85439. engine.setColorWrite(false);
  85440. this._colorShader._preBind();
  85441. var boundingBox = mesh._boundingInfo.boundingBox;
  85442. var min = boundingBox.minimum;
  85443. var max = boundingBox.maximum;
  85444. var diff = max.subtract(min);
  85445. var median = min.add(diff.scale(0.5));
  85446. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85447. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85448. .multiply(boundingBox.getWorldMatrix());
  85449. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85450. engine.setDepthFunctionToLess();
  85451. this._scene.resetCachedMaterial();
  85452. this._colorShader.bind(worldMatrix);
  85453. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85454. this._colorShader.unbind();
  85455. engine.setDepthFunctionToLessOrEqual();
  85456. engine.setDepthWrite(true);
  85457. engine.setColorWrite(true);
  85458. };
  85459. BoundingBoxRenderer.prototype.dispose = function () {
  85460. if (!this._colorShader) {
  85461. return;
  85462. }
  85463. this.renderList.dispose();
  85464. this._colorShader.dispose();
  85465. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85466. if (buffer) {
  85467. buffer.dispose();
  85468. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85469. }
  85470. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85471. };
  85472. return BoundingBoxRenderer;
  85473. }());
  85474. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  85475. })(BABYLON || (BABYLON = {}));
  85476. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  85477. var BABYLON;
  85478. (function (BABYLON) {
  85479. /**
  85480. * Defines a target to use with MorphTargetManager
  85481. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85482. */
  85483. var MorphTarget = /** @class */ (function () {
  85484. /**
  85485. * Creates a new MorphTarget
  85486. * @param name defines the name of the target
  85487. * @param influence defines the influence to use
  85488. */
  85489. function MorphTarget(
  85490. /** defines the name of the target */
  85491. name, influence) {
  85492. if (influence === void 0) { influence = 0; }
  85493. this.name = name;
  85494. /**
  85495. * Gets or sets the list of animations
  85496. */
  85497. this.animations = new Array();
  85498. this._positions = null;
  85499. this._normals = null;
  85500. this._tangents = null;
  85501. /**
  85502. * Observable raised when the influence changes
  85503. */
  85504. this.onInfluenceChanged = new BABYLON.Observable();
  85505. this.influence = influence;
  85506. }
  85507. Object.defineProperty(MorphTarget.prototype, "influence", {
  85508. /**
  85509. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  85510. */
  85511. get: function () {
  85512. return this._influence;
  85513. },
  85514. set: function (influence) {
  85515. if (this._influence === influence) {
  85516. return;
  85517. }
  85518. var previous = this._influence;
  85519. this._influence = influence;
  85520. if (this.onInfluenceChanged.hasObservers) {
  85521. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  85522. }
  85523. },
  85524. enumerable: true,
  85525. configurable: true
  85526. });
  85527. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  85528. /**
  85529. * Gets a boolean defining if the target contains position data
  85530. */
  85531. get: function () {
  85532. return !!this._positions;
  85533. },
  85534. enumerable: true,
  85535. configurable: true
  85536. });
  85537. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  85538. /**
  85539. * Gets a boolean defining if the target contains normal data
  85540. */
  85541. get: function () {
  85542. return !!this._normals;
  85543. },
  85544. enumerable: true,
  85545. configurable: true
  85546. });
  85547. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  85548. /**
  85549. * Gets a boolean defining if the target contains tangent data
  85550. */
  85551. get: function () {
  85552. return !!this._tangents;
  85553. },
  85554. enumerable: true,
  85555. configurable: true
  85556. });
  85557. /**
  85558. * Affects position data to this target
  85559. * @param data defines the position data to use
  85560. */
  85561. MorphTarget.prototype.setPositions = function (data) {
  85562. this._positions = data;
  85563. };
  85564. /**
  85565. * Gets the position data stored in this target
  85566. * @returns a FloatArray containing the position data (or null if not present)
  85567. */
  85568. MorphTarget.prototype.getPositions = function () {
  85569. return this._positions;
  85570. };
  85571. /**
  85572. * Affects normal data to this target
  85573. * @param data defines the normal data to use
  85574. */
  85575. MorphTarget.prototype.setNormals = function (data) {
  85576. this._normals = data;
  85577. };
  85578. /**
  85579. * Gets the normal data stored in this target
  85580. * @returns a FloatArray containing the normal data (or null if not present)
  85581. */
  85582. MorphTarget.prototype.getNormals = function () {
  85583. return this._normals;
  85584. };
  85585. /**
  85586. * Affects tangent data to this target
  85587. * @param data defines the tangent data to use
  85588. */
  85589. MorphTarget.prototype.setTangents = function (data) {
  85590. this._tangents = data;
  85591. };
  85592. /**
  85593. * Gets the tangent data stored in this target
  85594. * @returns a FloatArray containing the tangent data (or null if not present)
  85595. */
  85596. MorphTarget.prototype.getTangents = function () {
  85597. return this._tangents;
  85598. };
  85599. /**
  85600. * Serializes the current target into a Serialization object
  85601. * @returns the serialized object
  85602. */
  85603. MorphTarget.prototype.serialize = function () {
  85604. var serializationObject = {};
  85605. serializationObject.name = this.name;
  85606. serializationObject.influence = this.influence;
  85607. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  85608. if (this.hasNormals) {
  85609. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  85610. }
  85611. if (this.hasTangents) {
  85612. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  85613. }
  85614. // Animations
  85615. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  85616. return serializationObject;
  85617. };
  85618. // Statics
  85619. /**
  85620. * Creates a new target from serialized data
  85621. * @param serializationObject defines the serialized data to use
  85622. * @returns a new MorphTarget
  85623. */
  85624. MorphTarget.Parse = function (serializationObject) {
  85625. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  85626. result.setPositions(serializationObject.positions);
  85627. if (serializationObject.normals) {
  85628. result.setNormals(serializationObject.normals);
  85629. }
  85630. if (serializationObject.tangents) {
  85631. result.setTangents(serializationObject.tangents);
  85632. }
  85633. // Animations
  85634. if (serializationObject.animations) {
  85635. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  85636. var parsedAnimation = serializationObject.animations[animationIndex];
  85637. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  85638. }
  85639. }
  85640. return result;
  85641. };
  85642. /**
  85643. * Creates a MorphTarget from mesh data
  85644. * @param mesh defines the source mesh
  85645. * @param name defines the name to use for the new target
  85646. * @param influence defines the influence to attach to the target
  85647. * @returns a new MorphTarget
  85648. */
  85649. MorphTarget.FromMesh = function (mesh, name, influence) {
  85650. if (!name) {
  85651. name = mesh.name;
  85652. }
  85653. var result = new MorphTarget(name, influence);
  85654. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  85655. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  85656. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  85657. }
  85658. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  85659. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  85660. }
  85661. return result;
  85662. };
  85663. return MorphTarget;
  85664. }());
  85665. BABYLON.MorphTarget = MorphTarget;
  85666. })(BABYLON || (BABYLON = {}));
  85667. //# sourceMappingURL=babylon.morphTarget.js.map
  85668. var BABYLON;
  85669. (function (BABYLON) {
  85670. /**
  85671. * This class is used to deform meshes using morphing between different targets
  85672. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85673. */
  85674. var MorphTargetManager = /** @class */ (function () {
  85675. /**
  85676. * Creates a new MorphTargetManager
  85677. * @param scene defines the current scene
  85678. */
  85679. function MorphTargetManager(scene) {
  85680. if (scene === void 0) { scene = null; }
  85681. this._targets = new Array();
  85682. this._targetObservable = new Array();
  85683. this._activeTargets = new BABYLON.SmartArray(16);
  85684. this._supportsNormals = false;
  85685. this._supportsTangents = false;
  85686. this._vertexCount = 0;
  85687. this._uniqueId = 0;
  85688. this._tempInfluences = new Array();
  85689. if (!scene) {
  85690. scene = BABYLON.Engine.LastCreatedScene;
  85691. }
  85692. this._scene = scene;
  85693. if (this._scene) {
  85694. this._scene.morphTargetManagers.push(this);
  85695. this._uniqueId = this._scene.getUniqueId();
  85696. }
  85697. }
  85698. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  85699. /**
  85700. * Gets the unique ID of this manager
  85701. */
  85702. get: function () {
  85703. return this._uniqueId;
  85704. },
  85705. enumerable: true,
  85706. configurable: true
  85707. });
  85708. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  85709. /**
  85710. * Gets the number of vertices handled by this manager
  85711. */
  85712. get: function () {
  85713. return this._vertexCount;
  85714. },
  85715. enumerable: true,
  85716. configurable: true
  85717. });
  85718. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  85719. /**
  85720. * Gets a boolean indicating if this manager supports morphing of normals
  85721. */
  85722. get: function () {
  85723. return this._supportsNormals;
  85724. },
  85725. enumerable: true,
  85726. configurable: true
  85727. });
  85728. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  85729. /**
  85730. * Gets a boolean indicating if this manager supports morphing of tangents
  85731. */
  85732. get: function () {
  85733. return this._supportsTangents;
  85734. },
  85735. enumerable: true,
  85736. configurable: true
  85737. });
  85738. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  85739. /**
  85740. * Gets the number of targets stored in this manager
  85741. */
  85742. get: function () {
  85743. return this._targets.length;
  85744. },
  85745. enumerable: true,
  85746. configurable: true
  85747. });
  85748. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  85749. /**
  85750. * Gets the number of influencers (ie. the number of targets with influences > 0)
  85751. */
  85752. get: function () {
  85753. return this._activeTargets.length;
  85754. },
  85755. enumerable: true,
  85756. configurable: true
  85757. });
  85758. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  85759. /**
  85760. * Gets the list of influences (one per target)
  85761. */
  85762. get: function () {
  85763. return this._influences;
  85764. },
  85765. enumerable: true,
  85766. configurable: true
  85767. });
  85768. /**
  85769. * Gets the active target at specified index. An active target is a target with an influence > 0
  85770. * @param index defines the index to check
  85771. * @returns the requested target
  85772. */
  85773. MorphTargetManager.prototype.getActiveTarget = function (index) {
  85774. return this._activeTargets.data[index];
  85775. };
  85776. /**
  85777. * Gets the target at specified index
  85778. * @param index defines the index to check
  85779. * @returns the requested target
  85780. */
  85781. MorphTargetManager.prototype.getTarget = function (index) {
  85782. return this._targets[index];
  85783. };
  85784. /**
  85785. * Add a new target to this manager
  85786. * @param target defines the target to add
  85787. */
  85788. MorphTargetManager.prototype.addTarget = function (target) {
  85789. var _this = this;
  85790. this._targets.push(target);
  85791. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  85792. _this._syncActiveTargets(needUpdate);
  85793. }));
  85794. this._syncActiveTargets(true);
  85795. };
  85796. /**
  85797. * Removes a target from the manager
  85798. * @param target defines the target to remove
  85799. */
  85800. MorphTargetManager.prototype.removeTarget = function (target) {
  85801. var index = this._targets.indexOf(target);
  85802. if (index >= 0) {
  85803. this._targets.splice(index, 1);
  85804. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  85805. this._syncActiveTargets(true);
  85806. }
  85807. };
  85808. /**
  85809. * Serializes the current manager into a Serialization object
  85810. * @returns the serialized object
  85811. */
  85812. MorphTargetManager.prototype.serialize = function () {
  85813. var serializationObject = {};
  85814. serializationObject.id = this.uniqueId;
  85815. serializationObject.targets = [];
  85816. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85817. var target = _a[_i];
  85818. serializationObject.targets.push(target.serialize());
  85819. }
  85820. return serializationObject;
  85821. };
  85822. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  85823. var influenceCount = 0;
  85824. this._activeTargets.reset();
  85825. this._supportsNormals = true;
  85826. this._supportsTangents = true;
  85827. this._vertexCount = 0;
  85828. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85829. var target = _a[_i];
  85830. this._activeTargets.push(target);
  85831. this._tempInfluences[influenceCount++] = target.influence;
  85832. var positions = target.getPositions();
  85833. if (positions) {
  85834. this._supportsNormals = this._supportsNormals && target.hasNormals;
  85835. this._supportsTangents = this._supportsTangents && target.hasTangents;
  85836. var vertexCount = positions.length / 3;
  85837. if (this._vertexCount === 0) {
  85838. this._vertexCount = vertexCount;
  85839. }
  85840. else if (this._vertexCount !== vertexCount) {
  85841. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  85842. return;
  85843. }
  85844. }
  85845. }
  85846. if (!this._influences || this._influences.length !== influenceCount) {
  85847. this._influences = new Float32Array(influenceCount);
  85848. }
  85849. for (var index = 0; index < influenceCount; index++) {
  85850. this._influences[index] = this._tempInfluences[index];
  85851. }
  85852. if (needUpdate) {
  85853. this.synchronize();
  85854. }
  85855. };
  85856. /**
  85857. * Syncrhonize the targets with all the meshes using this morph target manager
  85858. */
  85859. MorphTargetManager.prototype.synchronize = function () {
  85860. if (!this._scene) {
  85861. return;
  85862. }
  85863. // Flag meshes as dirty to resync with the active targets
  85864. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  85865. var mesh = _a[_i];
  85866. if (mesh.morphTargetManager === this) {
  85867. mesh._syncGeometryWithMorphTargetManager();
  85868. }
  85869. }
  85870. };
  85871. // Statics
  85872. /**
  85873. * Creates a new MorphTargetManager from serialized data
  85874. * @param serializationObject defines the serialized data
  85875. * @param scene defines the hosting scene
  85876. * @returns the new MorphTargetManager
  85877. */
  85878. MorphTargetManager.Parse = function (serializationObject, scene) {
  85879. var result = new MorphTargetManager(scene);
  85880. result._uniqueId = serializationObject.id;
  85881. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  85882. var targetData = _a[_i];
  85883. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  85884. }
  85885. return result;
  85886. };
  85887. return MorphTargetManager;
  85888. }());
  85889. BABYLON.MorphTargetManager = MorphTargetManager;
  85890. })(BABYLON || (BABYLON = {}));
  85891. //# sourceMappingURL=babylon.morphTargetManager.js.map
  85892. var BABYLON;
  85893. (function (BABYLON) {
  85894. var Octree = /** @class */ (function () {
  85895. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  85896. if (maxDepth === void 0) { maxDepth = 2; }
  85897. this.maxDepth = maxDepth;
  85898. this.dynamicContent = new Array();
  85899. this._maxBlockCapacity = maxBlockCapacity || 64;
  85900. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  85901. this._creationFunc = creationFunc;
  85902. }
  85903. // Methods
  85904. Octree.prototype.update = function (worldMin, worldMax, entries) {
  85905. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  85906. };
  85907. Octree.prototype.addMesh = function (entry) {
  85908. for (var index = 0; index < this.blocks.length; index++) {
  85909. var block = this.blocks[index];
  85910. block.addEntry(entry);
  85911. }
  85912. };
  85913. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  85914. this._selectionContent.reset();
  85915. for (var index = 0; index < this.blocks.length; index++) {
  85916. var block = this.blocks[index];
  85917. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  85918. }
  85919. if (allowDuplicate) {
  85920. this._selectionContent.concat(this.dynamicContent);
  85921. }
  85922. else {
  85923. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85924. }
  85925. return this._selectionContent;
  85926. };
  85927. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  85928. this._selectionContent.reset();
  85929. for (var index = 0; index < this.blocks.length; index++) {
  85930. var block = this.blocks[index];
  85931. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  85932. }
  85933. if (allowDuplicate) {
  85934. this._selectionContent.concat(this.dynamicContent);
  85935. }
  85936. else {
  85937. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85938. }
  85939. return this._selectionContent;
  85940. };
  85941. Octree.prototype.intersectsRay = function (ray) {
  85942. this._selectionContent.reset();
  85943. for (var index = 0; index < this.blocks.length; index++) {
  85944. var block = this.blocks[index];
  85945. block.intersectsRay(ray, this._selectionContent);
  85946. }
  85947. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85948. return this._selectionContent;
  85949. };
  85950. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  85951. target.blocks = new Array();
  85952. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  85953. // Segmenting space
  85954. for (var x = 0; x < 2; x++) {
  85955. for (var y = 0; y < 2; y++) {
  85956. for (var z = 0; z < 2; z++) {
  85957. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  85958. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  85959. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  85960. block.addEntries(entries);
  85961. target.blocks.push(block);
  85962. }
  85963. }
  85964. }
  85965. };
  85966. Octree.CreationFuncForMeshes = function (entry, block) {
  85967. var boundingInfo = entry.getBoundingInfo();
  85968. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  85969. block.entries.push(entry);
  85970. }
  85971. };
  85972. Octree.CreationFuncForSubMeshes = function (entry, block) {
  85973. var boundingInfo = entry.getBoundingInfo();
  85974. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  85975. block.entries.push(entry);
  85976. }
  85977. };
  85978. return Octree;
  85979. }());
  85980. BABYLON.Octree = Octree;
  85981. })(BABYLON || (BABYLON = {}));
  85982. //# sourceMappingURL=babylon.octree.js.map
  85983. var BABYLON;
  85984. (function (BABYLON) {
  85985. var OctreeBlock = /** @class */ (function () {
  85986. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  85987. this.entries = new Array();
  85988. this._boundingVectors = new Array();
  85989. this._capacity = capacity;
  85990. this._depth = depth;
  85991. this._maxDepth = maxDepth;
  85992. this._creationFunc = creationFunc;
  85993. this._minPoint = minPoint;
  85994. this._maxPoint = maxPoint;
  85995. this._boundingVectors.push(minPoint.clone());
  85996. this._boundingVectors.push(maxPoint.clone());
  85997. this._boundingVectors.push(minPoint.clone());
  85998. this._boundingVectors[2].x = maxPoint.x;
  85999. this._boundingVectors.push(minPoint.clone());
  86000. this._boundingVectors[3].y = maxPoint.y;
  86001. this._boundingVectors.push(minPoint.clone());
  86002. this._boundingVectors[4].z = maxPoint.z;
  86003. this._boundingVectors.push(maxPoint.clone());
  86004. this._boundingVectors[5].z = minPoint.z;
  86005. this._boundingVectors.push(maxPoint.clone());
  86006. this._boundingVectors[6].x = minPoint.x;
  86007. this._boundingVectors.push(maxPoint.clone());
  86008. this._boundingVectors[7].y = minPoint.y;
  86009. }
  86010. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  86011. // Property
  86012. get: function () {
  86013. return this._capacity;
  86014. },
  86015. enumerable: true,
  86016. configurable: true
  86017. });
  86018. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  86019. get: function () {
  86020. return this._minPoint;
  86021. },
  86022. enumerable: true,
  86023. configurable: true
  86024. });
  86025. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  86026. get: function () {
  86027. return this._maxPoint;
  86028. },
  86029. enumerable: true,
  86030. configurable: true
  86031. });
  86032. // Methods
  86033. OctreeBlock.prototype.addEntry = function (entry) {
  86034. if (this.blocks) {
  86035. for (var index = 0; index < this.blocks.length; index++) {
  86036. var block = this.blocks[index];
  86037. block.addEntry(entry);
  86038. }
  86039. return;
  86040. }
  86041. this._creationFunc(entry, this);
  86042. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  86043. this.createInnerBlocks();
  86044. }
  86045. };
  86046. OctreeBlock.prototype.addEntries = function (entries) {
  86047. for (var index = 0; index < entries.length; index++) {
  86048. var mesh = entries[index];
  86049. this.addEntry(mesh);
  86050. }
  86051. };
  86052. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  86053. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  86054. if (this.blocks) {
  86055. for (var index = 0; index < this.blocks.length; index++) {
  86056. var block = this.blocks[index];
  86057. block.select(frustumPlanes, selection, allowDuplicate);
  86058. }
  86059. return;
  86060. }
  86061. if (allowDuplicate) {
  86062. selection.concat(this.entries);
  86063. }
  86064. else {
  86065. selection.concatWithNoDuplicate(this.entries);
  86066. }
  86067. }
  86068. };
  86069. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  86070. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  86071. if (this.blocks) {
  86072. for (var index = 0; index < this.blocks.length; index++) {
  86073. var block = this.blocks[index];
  86074. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  86075. }
  86076. return;
  86077. }
  86078. if (allowDuplicate) {
  86079. selection.concat(this.entries);
  86080. }
  86081. else {
  86082. selection.concatWithNoDuplicate(this.entries);
  86083. }
  86084. }
  86085. };
  86086. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  86087. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  86088. if (this.blocks) {
  86089. for (var index = 0; index < this.blocks.length; index++) {
  86090. var block = this.blocks[index];
  86091. block.intersectsRay(ray, selection);
  86092. }
  86093. return;
  86094. }
  86095. selection.concatWithNoDuplicate(this.entries);
  86096. }
  86097. };
  86098. OctreeBlock.prototype.createInnerBlocks = function () {
  86099. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  86100. };
  86101. return OctreeBlock;
  86102. }());
  86103. BABYLON.OctreeBlock = OctreeBlock;
  86104. })(BABYLON || (BABYLON = {}));
  86105. //# sourceMappingURL=babylon.octreeBlock.js.map
  86106. var BABYLON;
  86107. (function (BABYLON) {
  86108. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  86109. __extends(VRDistortionCorrectionPostProcess, _super);
  86110. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  86111. var _this = _super.call(this, name, "vrDistortionCorrection", [
  86112. 'LensCenter',
  86113. 'Scale',
  86114. 'ScaleIn',
  86115. 'HmdWarpParam'
  86116. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  86117. _this._isRightEye = isRightEye;
  86118. _this._distortionFactors = vrMetrics.distortionK;
  86119. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  86120. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  86121. _this.adaptScaleToCurrentViewport = true;
  86122. _this.onSizeChangedObservable.add(function () {
  86123. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  86124. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  86125. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  86126. });
  86127. _this.onApplyObservable.add(function (effect) {
  86128. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  86129. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  86130. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  86131. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  86132. });
  86133. return _this;
  86134. }
  86135. return VRDistortionCorrectionPostProcess;
  86136. }(BABYLON.PostProcess));
  86137. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  86138. })(BABYLON || (BABYLON = {}));
  86139. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  86140. var BABYLON;
  86141. (function (BABYLON) {
  86142. /**
  86143. * Postprocess used to generate anaglyphic rendering
  86144. */
  86145. var AnaglyphPostProcess = /** @class */ (function (_super) {
  86146. __extends(AnaglyphPostProcess, _super);
  86147. /**
  86148. * Creates a new AnaglyphPostProcess
  86149. * @param name defines postprocess name
  86150. * @param options defines creation options or target ratio scale
  86151. * @param rigCameras defines cameras using this postprocess
  86152. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  86153. * @param engine defines hosting engine
  86154. * @param reusable defines if the postprocess will be reused multiple times per frame
  86155. */
  86156. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  86157. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  86158. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86159. _this.onApplyObservable.add(function (effect) {
  86160. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  86161. });
  86162. return _this;
  86163. }
  86164. return AnaglyphPostProcess;
  86165. }(BABYLON.PostProcess));
  86166. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  86167. })(BABYLON || (BABYLON = {}));
  86168. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  86169. var BABYLON;
  86170. (function (BABYLON) {
  86171. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  86172. __extends(StereoscopicInterlacePostProcess, _super);
  86173. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  86174. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  86175. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86176. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86177. _this.onSizeChangedObservable.add(function () {
  86178. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86179. });
  86180. _this.onApplyObservable.add(function (effect) {
  86181. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  86182. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  86183. });
  86184. return _this;
  86185. }
  86186. return StereoscopicInterlacePostProcess;
  86187. }(BABYLON.PostProcess));
  86188. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  86189. })(BABYLON || (BABYLON = {}));
  86190. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  86191. var BABYLON;
  86192. (function (BABYLON) {
  86193. /**
  86194. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  86195. * Screen rotation is taken into account.
  86196. */
  86197. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  86198. function FreeCameraDeviceOrientationInput() {
  86199. var _this = this;
  86200. this._screenOrientationAngle = 0;
  86201. this._screenQuaternion = new BABYLON.Quaternion();
  86202. this._alpha = 0;
  86203. this._beta = 0;
  86204. this._gamma = 0;
  86205. this._orientationChanged = function () {
  86206. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  86207. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  86208. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  86209. };
  86210. this._deviceOrientation = function (evt) {
  86211. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  86212. _this._beta = evt.beta !== null ? evt.beta : 0;
  86213. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  86214. };
  86215. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  86216. this._orientationChanged();
  86217. }
  86218. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  86219. get: function () {
  86220. return this._camera;
  86221. },
  86222. set: function (camera) {
  86223. this._camera = camera;
  86224. if (this._camera != null && !this._camera.rotationQuaternion) {
  86225. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  86226. }
  86227. },
  86228. enumerable: true,
  86229. configurable: true
  86230. });
  86231. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86232. window.addEventListener("orientationchange", this._orientationChanged);
  86233. window.addEventListener("deviceorientation", this._deviceOrientation);
  86234. //In certain cases, the attach control is called AFTER orientation was changed,
  86235. //So this is needed.
  86236. this._orientationChanged();
  86237. };
  86238. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  86239. window.removeEventListener("orientationchange", this._orientationChanged);
  86240. window.removeEventListener("deviceorientation", this._deviceOrientation);
  86241. };
  86242. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  86243. //if no device orientation provided, don't update the rotation.
  86244. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  86245. if (!this._alpha)
  86246. return;
  86247. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  86248. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  86249. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  86250. //Mirror on XY Plane
  86251. this._camera.rotationQuaternion.z *= -1;
  86252. this._camera.rotationQuaternion.w *= -1;
  86253. };
  86254. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  86255. return "FreeCameraDeviceOrientationInput";
  86256. };
  86257. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  86258. return "deviceOrientation";
  86259. };
  86260. return FreeCameraDeviceOrientationInput;
  86261. }());
  86262. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  86263. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  86264. })(BABYLON || (BABYLON = {}));
  86265. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  86266. var BABYLON;
  86267. (function (BABYLON) {
  86268. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  86269. function ArcRotateCameraVRDeviceOrientationInput() {
  86270. this.alphaCorrection = 1;
  86271. this.betaCorrection = 1;
  86272. this.gammaCorrection = 1;
  86273. this._alpha = 0;
  86274. this._gamma = 0;
  86275. this._dirty = false;
  86276. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  86277. }
  86278. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86279. this.camera.attachControl(element, noPreventDefault);
  86280. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  86281. };
  86282. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  86283. if (evt.alpha !== null) {
  86284. this._alpha = +evt.alpha | 0;
  86285. }
  86286. if (evt.gamma !== null) {
  86287. this._gamma = +evt.gamma | 0;
  86288. }
  86289. this._dirty = true;
  86290. };
  86291. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  86292. if (this._dirty) {
  86293. this._dirty = false;
  86294. if (this._gamma < 0) {
  86295. this._gamma = 180 + this._gamma;
  86296. }
  86297. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  86298. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  86299. }
  86300. };
  86301. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  86302. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  86303. };
  86304. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  86305. return "ArcRotateCameraVRDeviceOrientationInput";
  86306. };
  86307. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  86308. return "VRDeviceOrientation";
  86309. };
  86310. return ArcRotateCameraVRDeviceOrientationInput;
  86311. }());
  86312. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  86313. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  86314. })(BABYLON || (BABYLON = {}));
  86315. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  86316. var BABYLON;
  86317. (function (BABYLON) {
  86318. var VRCameraMetrics = /** @class */ (function () {
  86319. function VRCameraMetrics() {
  86320. this.compensateDistortion = true;
  86321. }
  86322. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  86323. get: function () {
  86324. return this.hResolution / (2 * this.vResolution);
  86325. },
  86326. enumerable: true,
  86327. configurable: true
  86328. });
  86329. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  86330. get: function () {
  86331. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  86332. },
  86333. enumerable: true,
  86334. configurable: true
  86335. });
  86336. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  86337. get: function () {
  86338. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86339. var h = (4 * meters) / this.hScreenSize;
  86340. return BABYLON.Matrix.Translation(h, 0, 0);
  86341. },
  86342. enumerable: true,
  86343. configurable: true
  86344. });
  86345. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  86346. get: function () {
  86347. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86348. var h = (4 * meters) / this.hScreenSize;
  86349. return BABYLON.Matrix.Translation(-h, 0, 0);
  86350. },
  86351. enumerable: true,
  86352. configurable: true
  86353. });
  86354. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  86355. get: function () {
  86356. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  86357. },
  86358. enumerable: true,
  86359. configurable: true
  86360. });
  86361. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  86362. get: function () {
  86363. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  86364. },
  86365. enumerable: true,
  86366. configurable: true
  86367. });
  86368. VRCameraMetrics.GetDefault = function () {
  86369. var result = new VRCameraMetrics();
  86370. result.hResolution = 1280;
  86371. result.vResolution = 800;
  86372. result.hScreenSize = 0.149759993;
  86373. result.vScreenSize = 0.0935999975;
  86374. result.vScreenCenter = 0.0467999987;
  86375. result.eyeToScreenDistance = 0.0410000011;
  86376. result.lensSeparationDistance = 0.0635000020;
  86377. result.interpupillaryDistance = 0.0640000030;
  86378. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  86379. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  86380. result.postProcessScaleFactor = 1.714605507808412;
  86381. result.lensCenterOffset = 0.151976421;
  86382. return result;
  86383. };
  86384. return VRCameraMetrics;
  86385. }());
  86386. BABYLON.VRCameraMetrics = VRCameraMetrics;
  86387. })(BABYLON || (BABYLON = {}));
  86388. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  86389. var BABYLON;
  86390. (function (BABYLON) {
  86391. /**
  86392. * This represents a WebVR camera.
  86393. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  86394. * @example http://doc.babylonjs.com/how_to/webvr_camera
  86395. */
  86396. var WebVRFreeCamera = /** @class */ (function (_super) {
  86397. __extends(WebVRFreeCamera, _super);
  86398. /**
  86399. * Instantiates a WebVRFreeCamera.
  86400. * @param name The name of the WebVRFreeCamera
  86401. * @param position The starting anchor position for the camera
  86402. * @param scene The scene the camera belongs to
  86403. * @param webVROptions a set of customizable options for the webVRCamera
  86404. */
  86405. function WebVRFreeCamera(name, position, scene, webVROptions) {
  86406. if (webVROptions === void 0) { webVROptions = {}; }
  86407. var _this = _super.call(this, name, position, scene) || this;
  86408. _this.webVROptions = webVROptions;
  86409. /**
  86410. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  86411. */
  86412. _this._vrDevice = null;
  86413. /**
  86414. * The rawPose of the vrDevice.
  86415. */
  86416. _this.rawPose = null;
  86417. _this._specsVersion = "1.1";
  86418. _this._attached = false;
  86419. _this._descendants = [];
  86420. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  86421. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  86422. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  86423. _this._standingMatrix = null;
  86424. /**
  86425. * Represents device position in babylon space.
  86426. */
  86427. _this.devicePosition = BABYLON.Vector3.Zero();
  86428. /**
  86429. * Represents device rotation in babylon space.
  86430. */
  86431. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  86432. /**
  86433. * The scale of the device to be used when translating from device space to babylon space.
  86434. */
  86435. _this.deviceScaleFactor = 1;
  86436. _this._deviceToWorld = BABYLON.Matrix.Identity();
  86437. _this._worldToDevice = BABYLON.Matrix.Identity();
  86438. /**
  86439. * References to the webVR controllers for the vrDevice.
  86440. */
  86441. _this.controllers = [];
  86442. /**
  86443. * Emits an event when a controller is attached.
  86444. */
  86445. _this.onControllersAttachedObservable = new BABYLON.Observable();
  86446. /**
  86447. * Emits an event when a controller's mesh has been loaded;
  86448. */
  86449. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  86450. /**
  86451. * If the rig cameras be used as parent instead of this camera.
  86452. */
  86453. _this.rigParenting = true;
  86454. _this._defaultHeight = undefined;
  86455. _this._workingVector = BABYLON.Vector3.Zero();
  86456. _this._oneVector = BABYLON.Vector3.One();
  86457. _this._workingMatrix = BABYLON.Matrix.Identity();
  86458. _this._cache.position = BABYLON.Vector3.Zero();
  86459. if (webVROptions.defaultHeight) {
  86460. _this._defaultHeight = webVROptions.defaultHeight;
  86461. _this.position.y = _this._defaultHeight;
  86462. }
  86463. _this.minZ = 0.1;
  86464. //legacy support - the compensation boolean was removed.
  86465. if (arguments.length === 5) {
  86466. _this.webVROptions = arguments[4];
  86467. }
  86468. // default webVR options
  86469. if (_this.webVROptions.trackPosition == undefined) {
  86470. _this.webVROptions.trackPosition = true;
  86471. }
  86472. if (_this.webVROptions.controllerMeshes == undefined) {
  86473. _this.webVROptions.controllerMeshes = true;
  86474. }
  86475. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  86476. _this.webVROptions.defaultLightingOnControllers = true;
  86477. }
  86478. _this.rotationQuaternion = new BABYLON.Quaternion();
  86479. if (_this.webVROptions && _this.webVROptions.positionScale) {
  86480. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  86481. }
  86482. //enable VR
  86483. var engine = _this.getEngine();
  86484. _this._onVREnabled = function (success) { if (success) {
  86485. _this.initControllers();
  86486. } };
  86487. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  86488. engine.initWebVR().add(function (event) {
  86489. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  86490. return;
  86491. }
  86492. _this._vrDevice = event.vrDisplay;
  86493. //reset the rig parameters.
  86494. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  86495. if (_this._attached) {
  86496. _this.getEngine().enableVR();
  86497. }
  86498. });
  86499. if (typeof (VRFrameData) !== "undefined")
  86500. _this._frameData = new VRFrameData();
  86501. /**
  86502. * The idea behind the following lines:
  86503. * objects that have the camera as parent should actually have the rig cameras as a parent.
  86504. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  86505. * the second will not show it correctly.
  86506. *
  86507. * To solve this - each object that has the camera as parent will be added to a protected array.
  86508. * When the rig camera renders, it will take this array and set all of those to be its children.
  86509. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  86510. * Amazing!
  86511. */
  86512. scene.onBeforeCameraRenderObservable.add(function (camera) {
  86513. if (camera.parent === _this && _this.rigParenting) {
  86514. _this._descendants = _this.getDescendants(true, function (n) {
  86515. // don't take the cameras or the controllers!
  86516. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  86517. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  86518. return !isController && !isRigCamera;
  86519. });
  86520. _this._descendants.forEach(function (node) {
  86521. node.parent = camera;
  86522. });
  86523. }
  86524. });
  86525. scene.onAfterCameraRenderObservable.add(function (camera) {
  86526. if (camera.parent === _this && _this.rigParenting) {
  86527. _this._descendants.forEach(function (node) {
  86528. node.parent = _this;
  86529. });
  86530. }
  86531. });
  86532. return _this;
  86533. }
  86534. /**
  86535. * Gets the device distance from the ground in meters.
  86536. * @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.
  86537. */
  86538. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  86539. if (this._standingMatrix) {
  86540. // Add standing matrix offset to get real offset from ground in room
  86541. this._standingMatrix.getTranslationToRef(this._workingVector);
  86542. return this._deviceRoomPosition.y + this._workingVector.y;
  86543. }
  86544. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  86545. return this._defaultHeight || 0;
  86546. };
  86547. /**
  86548. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86549. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  86550. */
  86551. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  86552. var _this = this;
  86553. if (callback === void 0) { callback = function (bool) { }; }
  86554. // Use standing matrix if available
  86555. this.getEngine().initWebVRAsync().then(function (result) {
  86556. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  86557. callback(false);
  86558. }
  86559. else {
  86560. _this._standingMatrix = new BABYLON.Matrix();
  86561. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  86562. if (!_this.getScene().useRightHandedSystem) {
  86563. [2, 6, 8, 9, 14].forEach(function (num) {
  86564. if (_this._standingMatrix) {
  86565. _this._standingMatrix.m[num] *= -1;
  86566. }
  86567. });
  86568. }
  86569. callback(true);
  86570. }
  86571. });
  86572. };
  86573. /**
  86574. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86575. * @returns A promise with a boolean set to if the standing matrix is supported.
  86576. */
  86577. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  86578. var _this = this;
  86579. return new Promise(function (res, rej) {
  86580. _this.useStandingMatrix(function (supported) {
  86581. res(supported);
  86582. });
  86583. });
  86584. };
  86585. /**
  86586. * Disposes the camera
  86587. */
  86588. WebVRFreeCamera.prototype.dispose = function () {
  86589. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  86590. _super.prototype.dispose.call(this);
  86591. };
  86592. /**
  86593. * Gets a vrController by name.
  86594. * @param name The name of the controller to retreive
  86595. * @returns the controller matching the name specified or null if not found
  86596. */
  86597. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  86598. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  86599. var gp = _a[_i];
  86600. if (gp.hand === name) {
  86601. return gp;
  86602. }
  86603. }
  86604. return null;
  86605. };
  86606. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  86607. /**
  86608. * The controller corrisponding to the users left hand.
  86609. */
  86610. get: function () {
  86611. if (!this._leftController) {
  86612. this._leftController = this.getControllerByName("left");
  86613. }
  86614. return this._leftController;
  86615. },
  86616. enumerable: true,
  86617. configurable: true
  86618. });
  86619. ;
  86620. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  86621. /**
  86622. * The controller corrisponding to the users right hand.
  86623. */
  86624. get: function () {
  86625. if (!this._rightController) {
  86626. this._rightController = this.getControllerByName("right");
  86627. }
  86628. return this._rightController;
  86629. },
  86630. enumerable: true,
  86631. configurable: true
  86632. });
  86633. ;
  86634. /**
  86635. * Casts a ray forward from the vrCamera's gaze.
  86636. * @param length Length of the ray (default: 100)
  86637. * @returns the ray corrisponding to the gaze
  86638. */
  86639. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  86640. if (length === void 0) { length = 100; }
  86641. if (this.leftCamera) {
  86642. // Use left eye to avoid computation to compute center on every call
  86643. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  86644. }
  86645. else {
  86646. return _super.prototype.getForwardRay.call(this, length);
  86647. }
  86648. };
  86649. /**
  86650. * Updates the camera based on device's frame data
  86651. */
  86652. WebVRFreeCamera.prototype._checkInputs = function () {
  86653. if (this._vrDevice && this._vrDevice.isPresenting) {
  86654. this._vrDevice.getFrameData(this._frameData);
  86655. this.updateFromDevice(this._frameData.pose);
  86656. }
  86657. _super.prototype._checkInputs.call(this);
  86658. };
  86659. /**
  86660. * Updates the poseControlled values based on the input device pose.
  86661. * @param poseData Pose coming from the device
  86662. */
  86663. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  86664. if (poseData && poseData.orientation) {
  86665. this.rawPose = poseData;
  86666. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  86667. if (this.getScene().useRightHandedSystem) {
  86668. this._deviceRoomRotationQuaternion.z *= -1;
  86669. this._deviceRoomRotationQuaternion.w *= -1;
  86670. }
  86671. if (this.webVROptions.trackPosition && this.rawPose.position) {
  86672. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  86673. if (this.getScene().useRightHandedSystem) {
  86674. this._deviceRoomPosition.z *= -1;
  86675. }
  86676. }
  86677. }
  86678. };
  86679. /**
  86680. * WebVR's attach control will start broadcasting frames to the device.
  86681. * Note that in certain browsers (chrome for example) this function must be called
  86682. * within a user-interaction callback. Example:
  86683. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  86684. *
  86685. * @param element html element to attach the vrDevice to
  86686. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  86687. */
  86688. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  86689. _super.prototype.attachControl.call(this, element, noPreventDefault);
  86690. this._attached = true;
  86691. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  86692. if (this._vrDevice) {
  86693. this.getEngine().enableVR();
  86694. }
  86695. };
  86696. /**
  86697. * Detaches the camera from the html element and disables VR
  86698. *
  86699. * @param element html element to detach from
  86700. */
  86701. WebVRFreeCamera.prototype.detachControl = function (element) {
  86702. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  86703. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  86704. _super.prototype.detachControl.call(this, element);
  86705. this._attached = false;
  86706. this.getEngine().disableVR();
  86707. };
  86708. /**
  86709. * @returns the name of this class
  86710. */
  86711. WebVRFreeCamera.prototype.getClassName = function () {
  86712. return "WebVRFreeCamera";
  86713. };
  86714. /**
  86715. * Calls resetPose on the vrDisplay
  86716. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  86717. */
  86718. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  86719. //uses the vrDisplay's "resetPose()".
  86720. //pitch and roll won't be affected.
  86721. this._vrDevice.resetPose();
  86722. };
  86723. /**
  86724. * Updates the rig cameras (left and right eye)
  86725. */
  86726. WebVRFreeCamera.prototype._updateRigCameras = function () {
  86727. var camLeft = this._rigCameras[0];
  86728. var camRight = this._rigCameras[1];
  86729. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86730. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86731. camLeft.position.copyFrom(this._deviceRoomPosition);
  86732. camRight.position.copyFrom(this._deviceRoomPosition);
  86733. };
  86734. /**
  86735. * Updates the cached values of the camera
  86736. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  86737. */
  86738. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  86739. var _this = this;
  86740. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  86741. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  86742. if (!this.updateCacheCalled) {
  86743. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  86744. this.updateCacheCalled = true;
  86745. this.update();
  86746. }
  86747. // Set working vector to the device position in room space rotated by the new rotation
  86748. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  86749. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  86750. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  86751. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  86752. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  86753. // Add translation from anchor position
  86754. this._deviceToWorld.getTranslationToRef(this._workingVector);
  86755. this._workingVector.addInPlace(this.position);
  86756. this._workingVector.subtractInPlace(this._cache.position);
  86757. this._deviceToWorld.setTranslation(this._workingVector);
  86758. // Set an inverted matrix to be used when updating the camera
  86759. this._deviceToWorld.invertToRef(this._worldToDevice);
  86760. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  86761. this.controllers.forEach(function (controller) {
  86762. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  86763. controller.update();
  86764. });
  86765. }
  86766. if (!ignoreParentClass) {
  86767. _super.prototype._updateCache.call(this);
  86768. }
  86769. this.updateCacheCalled = false;
  86770. };
  86771. /**
  86772. * Updates the current device position and rotation in the babylon world
  86773. */
  86774. WebVRFreeCamera.prototype.update = function () {
  86775. // Get current device position in babylon world
  86776. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  86777. // Get current device rotation in babylon world
  86778. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  86779. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  86780. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  86781. _super.prototype.update.call(this);
  86782. };
  86783. /**
  86784. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  86785. * @returns an identity matrix
  86786. */
  86787. WebVRFreeCamera.prototype._getViewMatrix = function () {
  86788. return BABYLON.Matrix.Identity();
  86789. };
  86790. /**
  86791. * This function is called by the two RIG cameras.
  86792. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  86793. */
  86794. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  86795. var _this = this;
  86796. // Update the parent camera prior to using a child camera to avoid desynchronization
  86797. var parentCamera = this._cameraRigParams["parentCamera"];
  86798. parentCamera._updateCache();
  86799. //WebVR 1.1
  86800. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  86801. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  86802. if (!this.getScene().useRightHandedSystem) {
  86803. [2, 6, 8, 9, 14].forEach(function (num) {
  86804. _this._webvrViewMatrix.m[num] *= -1;
  86805. });
  86806. }
  86807. // update the camera rotation matrix
  86808. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  86809. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  86810. // Computing target and final matrix
  86811. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  86812. // should the view matrix be updated with scale and position offset?
  86813. if (parentCamera.deviceScaleFactor !== 1) {
  86814. this._webvrViewMatrix.invert();
  86815. // scale the position, if set
  86816. if (parentCamera.deviceScaleFactor) {
  86817. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  86818. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  86819. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  86820. }
  86821. this._webvrViewMatrix.invert();
  86822. }
  86823. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  86824. // Compute global position
  86825. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  86826. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  86827. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  86828. this._workingMatrix.getTranslationToRef(this._globalPosition);
  86829. this._markSyncedWithParent();
  86830. return this._webvrViewMatrix;
  86831. };
  86832. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  86833. var _this = this;
  86834. var parentCamera = this.parent;
  86835. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  86836. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  86837. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  86838. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  86839. //babylon compatible matrix
  86840. if (!this.getScene().useRightHandedSystem) {
  86841. [8, 9, 10, 11].forEach(function (num) {
  86842. _this._projectionMatrix.m[num] *= -1;
  86843. });
  86844. }
  86845. return this._projectionMatrix;
  86846. };
  86847. /**
  86848. * Initializes the controllers and their meshes
  86849. */
  86850. WebVRFreeCamera.prototype.initControllers = function () {
  86851. var _this = this;
  86852. this.controllers = [];
  86853. var manager = this.getScene().gamepadManager;
  86854. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  86855. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  86856. var webVrController = gamepad;
  86857. if (webVrController.defaultModel) {
  86858. webVrController.defaultModel.setEnabled(false);
  86859. }
  86860. if (webVrController.hand === "right") {
  86861. _this._rightController = null;
  86862. }
  86863. if (webVrController.hand === "left") {
  86864. _this._leftController = null;
  86865. }
  86866. var controllerIndex = _this.controllers.indexOf(webVrController);
  86867. if (controllerIndex !== -1) {
  86868. _this.controllers.splice(controllerIndex, 1);
  86869. }
  86870. }
  86871. });
  86872. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  86873. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  86874. var webVrController_1 = gamepad;
  86875. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  86876. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  86877. if (_this.webVROptions.controllerMeshes) {
  86878. if (webVrController_1.defaultModel) {
  86879. webVrController_1.defaultModel.setEnabled(true);
  86880. }
  86881. else {
  86882. // Load the meshes
  86883. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  86884. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  86885. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  86886. if (_this.webVROptions.defaultLightingOnControllers) {
  86887. if (!_this._lightOnControllers) {
  86888. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  86889. }
  86890. var activateLightOnSubMeshes_1 = function (mesh, light) {
  86891. var children = mesh.getChildren();
  86892. if (children.length !== 0) {
  86893. children.forEach(function (mesh) {
  86894. light.includedOnlyMeshes.push(mesh);
  86895. activateLightOnSubMeshes_1(mesh, light);
  86896. });
  86897. }
  86898. };
  86899. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  86900. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  86901. }
  86902. });
  86903. }
  86904. }
  86905. webVrController_1.attachToPoseControlledCamera(_this);
  86906. // since this is async - sanity check. Is the controller already stored?
  86907. if (_this.controllers.indexOf(webVrController_1) === -1) {
  86908. //add to the controllers array
  86909. _this.controllers.push(webVrController_1);
  86910. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  86911. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  86912. // So we're overriding setting left & right manually to be sure
  86913. var firstViveWandDetected = false;
  86914. for (var i = 0; i < _this.controllers.length; i++) {
  86915. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  86916. if (!firstViveWandDetected) {
  86917. firstViveWandDetected = true;
  86918. _this.controllers[i].hand = "left";
  86919. }
  86920. else {
  86921. _this.controllers[i].hand = "right";
  86922. }
  86923. }
  86924. }
  86925. //did we find enough controllers? Great! let the developer know.
  86926. if (_this.controllers.length >= 2) {
  86927. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  86928. }
  86929. }
  86930. }
  86931. });
  86932. };
  86933. return WebVRFreeCamera;
  86934. }(BABYLON.FreeCamera));
  86935. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  86936. })(BABYLON || (BABYLON = {}));
  86937. //# sourceMappingURL=babylon.webVRCamera.js.map
  86938. var BABYLON;
  86939. (function (BABYLON) {
  86940. // We're mainly based on the logic defined into the FreeCamera code
  86941. /**
  86942. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  86943. * being tilted forward or back and left or right.
  86944. */
  86945. var DeviceOrientationCamera = /** @class */ (function (_super) {
  86946. __extends(DeviceOrientationCamera, _super);
  86947. /**
  86948. * Creates a new device orientation camera
  86949. * @param name The name of the camera
  86950. * @param position The start position camera
  86951. * @param scene The scene the camera belongs to
  86952. */
  86953. function DeviceOrientationCamera(name, position, scene) {
  86954. var _this = _super.call(this, name, position, scene) || this;
  86955. _this._quaternionCache = new BABYLON.Quaternion();
  86956. _this.inputs.addDeviceOrientation();
  86957. return _this;
  86958. }
  86959. /**
  86960. * Gets the current instance class name ("DeviceOrientationCamera").
  86961. * This helps avoiding instanceof at run time.
  86962. * @returns the class name
  86963. */
  86964. DeviceOrientationCamera.prototype.getClassName = function () {
  86965. return "DeviceOrientationCamera";
  86966. };
  86967. /**
  86968. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  86969. */
  86970. DeviceOrientationCamera.prototype._checkInputs = function () {
  86971. _super.prototype._checkInputs.call(this);
  86972. this._quaternionCache.copyFrom(this.rotationQuaternion);
  86973. if (this._initialQuaternion) {
  86974. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  86975. }
  86976. };
  86977. /**
  86978. * Reset the camera to its default orientation on the specified axis only.
  86979. * @param axis The axis to reset
  86980. */
  86981. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  86982. var _this = this;
  86983. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  86984. //can only work if this camera has a rotation quaternion already.
  86985. if (!this.rotationQuaternion)
  86986. return;
  86987. if (!this._initialQuaternion) {
  86988. this._initialQuaternion = new BABYLON.Quaternion();
  86989. }
  86990. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  86991. ['x', 'y', 'z'].forEach(function (axisName) {
  86992. if (!axis[axisName]) {
  86993. _this._initialQuaternion[axisName] = 0;
  86994. }
  86995. else {
  86996. _this._initialQuaternion[axisName] *= -1;
  86997. }
  86998. });
  86999. this._initialQuaternion.normalize();
  87000. //force rotation update
  87001. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87002. };
  87003. return DeviceOrientationCamera;
  87004. }(BABYLON.FreeCamera));
  87005. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  87006. })(BABYLON || (BABYLON = {}));
  87007. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  87008. var BABYLON;
  87009. (function (BABYLON) {
  87010. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  87011. __extends(VRDeviceOrientationFreeCamera, _super);
  87012. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87013. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87014. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87015. var _this = _super.call(this, name, position, scene) || this;
  87016. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87017. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87018. return _this;
  87019. }
  87020. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  87021. return "VRDeviceOrientationFreeCamera";
  87022. };
  87023. return VRDeviceOrientationFreeCamera;
  87024. }(BABYLON.DeviceOrientationCamera));
  87025. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  87026. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  87027. __extends(VRDeviceOrientationGamepadCamera, _super);
  87028. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87029. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87030. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87031. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  87032. _this.inputs.addGamepad();
  87033. return _this;
  87034. }
  87035. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  87036. return "VRDeviceOrientationGamepadCamera";
  87037. };
  87038. return VRDeviceOrientationGamepadCamera;
  87039. }(VRDeviceOrientationFreeCamera));
  87040. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  87041. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  87042. __extends(VRDeviceOrientationArcRotateCamera, _super);
  87043. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  87044. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87045. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87046. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87047. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87048. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87049. _this.inputs.addVRDeviceOrientation();
  87050. return _this;
  87051. }
  87052. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  87053. return "VRDeviceOrientationArcRotateCamera";
  87054. };
  87055. return VRDeviceOrientationArcRotateCamera;
  87056. }(BABYLON.ArcRotateCamera));
  87057. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  87058. })(BABYLON || (BABYLON = {}));
  87059. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  87060. var BABYLON;
  87061. (function (BABYLON) {
  87062. /**
  87063. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  87064. */
  87065. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  87066. __extends(AnaglyphFreeCamera, _super);
  87067. /**
  87068. * Creates a new AnaglyphFreeCamera
  87069. * @param name defines camera name
  87070. * @param position defines initial position
  87071. * @param interaxialDistance defines distance between each color axis
  87072. * @param scene defines the hosting scene
  87073. */
  87074. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  87075. var _this = _super.call(this, name, position, scene) || this;
  87076. _this.interaxialDistance = interaxialDistance;
  87077. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87078. return _this;
  87079. }
  87080. /**
  87081. * Gets camera class name
  87082. * @returns AnaglyphFreeCamera
  87083. */
  87084. AnaglyphFreeCamera.prototype.getClassName = function () {
  87085. return "AnaglyphFreeCamera";
  87086. };
  87087. return AnaglyphFreeCamera;
  87088. }(BABYLON.FreeCamera));
  87089. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  87090. /**
  87091. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  87092. */
  87093. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  87094. __extends(AnaglyphArcRotateCamera, _super);
  87095. /**
  87096. * Creates a new AnaglyphArcRotateCamera
  87097. * @param name defines camera name
  87098. * @param alpha defines alpha angle (in radians)
  87099. * @param beta defines beta angle (in radians)
  87100. * @param radius defines radius
  87101. * @param target defines camera target
  87102. * @param interaxialDistance defines distance between each color axis
  87103. * @param scene defines the hosting scene
  87104. */
  87105. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  87106. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87107. _this.interaxialDistance = interaxialDistance;
  87108. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87109. return _this;
  87110. }
  87111. /**
  87112. * Gets camera class name
  87113. * @returns AnaglyphArcRotateCamera
  87114. */
  87115. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  87116. return "AnaglyphArcRotateCamera";
  87117. };
  87118. return AnaglyphArcRotateCamera;
  87119. }(BABYLON.ArcRotateCamera));
  87120. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  87121. /**
  87122. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  87123. */
  87124. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  87125. __extends(AnaglyphGamepadCamera, _super);
  87126. /**
  87127. * Creates a new AnaglyphGamepadCamera
  87128. * @param name defines camera name
  87129. * @param position defines initial position
  87130. * @param interaxialDistance defines distance between each color axis
  87131. * @param scene defines the hosting scene
  87132. */
  87133. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  87134. var _this = _super.call(this, name, position, scene) || this;
  87135. _this.interaxialDistance = interaxialDistance;
  87136. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87137. return _this;
  87138. }
  87139. /**
  87140. * Gets camera class name
  87141. * @returns AnaglyphGamepadCamera
  87142. */
  87143. AnaglyphGamepadCamera.prototype.getClassName = function () {
  87144. return "AnaglyphGamepadCamera";
  87145. };
  87146. return AnaglyphGamepadCamera;
  87147. }(BABYLON.GamepadCamera));
  87148. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  87149. /**
  87150. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  87151. */
  87152. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  87153. __extends(AnaglyphUniversalCamera, _super);
  87154. /**
  87155. * Creates a new AnaglyphUniversalCamera
  87156. * @param name defines camera name
  87157. * @param position defines initial position
  87158. * @param interaxialDistance defines distance between each color axis
  87159. * @param scene defines the hosting scene
  87160. */
  87161. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  87162. var _this = _super.call(this, name, position, scene) || this;
  87163. _this.interaxialDistance = interaxialDistance;
  87164. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87165. return _this;
  87166. }
  87167. /**
  87168. * Gets camera class name
  87169. * @returns AnaglyphUniversalCamera
  87170. */
  87171. AnaglyphUniversalCamera.prototype.getClassName = function () {
  87172. return "AnaglyphUniversalCamera";
  87173. };
  87174. return AnaglyphUniversalCamera;
  87175. }(BABYLON.UniversalCamera));
  87176. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  87177. /**
  87178. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  87179. */
  87180. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  87181. __extends(StereoscopicFreeCamera, _super);
  87182. /**
  87183. * Creates a new StereoscopicFreeCamera
  87184. * @param name defines camera name
  87185. * @param position defines initial position
  87186. * @param interaxialDistance defines distance between each color axis
  87187. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87188. * @param scene defines the hosting scene
  87189. */
  87190. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87191. var _this = _super.call(this, name, position, scene) || this;
  87192. _this.interaxialDistance = interaxialDistance;
  87193. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87194. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87195. return _this;
  87196. }
  87197. /**
  87198. * Gets camera class name
  87199. * @returns StereoscopicFreeCamera
  87200. */
  87201. StereoscopicFreeCamera.prototype.getClassName = function () {
  87202. return "StereoscopicFreeCamera";
  87203. };
  87204. return StereoscopicFreeCamera;
  87205. }(BABYLON.FreeCamera));
  87206. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  87207. /**
  87208. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  87209. */
  87210. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  87211. __extends(StereoscopicArcRotateCamera, _super);
  87212. /**
  87213. * Creates a new StereoscopicArcRotateCamera
  87214. * @param name defines camera name
  87215. * @param alpha defines alpha angle (in radians)
  87216. * @param beta defines beta angle (in radians)
  87217. * @param radius defines radius
  87218. * @param target defines camera target
  87219. * @param interaxialDistance defines distance between each color axis
  87220. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87221. * @param scene defines the hosting scene
  87222. */
  87223. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  87224. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87225. _this.interaxialDistance = interaxialDistance;
  87226. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87227. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87228. return _this;
  87229. }
  87230. /**
  87231. * Gets camera class name
  87232. * @returns StereoscopicArcRotateCamera
  87233. */
  87234. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  87235. return "StereoscopicArcRotateCamera";
  87236. };
  87237. return StereoscopicArcRotateCamera;
  87238. }(BABYLON.ArcRotateCamera));
  87239. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  87240. /**
  87241. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  87242. */
  87243. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  87244. __extends(StereoscopicGamepadCamera, _super);
  87245. /**
  87246. * Creates a new StereoscopicGamepadCamera
  87247. * @param name defines camera name
  87248. * @param position defines initial position
  87249. * @param interaxialDistance defines distance between each color axis
  87250. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87251. * @param scene defines the hosting scene
  87252. */
  87253. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87254. var _this = _super.call(this, name, position, scene) || this;
  87255. _this.interaxialDistance = interaxialDistance;
  87256. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87257. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87258. return _this;
  87259. }
  87260. /**
  87261. * Gets camera class name
  87262. * @returns StereoscopicGamepadCamera
  87263. */
  87264. StereoscopicGamepadCamera.prototype.getClassName = function () {
  87265. return "StereoscopicGamepadCamera";
  87266. };
  87267. return StereoscopicGamepadCamera;
  87268. }(BABYLON.GamepadCamera));
  87269. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  87270. /**
  87271. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  87272. */
  87273. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  87274. __extends(StereoscopicUniversalCamera, _super);
  87275. /**
  87276. * Creates a new StereoscopicUniversalCamera
  87277. * @param name defines camera name
  87278. * @param position defines initial position
  87279. * @param interaxialDistance defines distance between each color axis
  87280. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87281. * @param scene defines the hosting scene
  87282. */
  87283. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87284. var _this = _super.call(this, name, position, scene) || this;
  87285. _this.interaxialDistance = interaxialDistance;
  87286. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87287. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87288. return _this;
  87289. }
  87290. /**
  87291. * Gets camera class name
  87292. * @returns StereoscopicUniversalCamera
  87293. */
  87294. StereoscopicUniversalCamera.prototype.getClassName = function () {
  87295. return "StereoscopicUniversalCamera";
  87296. };
  87297. return StereoscopicUniversalCamera;
  87298. }(BABYLON.UniversalCamera));
  87299. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  87300. })(BABYLON || (BABYLON = {}));
  87301. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  87302. var BABYLON;
  87303. (function (BABYLON) {
  87304. var VRExperienceHelperGazer = /** @class */ (function () {
  87305. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  87306. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  87307. this.scene = scene;
  87308. this._pointerDownOnMeshAsked = false;
  87309. this._isActionableMesh = false;
  87310. this._teleportationRequestInitiated = false;
  87311. this._teleportationBackRequestInitiated = false;
  87312. this._dpadPressed = true;
  87313. this._activePointer = false;
  87314. this._id = VRExperienceHelperGazer._idCounter++;
  87315. // Gaze tracker
  87316. if (!gazeTrackerToClone) {
  87317. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  87318. this._gazeTracker.bakeCurrentTransformIntoVertices();
  87319. this._gazeTracker.isPickable = false;
  87320. this._gazeTracker.isVisible = false;
  87321. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  87322. targetMat.specularColor = BABYLON.Color3.Black();
  87323. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87324. targetMat.backFaceCulling = false;
  87325. this._gazeTracker.material = targetMat;
  87326. }
  87327. else {
  87328. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  87329. }
  87330. }
  87331. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  87332. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  87333. };
  87334. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  87335. this._pointerDownOnMeshAsked = true;
  87336. if (this._currentMeshSelected && this._currentHit) {
  87337. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  87338. }
  87339. };
  87340. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  87341. if (this._currentMeshSelected && this._currentHit) {
  87342. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  87343. }
  87344. this._pointerDownOnMeshAsked = false;
  87345. };
  87346. VRExperienceHelperGazer.prototype._activatePointer = function () {
  87347. this._activePointer = true;
  87348. };
  87349. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  87350. this._activePointer = false;
  87351. };
  87352. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  87353. };
  87354. VRExperienceHelperGazer.prototype.dispose = function () {
  87355. this._interactionsEnabled = false;
  87356. this._teleportationEnabled = false;
  87357. };
  87358. VRExperienceHelperGazer._idCounter = 0;
  87359. return VRExperienceHelperGazer;
  87360. }());
  87361. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  87362. __extends(VRExperienceHelperControllerGazer, _super);
  87363. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  87364. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  87365. _this.webVRController = webVRController;
  87366. // Laser pointer
  87367. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  87368. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  87369. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87370. laserPointerMaterial.alpha = 0.6;
  87371. _this._laserPointer.material = laserPointerMaterial;
  87372. _this._laserPointer.rotation.x = Math.PI / 2;
  87373. _this._laserPointer.position.z = -0.5;
  87374. _this._laserPointer.isVisible = false;
  87375. if (!webVRController.mesh) {
  87376. // Create an empty mesh that is used prior to loading the high quality model
  87377. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  87378. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  87379. preloadPointerPose.rotation.x = -0.7;
  87380. preloadMesh.addChild(preloadPointerPose);
  87381. webVRController.attachToMesh(preloadMesh);
  87382. }
  87383. _this._setLaserPointerParent(webVRController.mesh);
  87384. return _this;
  87385. }
  87386. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  87387. return this.webVRController.getForwardRay(length);
  87388. };
  87389. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  87390. _super.prototype._activatePointer.call(this);
  87391. this._laserPointer.isVisible = true;
  87392. };
  87393. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  87394. _super.prototype._deactivatePointer.call(this);
  87395. this._laserPointer.isVisible = false;
  87396. };
  87397. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  87398. this._laserPointer.material.emissiveColor = color;
  87399. };
  87400. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  87401. var makeNotPick = function (root) {
  87402. root.name += " laserPointer";
  87403. root.getChildMeshes().forEach(function (c) {
  87404. makeNotPick(c);
  87405. });
  87406. };
  87407. makeNotPick(mesh);
  87408. var childMeshes = mesh.getChildMeshes();
  87409. this.webVRController._pointingPoseNode = null;
  87410. for (var i = 0; i < childMeshes.length; i++) {
  87411. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  87412. mesh = childMeshes[i];
  87413. this.webVRController._pointingPoseNode = mesh;
  87414. break;
  87415. }
  87416. }
  87417. this._laserPointer.parent = mesh;
  87418. };
  87419. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  87420. this._laserPointer.scaling.y = distance;
  87421. this._laserPointer.position.z = -distance / 2;
  87422. };
  87423. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  87424. _super.prototype.dispose.call(this);
  87425. this._laserPointer.dispose();
  87426. };
  87427. return VRExperienceHelperControllerGazer;
  87428. }(VRExperienceHelperGazer));
  87429. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  87430. __extends(VRExperienceHelperCameraGazer, _super);
  87431. function VRExperienceHelperCameraGazer(getCamera, scene) {
  87432. var _this = _super.call(this, scene) || this;
  87433. _this.getCamera = getCamera;
  87434. return _this;
  87435. }
  87436. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  87437. var camera = this.getCamera();
  87438. if (camera) {
  87439. return camera.getForwardRay(length);
  87440. }
  87441. else {
  87442. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  87443. }
  87444. };
  87445. return VRExperienceHelperCameraGazer;
  87446. }(VRExperienceHelperGazer));
  87447. /**
  87448. * Helps to quickly add VR support to an existing scene.
  87449. * See http://doc.babylonjs.com/how_to/webvr_helper
  87450. */
  87451. var VRExperienceHelper = /** @class */ (function () {
  87452. /**
  87453. * Instantiates a VRExperienceHelper.
  87454. * Helps to quickly add VR support to an existing scene.
  87455. * @param scene The scene the VRExperienceHelper belongs to.
  87456. * @param webVROptions Options to modify the vr experience helper's behavior.
  87457. */
  87458. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  87459. if (webVROptions === void 0) { webVROptions = {}; }
  87460. var _this = this;
  87461. this.webVROptions = webVROptions;
  87462. // Can the system support WebVR, even if a headset isn't plugged in?
  87463. this._webVRsupported = false;
  87464. // If WebVR is supported, is a headset plugged in and are we ready to present?
  87465. this._webVRready = false;
  87466. // Are we waiting for the requestPresent callback to complete?
  87467. this._webVRrequesting = false;
  87468. // Are we presenting to the headset right now?
  87469. this._webVRpresenting = false;
  87470. // Are we presenting in the fullscreen fallback?
  87471. this._fullscreenVRpresenting = false;
  87472. /**
  87473. * Observable raised when entering VR.
  87474. */
  87475. this.onEnteringVRObservable = new BABYLON.Observable();
  87476. /**
  87477. * Observable raised when exiting VR.
  87478. */
  87479. this.onExitingVRObservable = new BABYLON.Observable();
  87480. /**
  87481. * Observable raised when controller mesh is loaded.
  87482. */
  87483. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  87484. this._useCustomVRButton = false;
  87485. this._teleportationRequested = false;
  87486. this._teleportActive = false;
  87487. this._floorMeshesCollection = [];
  87488. this._rotationAllowed = true;
  87489. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  87490. this._rotationRightAsked = false;
  87491. this._rotationLeftAsked = false;
  87492. this._isDefaultTeleportationTarget = true;
  87493. this._teleportationFillColor = "#444444";
  87494. this._teleportationBorderColor = "#FFFFFF";
  87495. this._rotationAngle = 0;
  87496. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  87497. this._padSensibilityUp = 0.65;
  87498. this._padSensibilityDown = 0.35;
  87499. this.leftController = null;
  87500. this.rightController = null;
  87501. /**
  87502. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  87503. */
  87504. this.onNewMeshSelected = new BABYLON.Observable();
  87505. /**
  87506. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  87507. */
  87508. this.onNewMeshPicked = new BABYLON.Observable();
  87509. /**
  87510. * Observable raised before camera teleportation
  87511. */
  87512. this.onBeforeCameraTeleport = new BABYLON.Observable();
  87513. /**
  87514. * Observable raised after camera teleportation
  87515. */
  87516. this.onAfterCameraTeleport = new BABYLON.Observable();
  87517. /**
  87518. * Observable raised when current selected mesh gets unselected
  87519. */
  87520. this.onSelectedMeshUnselected = new BABYLON.Observable();
  87521. /**
  87522. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  87523. */
  87524. this.teleportationEnabled = true;
  87525. this._teleportationInitialized = false;
  87526. this._interactionsEnabled = false;
  87527. this._interactionsRequested = false;
  87528. this._displayGaze = true;
  87529. this._displayLaserPointer = true;
  87530. this._onResize = function () {
  87531. _this.moveButtonToBottomRight();
  87532. if (_this._fullscreenVRpresenting && _this._webVRready) {
  87533. _this.exitVR();
  87534. }
  87535. };
  87536. this._onFullscreenChange = function () {
  87537. if (document.fullscreen !== undefined) {
  87538. _this._fullscreenVRpresenting = document.fullscreen;
  87539. }
  87540. else if (document.mozFullScreen !== undefined) {
  87541. _this._fullscreenVRpresenting = document.mozFullScreen;
  87542. }
  87543. else if (document.webkitIsFullScreen !== undefined) {
  87544. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  87545. }
  87546. else if (document.msIsFullScreen !== undefined) {
  87547. _this._fullscreenVRpresenting = document.msIsFullScreen;
  87548. }
  87549. if (!_this._fullscreenVRpresenting && _this._canvas) {
  87550. _this.exitVR();
  87551. if (!_this._useCustomVRButton) {
  87552. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  87553. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  87554. }
  87555. }
  87556. };
  87557. this.beforeRender = function () {
  87558. if (_this.leftController && _this.leftController._activePointer) {
  87559. _this._castRayAndSelectObject(_this.leftController);
  87560. }
  87561. if (_this.rightController && _this.rightController._activePointer) {
  87562. _this._castRayAndSelectObject(_this.rightController);
  87563. }
  87564. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  87565. _this._castRayAndSelectObject(_this._cameraGazer);
  87566. }
  87567. else {
  87568. _this._cameraGazer._gazeTracker.isVisible = false;
  87569. }
  87570. };
  87571. this._onNewGamepadConnected = function (gamepad) {
  87572. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  87573. if (gamepad.leftStick) {
  87574. gamepad.onleftstickchanged(function (stickValues) {
  87575. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  87576. // Listening to classic/xbox gamepad only if no VR controller is active
  87577. if ((!_this.leftController && !_this.rightController) ||
  87578. ((_this.leftController && !_this.leftController._activePointer) &&
  87579. (_this.rightController && !_this.rightController._activePointer))) {
  87580. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  87581. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  87582. }
  87583. }
  87584. });
  87585. }
  87586. if (gamepad.rightStick) {
  87587. gamepad.onrightstickchanged(function (stickValues) {
  87588. if (_this._teleportationInitialized) {
  87589. _this._checkRotate(stickValues, _this._cameraGazer);
  87590. }
  87591. });
  87592. }
  87593. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  87594. gamepad.onbuttondown(function (buttonPressed) {
  87595. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87596. _this._cameraGazer._selectionPointerDown();
  87597. }
  87598. });
  87599. gamepad.onbuttonup(function (buttonPressed) {
  87600. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87601. _this._cameraGazer._selectionPointerUp();
  87602. }
  87603. });
  87604. }
  87605. }
  87606. else {
  87607. var webVRController = gamepad;
  87608. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  87609. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  87610. _this.rightController = controller;
  87611. }
  87612. else {
  87613. _this.leftController = controller;
  87614. }
  87615. _this._tryEnableInteractionOnController(controller);
  87616. }
  87617. };
  87618. // 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
  87619. this._tryEnableInteractionOnController = function (controller) {
  87620. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  87621. _this._enableInteractionOnController(controller);
  87622. }
  87623. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  87624. _this._enableTeleportationOnController(controller);
  87625. }
  87626. };
  87627. this._onNewGamepadDisconnected = function (gamepad) {
  87628. if (gamepad instanceof BABYLON.WebVRController) {
  87629. if (gamepad.hand === "left" && _this.leftController != null) {
  87630. _this.leftController.dispose();
  87631. _this.leftController = null;
  87632. }
  87633. if (gamepad.hand === "right" && _this.rightController != null) {
  87634. _this.rightController.dispose();
  87635. _this.rightController = null;
  87636. }
  87637. }
  87638. };
  87639. this._workingVector = BABYLON.Vector3.Zero();
  87640. this._workingQuaternion = BABYLON.Quaternion.Identity();
  87641. this._workingMatrix = BABYLON.Matrix.Identity();
  87642. this._scene = scene;
  87643. this._canvas = scene.getEngine().getRenderingCanvas();
  87644. // Parse options
  87645. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  87646. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  87647. }
  87648. if (webVROptions.createDeviceOrientationCamera === undefined) {
  87649. webVROptions.createDeviceOrientationCamera = true;
  87650. }
  87651. if (webVROptions.defaultHeight === undefined) {
  87652. webVROptions.defaultHeight = 1.7;
  87653. }
  87654. if (webVROptions.useCustomVRButton) {
  87655. this._useCustomVRButton = true;
  87656. if (webVROptions.customVRButton) {
  87657. this._btnVR = webVROptions.customVRButton;
  87658. }
  87659. }
  87660. if (webVROptions.rayLength) {
  87661. this._rayLength = webVROptions.rayLength;
  87662. }
  87663. this._defaultHeight = webVROptions.defaultHeight;
  87664. if (webVROptions.positionScale) {
  87665. this._rayLength *= webVROptions.positionScale;
  87666. this._defaultHeight *= webVROptions.positionScale;
  87667. }
  87668. // Set position
  87669. if (this._scene.activeCamera) {
  87670. this._position = this._scene.activeCamera.position.clone();
  87671. }
  87672. else {
  87673. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  87674. }
  87675. // Set non-vr camera
  87676. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  87677. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  87678. // Copy data from existing camera
  87679. if (this._scene.activeCamera) {
  87680. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  87681. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  87682. // Set rotation from previous camera
  87683. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  87684. var targetCamera = this._scene.activeCamera;
  87685. if (targetCamera.rotationQuaternion) {
  87686. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  87687. }
  87688. else {
  87689. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  87690. }
  87691. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  87692. }
  87693. }
  87694. this._scene.activeCamera = this._deviceOrientationCamera;
  87695. if (this._canvas) {
  87696. this._scene.activeCamera.attachControl(this._canvas);
  87697. }
  87698. }
  87699. else {
  87700. this._existingCamera = this._scene.activeCamera;
  87701. }
  87702. // Create VR cameras
  87703. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87704. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  87705. }
  87706. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  87707. this._webVRCamera.useStandingMatrix();
  87708. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  87709. // Create default button
  87710. if (!this._useCustomVRButton) {
  87711. this._btnVR = document.createElement("BUTTON");
  87712. this._btnVR.className = "babylonVRicon";
  87713. this._btnVR.id = "babylonVRiconbtn";
  87714. this._btnVR.title = "Click to switch to VR";
  87715. 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) }";
  87716. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  87717. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  87718. // css += ".babylonVRicon.vrdisplaysupported { }";
  87719. // css += ".babylonVRicon.vrdisplayready { }";
  87720. // css += ".babylonVRicon.vrdisplayrequesting { }";
  87721. var style = document.createElement('style');
  87722. style.appendChild(document.createTextNode(css));
  87723. document.getElementsByTagName('head')[0].appendChild(style);
  87724. this.moveButtonToBottomRight();
  87725. }
  87726. // VR button click event
  87727. if (this._btnVR) {
  87728. this._btnVR.addEventListener("click", function () {
  87729. if (!_this.isInVRMode) {
  87730. _this.enterVR();
  87731. }
  87732. else {
  87733. _this.exitVR();
  87734. }
  87735. });
  87736. }
  87737. // Window events
  87738. window.addEventListener("resize", this._onResize);
  87739. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  87740. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  87741. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  87742. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  87743. // Display vr button when headset is connected
  87744. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87745. this.displayVRButton();
  87746. }
  87747. else {
  87748. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  87749. if (e.vrDisplay) {
  87750. _this.displayVRButton();
  87751. }
  87752. });
  87753. }
  87754. // Exiting VR mode using 'ESC' key on desktop
  87755. this._onKeyDown = function (event) {
  87756. if (event.keyCode === 27 && _this.isInVRMode) {
  87757. _this.exitVR();
  87758. }
  87759. };
  87760. document.addEventListener("keydown", this._onKeyDown);
  87761. // Exiting VR mode double tapping the touch screen
  87762. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  87763. if (_this.isInVRMode) {
  87764. _this.exitVR();
  87765. if (_this._fullscreenVRpresenting) {
  87766. _this._scene.getEngine().switchFullscreen(true);
  87767. }
  87768. }
  87769. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  87770. // Listen for WebVR display changes
  87771. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  87772. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  87773. this._onVRRequestPresentStart = function () {
  87774. _this._webVRrequesting = true;
  87775. _this.updateButtonVisibility();
  87776. };
  87777. this._onVRRequestPresentComplete = function (success) {
  87778. _this._webVRrequesting = false;
  87779. _this.updateButtonVisibility();
  87780. };
  87781. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  87782. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  87783. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  87784. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  87785. scene.onDisposeObservable.add(function () {
  87786. _this.dispose();
  87787. });
  87788. // Gamepad connection events
  87789. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  87790. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  87791. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  87792. this.updateButtonVisibility();
  87793. //create easing functions
  87794. this._circleEase = new BABYLON.CircleEase();
  87795. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  87796. }
  87797. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  87798. /** Return this.onEnteringVRObservable
  87799. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  87800. */
  87801. get: function () {
  87802. return this.onEnteringVRObservable;
  87803. },
  87804. enumerable: true,
  87805. configurable: true
  87806. });
  87807. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  87808. /** Return this.onExitingVRObservable
  87809. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  87810. */
  87811. get: function () {
  87812. return this.onExitingVRObservable;
  87813. },
  87814. enumerable: true,
  87815. configurable: true
  87816. });
  87817. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  87818. /** Return this.onControllerMeshLoadedObservable
  87819. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  87820. */
  87821. get: function () {
  87822. return this.onControllerMeshLoadedObservable;
  87823. },
  87824. enumerable: true,
  87825. configurable: true
  87826. });
  87827. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  87828. /**
  87829. * The mesh used to display where the user is going to teleport.
  87830. */
  87831. get: function () {
  87832. return this._teleportationTarget;
  87833. },
  87834. /**
  87835. * Sets the mesh to be used to display where the user is going to teleport.
  87836. */
  87837. set: function (value) {
  87838. if (value) {
  87839. value.name = "teleportationTarget";
  87840. this._isDefaultTeleportationTarget = false;
  87841. this._teleportationTarget = value;
  87842. }
  87843. },
  87844. enumerable: true,
  87845. configurable: true
  87846. });
  87847. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  87848. /**
  87849. * The mesh used to display where the user is selecting,
  87850. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  87851. * See http://doc.babylonjs.com/resources/baking_transformations
  87852. */
  87853. get: function () {
  87854. return this._cameraGazer._gazeTracker;
  87855. },
  87856. set: function (value) {
  87857. if (value) {
  87858. this._cameraGazer._gazeTracker = value;
  87859. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  87860. this._cameraGazer._gazeTracker.isPickable = false;
  87861. this._cameraGazer._gazeTracker.isVisible = false;
  87862. this._cameraGazer._gazeTracker.name = "gazeTracker";
  87863. if (this.leftController) {
  87864. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  87865. }
  87866. if (this.rightController) {
  87867. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  87868. }
  87869. }
  87870. },
  87871. enumerable: true,
  87872. configurable: true
  87873. });
  87874. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  87875. /**
  87876. * If the ray of the gaze should be displayed.
  87877. */
  87878. get: function () {
  87879. return this._displayGaze;
  87880. },
  87881. /**
  87882. * Sets if the ray of the gaze should be displayed.
  87883. */
  87884. set: function (value) {
  87885. this._displayGaze = value;
  87886. if (!value) {
  87887. this._cameraGazer._gazeTracker.isVisible = false;
  87888. if (this.leftController) {
  87889. this.leftController._gazeTracker.isVisible = false;
  87890. }
  87891. if (this.rightController) {
  87892. this.rightController._gazeTracker.isVisible = false;
  87893. }
  87894. }
  87895. },
  87896. enumerable: true,
  87897. configurable: true
  87898. });
  87899. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  87900. /**
  87901. * If the ray of the LaserPointer should be displayed.
  87902. */
  87903. get: function () {
  87904. return this._displayLaserPointer;
  87905. },
  87906. /**
  87907. * Sets if the ray of the LaserPointer should be displayed.
  87908. */
  87909. set: function (value) {
  87910. this._displayLaserPointer = value;
  87911. if (!value) {
  87912. if (this.rightController) {
  87913. this.rightController._deactivatePointer();
  87914. this.rightController._gazeTracker.isVisible = false;
  87915. }
  87916. if (this.leftController) {
  87917. this.leftController._deactivatePointer();
  87918. this.leftController._gazeTracker.isVisible = false;
  87919. }
  87920. }
  87921. else {
  87922. if (this.rightController) {
  87923. this.rightController._activatePointer();
  87924. }
  87925. else if (this.leftController) {
  87926. this.leftController._activatePointer();
  87927. }
  87928. }
  87929. },
  87930. enumerable: true,
  87931. configurable: true
  87932. });
  87933. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  87934. /**
  87935. * The deviceOrientationCamera used as the camera when not in VR.
  87936. */
  87937. get: function () {
  87938. return this._deviceOrientationCamera;
  87939. },
  87940. enumerable: true,
  87941. configurable: true
  87942. });
  87943. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  87944. /**
  87945. * Based on the current WebVR support, returns the current VR camera used.
  87946. */
  87947. get: function () {
  87948. if (this._webVRready) {
  87949. return this._webVRCamera;
  87950. }
  87951. else {
  87952. return this._scene.activeCamera;
  87953. }
  87954. },
  87955. enumerable: true,
  87956. configurable: true
  87957. });
  87958. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  87959. /**
  87960. * The webVRCamera which is used when in VR.
  87961. */
  87962. get: function () {
  87963. return this._webVRCamera;
  87964. },
  87965. enumerable: true,
  87966. configurable: true
  87967. });
  87968. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  87969. /**
  87970. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  87971. */
  87972. get: function () {
  87973. return this._vrDeviceOrientationCamera;
  87974. },
  87975. enumerable: true,
  87976. configurable: true
  87977. });
  87978. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  87979. get: function () {
  87980. var result = this._cameraGazer._teleportationRequestInitiated
  87981. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  87982. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  87983. return result;
  87984. },
  87985. enumerable: true,
  87986. configurable: true
  87987. });
  87988. // Raised when one of the controller has loaded successfully its associated default mesh
  87989. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  87990. if (this.leftController && this.leftController.webVRController == webVRController) {
  87991. if (webVRController.mesh) {
  87992. this.leftController._setLaserPointerParent(webVRController.mesh);
  87993. }
  87994. }
  87995. if (this.rightController && this.rightController.webVRController == webVRController) {
  87996. if (webVRController.mesh) {
  87997. this.rightController._setLaserPointerParent(webVRController.mesh);
  87998. }
  87999. }
  88000. try {
  88001. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  88002. }
  88003. catch (err) {
  88004. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  88005. }
  88006. };
  88007. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  88008. /**
  88009. * Gets a value indicating if we are currently in VR mode.
  88010. */
  88011. get: function () {
  88012. return this._webVRpresenting || this._fullscreenVRpresenting;
  88013. },
  88014. enumerable: true,
  88015. configurable: true
  88016. });
  88017. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  88018. var vrDisplay = this._scene.getEngine().getVRDevice();
  88019. if (vrDisplay) {
  88020. var wasPresenting = this._webVRpresenting;
  88021. // A VR display is connected
  88022. this._webVRpresenting = vrDisplay.isPresenting;
  88023. if (wasPresenting && !this._webVRpresenting)
  88024. this.exitVR();
  88025. }
  88026. else {
  88027. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  88028. }
  88029. this.updateButtonVisibility();
  88030. };
  88031. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  88032. this._webVRsupported = eventArgs.vrSupported;
  88033. this._webVRready = !!eventArgs.vrDisplay;
  88034. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  88035. this.updateButtonVisibility();
  88036. };
  88037. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  88038. if (this._canvas && !this._useCustomVRButton) {
  88039. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  88040. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  88041. }
  88042. };
  88043. VRExperienceHelper.prototype.displayVRButton = function () {
  88044. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  88045. document.body.appendChild(this._btnVR);
  88046. this._btnVRDisplayed = true;
  88047. }
  88048. };
  88049. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  88050. if (!this._btnVR || this._useCustomVRButton) {
  88051. return;
  88052. }
  88053. this._btnVR.className = "babylonVRicon";
  88054. if (this.isInVRMode) {
  88055. this._btnVR.className += " vrdisplaypresenting";
  88056. }
  88057. else {
  88058. if (this._webVRready)
  88059. this._btnVR.className += " vrdisplayready";
  88060. if (this._webVRsupported)
  88061. this._btnVR.className += " vrdisplaysupported";
  88062. if (this._webVRrequesting)
  88063. this._btnVR.className += " vrdisplayrequesting";
  88064. }
  88065. };
  88066. /**
  88067. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  88068. * Otherwise, will use the fullscreen API.
  88069. */
  88070. VRExperienceHelper.prototype.enterVR = function () {
  88071. if (this.onEnteringVRObservable) {
  88072. try {
  88073. this.onEnteringVRObservable.notifyObservers(this);
  88074. }
  88075. catch (err) {
  88076. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  88077. }
  88078. }
  88079. if (this._scene.activeCamera) {
  88080. this._position = this._scene.activeCamera.position.clone();
  88081. // make sure that we return to the last active camera
  88082. this._existingCamera = this._scene.activeCamera;
  88083. }
  88084. if (this._webVRrequesting)
  88085. return;
  88086. // If WebVR is supported and a headset is connected
  88087. if (this._webVRready) {
  88088. if (!this._webVRpresenting) {
  88089. this._webVRCamera.position = this._position;
  88090. this._scene.activeCamera = this._webVRCamera;
  88091. }
  88092. }
  88093. else if (this._vrDeviceOrientationCamera) {
  88094. this._vrDeviceOrientationCamera.position = this._position;
  88095. if (this._scene.activeCamera) {
  88096. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  88097. }
  88098. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  88099. this._scene.getEngine().switchFullscreen(true);
  88100. this.updateButtonVisibility();
  88101. }
  88102. if (this._scene.activeCamera && this._canvas) {
  88103. this._scene.activeCamera.attachControl(this._canvas);
  88104. }
  88105. if (this._interactionsEnabled) {
  88106. this._scene.registerBeforeRender(this.beforeRender);
  88107. }
  88108. };
  88109. /**
  88110. * Attempt to exit VR, or fullscreen.
  88111. */
  88112. VRExperienceHelper.prototype.exitVR = function () {
  88113. if (this.onExitingVRObservable) {
  88114. try {
  88115. this.onExitingVRObservable.notifyObservers(this);
  88116. }
  88117. catch (err) {
  88118. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  88119. }
  88120. }
  88121. if (this._webVRpresenting) {
  88122. this._scene.getEngine().disableVR();
  88123. }
  88124. if (this._scene.activeCamera) {
  88125. this._position = this._scene.activeCamera.position.clone();
  88126. }
  88127. if (this._deviceOrientationCamera) {
  88128. this._deviceOrientationCamera.position = this._position;
  88129. this._scene.activeCamera = this._deviceOrientationCamera;
  88130. if (this._canvas) {
  88131. this._scene.activeCamera.attachControl(this._canvas);
  88132. }
  88133. }
  88134. else if (this._existingCamera) {
  88135. this._existingCamera.position = this._position;
  88136. this._scene.activeCamera = this._existingCamera;
  88137. }
  88138. this.updateButtonVisibility();
  88139. if (this._interactionsEnabled) {
  88140. this._scene.unregisterBeforeRender(this.beforeRender);
  88141. }
  88142. // resize to update width and height when exiting vr exits fullscreen
  88143. this._scene.getEngine().resize();
  88144. };
  88145. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  88146. /**
  88147. * The position of the vr experience helper.
  88148. */
  88149. get: function () {
  88150. return this._position;
  88151. },
  88152. /**
  88153. * Sets the position of the vr experience helper.
  88154. */
  88155. set: function (value) {
  88156. this._position = value;
  88157. if (this._scene.activeCamera) {
  88158. this._scene.activeCamera.position = value;
  88159. }
  88160. },
  88161. enumerable: true,
  88162. configurable: true
  88163. });
  88164. /**
  88165. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  88166. */
  88167. VRExperienceHelper.prototype.enableInteractions = function () {
  88168. var _this = this;
  88169. if (!this._interactionsEnabled) {
  88170. this._interactionsRequested = true;
  88171. if (this.leftController) {
  88172. this._enableInteractionOnController(this.leftController);
  88173. }
  88174. if (this.rightController) {
  88175. this._enableInteractionOnController(this.rightController);
  88176. }
  88177. this.raySelectionPredicate = function (mesh) {
  88178. return mesh.isVisible;
  88179. };
  88180. this.meshSelectionPredicate = function (mesh) {
  88181. return true;
  88182. };
  88183. this._raySelectionPredicate = function (mesh) {
  88184. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  88185. && mesh.name.indexOf("teleportationTarget") === -1
  88186. && mesh.name.indexOf("torusTeleportation") === -1
  88187. && mesh.name.indexOf("laserPointer") === -1)) {
  88188. return _this.raySelectionPredicate(mesh);
  88189. }
  88190. return false;
  88191. };
  88192. this._interactionsEnabled = true;
  88193. }
  88194. };
  88195. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  88196. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  88197. if (this._floorMeshesCollection[i].id === mesh.id) {
  88198. return true;
  88199. }
  88200. }
  88201. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  88202. return true;
  88203. }
  88204. return false;
  88205. };
  88206. /**
  88207. * Adds a floor mesh to be used for teleportation.
  88208. * @param floorMesh the mesh to be used for teleportation.
  88209. */
  88210. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  88211. if (!this._floorMeshesCollection) {
  88212. return;
  88213. }
  88214. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  88215. return;
  88216. }
  88217. this._floorMeshesCollection.push(floorMesh);
  88218. };
  88219. /**
  88220. * Removes a floor mesh from being used for teleportation.
  88221. * @param floorMesh the mesh to be removed.
  88222. */
  88223. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  88224. if (!this._floorMeshesCollection) {
  88225. return;
  88226. }
  88227. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  88228. if (meshIndex !== -1) {
  88229. this._floorMeshesCollection.splice(meshIndex, 1);
  88230. }
  88231. };
  88232. /**
  88233. * Enables interactions and teleportation using the VR controllers and gaze.
  88234. * @param vrTeleportationOptions options to modify teleportation behavior.
  88235. */
  88236. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  88237. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  88238. if (!this._teleportationInitialized) {
  88239. this._teleportationRequested = true;
  88240. this.enableInteractions();
  88241. if (vrTeleportationOptions.floorMeshName) {
  88242. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  88243. }
  88244. if (vrTeleportationOptions.floorMeshes) {
  88245. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  88246. }
  88247. if (this.leftController != null) {
  88248. this._enableTeleportationOnController(this.leftController);
  88249. }
  88250. if (this.rightController != null) {
  88251. this._enableTeleportationOnController(this.rightController);
  88252. }
  88253. // Creates an image processing post process for the vignette not relying
  88254. // on the main scene configuration for image processing to reduce setup and spaces
  88255. // (gamma/linear) conflicts.
  88256. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  88257. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  88258. imageProcessingConfiguration.vignetteEnabled = true;
  88259. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  88260. this._webVRCamera.detachPostProcess(this._postProcessMove);
  88261. this._teleportationInitialized = true;
  88262. if (this._isDefaultTeleportationTarget) {
  88263. this._createTeleportationCircles();
  88264. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  88265. }
  88266. }
  88267. };
  88268. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  88269. var _this = this;
  88270. var controllerMesh = controller.webVRController.mesh;
  88271. if (controllerMesh) {
  88272. controller._interactionsEnabled = true;
  88273. controller._activatePointer();
  88274. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  88275. // Enabling / disabling laserPointer
  88276. if (_this._displayLaserPointer && stateObject.value === 1) {
  88277. if (controller._activePointer) {
  88278. controller._deactivatePointer();
  88279. }
  88280. else {
  88281. controller._activatePointer();
  88282. }
  88283. if (_this.displayGaze) {
  88284. controller._gazeTracker.isVisible = controller._activePointer;
  88285. }
  88286. }
  88287. });
  88288. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  88289. if (!controller._pointerDownOnMeshAsked) {
  88290. if (stateObject.value > _this._padSensibilityUp) {
  88291. controller._selectionPointerDown();
  88292. }
  88293. }
  88294. else if (stateObject.value < _this._padSensibilityDown) {
  88295. controller._selectionPointerUp();
  88296. }
  88297. });
  88298. }
  88299. };
  88300. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  88301. // Dont teleport if another gaze already requested teleportation
  88302. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  88303. return;
  88304. }
  88305. if (!gazer._teleportationRequestInitiated) {
  88306. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  88307. gazer._activatePointer();
  88308. gazer._teleportationRequestInitiated = true;
  88309. }
  88310. }
  88311. else {
  88312. // Listening to the proper controller values changes to confirm teleportation
  88313. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  88314. if (this._teleportActive) {
  88315. this._teleportCamera(this._haloCenter);
  88316. }
  88317. gazer._teleportationRequestInitiated = false;
  88318. }
  88319. }
  88320. };
  88321. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  88322. // Only rotate when user is not currently selecting a teleportation location
  88323. if (gazer._teleportationRequestInitiated) {
  88324. return;
  88325. }
  88326. if (!this._rotationLeftAsked) {
  88327. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  88328. this._rotationLeftAsked = true;
  88329. if (this._rotationAllowed) {
  88330. this._rotateCamera(false);
  88331. }
  88332. }
  88333. }
  88334. else {
  88335. if (stateObject.x > -this._padSensibilityDown) {
  88336. this._rotationLeftAsked = false;
  88337. }
  88338. }
  88339. if (!this._rotationRightAsked) {
  88340. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  88341. this._rotationRightAsked = true;
  88342. if (this._rotationAllowed) {
  88343. this._rotateCamera(true);
  88344. }
  88345. }
  88346. }
  88347. else {
  88348. if (stateObject.x < this._padSensibilityDown) {
  88349. this._rotationRightAsked = false;
  88350. }
  88351. }
  88352. };
  88353. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  88354. // Only teleport backwards when user is not currently selecting a teleportation location
  88355. if (gazer._teleportationRequestInitiated) {
  88356. return;
  88357. }
  88358. // Teleport backwards
  88359. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  88360. if (!gazer._teleportationBackRequestInitiated) {
  88361. if (!this.currentVRCamera) {
  88362. return;
  88363. }
  88364. // Get rotation and position of the current camera
  88365. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  88366. var position = this.currentVRCamera.position;
  88367. // If the camera has device position, use that instead
  88368. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  88369. rotation = this.currentVRCamera.deviceRotationQuaternion;
  88370. position = this.currentVRCamera.devicePosition;
  88371. }
  88372. // Get matrix with only the y rotation of the device rotation
  88373. rotation.toEulerAnglesToRef(this._workingVector);
  88374. this._workingVector.z = 0;
  88375. this._workingVector.x = 0;
  88376. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  88377. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  88378. // Rotate backwards ray by device rotation to cast at the ground behind the user
  88379. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  88380. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  88381. var ray = new BABYLON.Ray(position, this._workingVector);
  88382. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  88383. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  88384. this._teleportCamera(hit.pickedPoint);
  88385. }
  88386. gazer._teleportationBackRequestInitiated = true;
  88387. }
  88388. }
  88389. else {
  88390. gazer._teleportationBackRequestInitiated = false;
  88391. }
  88392. };
  88393. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  88394. var _this = this;
  88395. var controllerMesh = controller.webVRController.mesh;
  88396. if (controllerMesh) {
  88397. if (!controller._interactionsEnabled) {
  88398. this._enableInteractionOnController(controller);
  88399. }
  88400. controller._interactionsEnabled = true;
  88401. controller._teleportationEnabled = true;
  88402. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  88403. controller._dpadPressed = false;
  88404. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  88405. controller._dpadPressed = stateObject.pressed;
  88406. if (!controller._dpadPressed) {
  88407. _this._rotationLeftAsked = false;
  88408. _this._rotationRightAsked = false;
  88409. controller._teleportationBackRequestInitiated = false;
  88410. }
  88411. });
  88412. }
  88413. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  88414. if (_this.teleportationEnabled) {
  88415. _this._checkTeleportBackwards(stateObject, controller);
  88416. _this._checkTeleportWithRay(stateObject, controller);
  88417. }
  88418. _this._checkRotate(stateObject, controller);
  88419. });
  88420. }
  88421. };
  88422. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  88423. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  88424. this._teleportationTarget.isPickable = false;
  88425. var length = 512;
  88426. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  88427. dynamicTexture.hasAlpha = true;
  88428. var context = dynamicTexture.getContext();
  88429. var centerX = length / 2;
  88430. var centerY = length / 2;
  88431. var radius = 200;
  88432. context.beginPath();
  88433. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  88434. context.fillStyle = this._teleportationFillColor;
  88435. context.fill();
  88436. context.lineWidth = 10;
  88437. context.strokeStyle = this._teleportationBorderColor;
  88438. context.stroke();
  88439. context.closePath();
  88440. dynamicTexture.update();
  88441. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  88442. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  88443. this._teleportationTarget.material = teleportationCircleMaterial;
  88444. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  88445. torus.isPickable = false;
  88446. torus.parent = this._teleportationTarget;
  88447. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  88448. var keys = [];
  88449. keys.push({
  88450. frame: 0,
  88451. value: 0
  88452. });
  88453. keys.push({
  88454. frame: 30,
  88455. value: 0.4
  88456. });
  88457. keys.push({
  88458. frame: 60,
  88459. value: 0
  88460. });
  88461. animationInnerCircle.setKeys(keys);
  88462. var easingFunction = new BABYLON.SineEase();
  88463. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  88464. animationInnerCircle.setEasingFunction(easingFunction);
  88465. torus.animations = [];
  88466. torus.animations.push(animationInnerCircle);
  88467. this._scene.beginAnimation(torus, 0, 60, true);
  88468. this._hideTeleportationTarget();
  88469. };
  88470. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  88471. this._teleportActive = true;
  88472. if (this._teleportationInitialized) {
  88473. this._teleportationTarget.isVisible = true;
  88474. if (this._isDefaultTeleportationTarget) {
  88475. this._teleportationTarget.getChildren()[0].isVisible = true;
  88476. }
  88477. }
  88478. };
  88479. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  88480. this._teleportActive = false;
  88481. if (this._teleportationInitialized) {
  88482. this._teleportationTarget.isVisible = false;
  88483. if (this._isDefaultTeleportationTarget) {
  88484. this._teleportationTarget.getChildren()[0].isVisible = false;
  88485. }
  88486. }
  88487. };
  88488. VRExperienceHelper.prototype._rotateCamera = function (right) {
  88489. var _this = this;
  88490. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88491. return;
  88492. }
  88493. if (right) {
  88494. this._rotationAngle++;
  88495. }
  88496. else {
  88497. this._rotationAngle--;
  88498. }
  88499. this.currentVRCamera.animations = [];
  88500. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  88501. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88502. var animationRotationKeys = [];
  88503. animationRotationKeys.push({
  88504. frame: 0,
  88505. value: this.currentVRCamera.rotationQuaternion
  88506. });
  88507. animationRotationKeys.push({
  88508. frame: 6,
  88509. value: target
  88510. });
  88511. animationRotation.setKeys(animationRotationKeys);
  88512. animationRotation.setEasingFunction(this._circleEase);
  88513. this.currentVRCamera.animations.push(animationRotation);
  88514. this._postProcessMove.animations = [];
  88515. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88516. var vignetteWeightKeys = [];
  88517. vignetteWeightKeys.push({
  88518. frame: 0,
  88519. value: 0
  88520. });
  88521. vignetteWeightKeys.push({
  88522. frame: 3,
  88523. value: 4
  88524. });
  88525. vignetteWeightKeys.push({
  88526. frame: 6,
  88527. value: 0
  88528. });
  88529. animationPP.setKeys(vignetteWeightKeys);
  88530. animationPP.setEasingFunction(this._circleEase);
  88531. this._postProcessMove.animations.push(animationPP);
  88532. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88533. var vignetteStretchKeys = [];
  88534. vignetteStretchKeys.push({
  88535. frame: 0,
  88536. value: 0
  88537. });
  88538. vignetteStretchKeys.push({
  88539. frame: 3,
  88540. value: 10
  88541. });
  88542. vignetteStretchKeys.push({
  88543. frame: 6,
  88544. value: 0
  88545. });
  88546. animationPP2.setKeys(vignetteStretchKeys);
  88547. animationPP2.setEasingFunction(this._circleEase);
  88548. this._postProcessMove.animations.push(animationPP2);
  88549. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88550. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88551. this._postProcessMove.samples = 4;
  88552. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88553. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  88554. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88555. });
  88556. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  88557. };
  88558. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  88559. if (hit.pickedPoint) {
  88560. if (gazer._teleportationRequestInitiated) {
  88561. this._displayTeleportationTarget();
  88562. this._haloCenter.copyFrom(hit.pickedPoint);
  88563. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  88564. }
  88565. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  88566. if (pickNormal) {
  88567. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88568. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88569. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  88570. }
  88571. this._teleportationTarget.position.y += 0.1;
  88572. }
  88573. };
  88574. VRExperienceHelper.prototype._teleportCamera = function (location) {
  88575. var _this = this;
  88576. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88577. return;
  88578. }
  88579. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  88580. // offset of the headset from the anchor.
  88581. if (this.webVRCamera.leftCamera) {
  88582. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  88583. this._workingVector.subtractInPlace(this.webVRCamera.position);
  88584. location.subtractToRef(this._workingVector, this._workingVector);
  88585. }
  88586. else {
  88587. this._workingVector.copyFrom(location);
  88588. }
  88589. // Add height to account for user's height offset
  88590. if (this.isInVRMode) {
  88591. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  88592. }
  88593. else {
  88594. this._workingVector.y += this._defaultHeight;
  88595. }
  88596. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  88597. // Create animation from the camera's position to the new location
  88598. this.currentVRCamera.animations = [];
  88599. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88600. var animationCameraTeleportationKeys = [{
  88601. frame: 0,
  88602. value: this.currentVRCamera.position
  88603. },
  88604. {
  88605. frame: 11,
  88606. value: this._workingVector
  88607. }
  88608. ];
  88609. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  88610. animationCameraTeleportation.setEasingFunction(this._circleEase);
  88611. this.currentVRCamera.animations.push(animationCameraTeleportation);
  88612. this._postProcessMove.animations = [];
  88613. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88614. var vignetteWeightKeys = [];
  88615. vignetteWeightKeys.push({
  88616. frame: 0,
  88617. value: 0
  88618. });
  88619. vignetteWeightKeys.push({
  88620. frame: 5,
  88621. value: 8
  88622. });
  88623. vignetteWeightKeys.push({
  88624. frame: 11,
  88625. value: 0
  88626. });
  88627. animationPP.setKeys(vignetteWeightKeys);
  88628. this._postProcessMove.animations.push(animationPP);
  88629. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88630. var vignetteStretchKeys = [];
  88631. vignetteStretchKeys.push({
  88632. frame: 0,
  88633. value: 0
  88634. });
  88635. vignetteStretchKeys.push({
  88636. frame: 5,
  88637. value: 10
  88638. });
  88639. vignetteStretchKeys.push({
  88640. frame: 11,
  88641. value: 0
  88642. });
  88643. animationPP2.setKeys(vignetteStretchKeys);
  88644. this._postProcessMove.animations.push(animationPP2);
  88645. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88646. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88647. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88648. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  88649. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88650. });
  88651. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  88652. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  88653. });
  88654. this._hideTeleportationTarget();
  88655. };
  88656. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  88657. if (normal) {
  88658. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  88659. if (angle < Math.PI / 2) {
  88660. normal.scaleInPlace(-1);
  88661. }
  88662. }
  88663. return normal;
  88664. };
  88665. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  88666. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88667. return;
  88668. }
  88669. var ray = gazer._getForwardRay(this._rayLength);
  88670. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  88671. // Moving the gazeTracker on the mesh face targetted
  88672. if (hit && hit.pickedPoint) {
  88673. if (this._displayGaze) {
  88674. var multiplier = 1;
  88675. gazer._gazeTracker.isVisible = true;
  88676. if (gazer._isActionableMesh) {
  88677. multiplier = 3;
  88678. }
  88679. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  88680. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  88681. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  88682. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  88683. // To avoid z-fighting
  88684. var deltaFighting = 0.002;
  88685. if (pickNormal) {
  88686. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88687. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88688. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  88689. }
  88690. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  88691. if (gazer._gazeTracker.position.x < 0) {
  88692. gazer._gazeTracker.position.x += deltaFighting;
  88693. }
  88694. else {
  88695. gazer._gazeTracker.position.x -= deltaFighting;
  88696. }
  88697. if (gazer._gazeTracker.position.y < 0) {
  88698. gazer._gazeTracker.position.y += deltaFighting;
  88699. }
  88700. else {
  88701. gazer._gazeTracker.position.y -= deltaFighting;
  88702. }
  88703. if (gazer._gazeTracker.position.z < 0) {
  88704. gazer._gazeTracker.position.z += deltaFighting;
  88705. }
  88706. else {
  88707. gazer._gazeTracker.position.z -= deltaFighting;
  88708. }
  88709. }
  88710. // Changing the size of the laser pointer based on the distance from the targetted point
  88711. gazer._updatePointerDistance(hit.distance);
  88712. }
  88713. else {
  88714. gazer._gazeTracker.isVisible = false;
  88715. }
  88716. if (hit && hit.pickedMesh) {
  88717. gazer._currentHit = hit;
  88718. if (gazer._pointerDownOnMeshAsked) {
  88719. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  88720. }
  88721. // The object selected is the floor, we're in a teleportation scenario
  88722. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  88723. // Moving the teleportation area to this targetted point
  88724. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  88725. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  88726. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88727. }
  88728. gazer._currentMeshSelected = null;
  88729. if (gazer._teleportationRequestInitiated) {
  88730. this._moveTeleportationSelectorTo(hit, gazer, ray);
  88731. }
  88732. return;
  88733. }
  88734. // If not, we're in a selection scenario
  88735. //this._teleportationAllowed = false;
  88736. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  88737. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  88738. this.onNewMeshPicked.notifyObservers(hit);
  88739. gazer._currentMeshSelected = hit.pickedMesh;
  88740. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  88741. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  88742. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  88743. gazer._isActionableMesh = true;
  88744. }
  88745. else {
  88746. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88747. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88748. gazer._isActionableMesh = false;
  88749. }
  88750. try {
  88751. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  88752. }
  88753. catch (err) {
  88754. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  88755. }
  88756. }
  88757. else {
  88758. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88759. gazer._currentMeshSelected = null;
  88760. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88761. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88762. }
  88763. }
  88764. }
  88765. else {
  88766. gazer._currentHit = null;
  88767. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88768. gazer._currentMeshSelected = null;
  88769. //this._teleportationAllowed = false;
  88770. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88771. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88772. }
  88773. };
  88774. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  88775. if (mesh) {
  88776. this.onSelectedMeshUnselected.notifyObservers(mesh);
  88777. }
  88778. };
  88779. /**
  88780. * Sets the color of the laser ray from the vr controllers.
  88781. * @param color new color for the ray.
  88782. */
  88783. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  88784. if (this.leftController) {
  88785. this.leftController._setLaserPointerColor(color);
  88786. }
  88787. if (this.rightController) {
  88788. this.rightController._setLaserPointerColor(color);
  88789. }
  88790. };
  88791. /**
  88792. * Sets the color of the ray from the vr headsets gaze.
  88793. * @param color new color for the ray.
  88794. */
  88795. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  88796. if (!this._cameraGazer._gazeTracker.material) {
  88797. return;
  88798. }
  88799. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  88800. if (this.leftController) {
  88801. this.leftController._gazeTracker.material.emissiveColor = color;
  88802. }
  88803. if (this.rightController) {
  88804. this.rightController._gazeTracker.material.emissiveColor = color;
  88805. }
  88806. };
  88807. /**
  88808. * Exits VR and disposes of the vr experience helper
  88809. */
  88810. VRExperienceHelper.prototype.dispose = function () {
  88811. if (this.isInVRMode) {
  88812. this.exitVR();
  88813. }
  88814. if (this._postProcessMove) {
  88815. this._postProcessMove.dispose();
  88816. }
  88817. if (this._webVRCamera) {
  88818. this._webVRCamera.dispose();
  88819. }
  88820. if (this._vrDeviceOrientationCamera) {
  88821. this._vrDeviceOrientationCamera.dispose();
  88822. }
  88823. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  88824. document.body.removeChild(this._btnVR);
  88825. }
  88826. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  88827. this._deviceOrientationCamera.dispose();
  88828. }
  88829. if (this._cameraGazer) {
  88830. this._cameraGazer.dispose();
  88831. }
  88832. if (this.leftController) {
  88833. this.leftController.dispose();
  88834. }
  88835. if (this.rightController) {
  88836. this.rightController.dispose();
  88837. }
  88838. if (this._teleportationTarget) {
  88839. this._teleportationTarget.dispose();
  88840. }
  88841. this._floorMeshesCollection = [];
  88842. document.removeEventListener("keydown", this._onKeyDown);
  88843. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88844. window.removeEventListener("resize", this._onResize);
  88845. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  88846. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  88847. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  88848. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  88849. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  88850. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  88851. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  88852. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88853. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  88854. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  88855. this._scene.unregisterBeforeRender(this.beforeRender);
  88856. };
  88857. /**
  88858. * Gets the name of the VRExperienceHelper class
  88859. * @returns "VRExperienceHelper"
  88860. */
  88861. VRExperienceHelper.prototype.getClassName = function () {
  88862. return "VRExperienceHelper";
  88863. };
  88864. return VRExperienceHelper;
  88865. }());
  88866. BABYLON.VRExperienceHelper = VRExperienceHelper;
  88867. })(BABYLON || (BABYLON = {}));
  88868. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  88869. // Mainly based on these 2 articles :
  88870. // 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
  88871. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  88872. var BABYLON;
  88873. (function (BABYLON) {
  88874. /**
  88875. * Defines the potential axis of a Joystick
  88876. */
  88877. var JoystickAxis;
  88878. (function (JoystickAxis) {
  88879. /** X axis */
  88880. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  88881. /** Y axis */
  88882. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  88883. /** Z axis */
  88884. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  88885. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  88886. /**
  88887. * Class used to define virtual joystick (used in touch mode)
  88888. */
  88889. var VirtualJoystick = /** @class */ (function () {
  88890. /**
  88891. * Creates a new virtual joystick
  88892. * @param leftJoystick defines that the joystick is for left hand (false by default)
  88893. */
  88894. function VirtualJoystick(leftJoystick) {
  88895. var _this = this;
  88896. if (leftJoystick) {
  88897. this._leftJoystick = true;
  88898. }
  88899. else {
  88900. this._leftJoystick = false;
  88901. }
  88902. VirtualJoystick._globalJoystickIndex++;
  88903. // By default left & right arrow keys are moving the X
  88904. // and up & down keys are moving the Y
  88905. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  88906. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  88907. this.reverseLeftRight = false;
  88908. this.reverseUpDown = false;
  88909. // collections of pointers
  88910. this._touches = new BABYLON.StringDictionary();
  88911. this.deltaPosition = BABYLON.Vector3.Zero();
  88912. this._joystickSensibility = 25;
  88913. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  88914. this._onResize = function (evt) {
  88915. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  88916. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  88917. if (VirtualJoystick.vjCanvas) {
  88918. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  88919. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  88920. }
  88921. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  88922. };
  88923. // injecting a canvas element on top of the canvas 3D game
  88924. if (!VirtualJoystick.vjCanvas) {
  88925. window.addEventListener("resize", this._onResize, false);
  88926. VirtualJoystick.vjCanvas = document.createElement("canvas");
  88927. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  88928. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  88929. VirtualJoystick.vjCanvas.width = window.innerWidth;
  88930. VirtualJoystick.vjCanvas.height = window.innerHeight;
  88931. VirtualJoystick.vjCanvas.style.width = "100%";
  88932. VirtualJoystick.vjCanvas.style.height = "100%";
  88933. VirtualJoystick.vjCanvas.style.position = "absolute";
  88934. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  88935. VirtualJoystick.vjCanvas.style.top = "0px";
  88936. VirtualJoystick.vjCanvas.style.left = "0px";
  88937. VirtualJoystick.vjCanvas.style.zIndex = "5";
  88938. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  88939. // Support for jQuery PEP polyfill
  88940. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  88941. var context = VirtualJoystick.vjCanvas.getContext('2d');
  88942. if (!context) {
  88943. throw new Error("Unable to create canvas for virtual joystick");
  88944. }
  88945. VirtualJoystick.vjCanvasContext = context;
  88946. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  88947. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  88948. document.body.appendChild(VirtualJoystick.vjCanvas);
  88949. }
  88950. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  88951. this.pressed = false;
  88952. // default joystick color
  88953. this._joystickColor = "cyan";
  88954. this._joystickPointerID = -1;
  88955. // current joystick position
  88956. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  88957. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  88958. // origin joystick position
  88959. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  88960. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  88961. this._onPointerDownHandlerRef = function (evt) {
  88962. _this._onPointerDown(evt);
  88963. };
  88964. this._onPointerMoveHandlerRef = function (evt) {
  88965. _this._onPointerMove(evt);
  88966. };
  88967. this._onPointerUpHandlerRef = function (evt) {
  88968. _this._onPointerUp(evt);
  88969. };
  88970. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  88971. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  88972. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  88973. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  88974. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  88975. evt.preventDefault(); // Disables system menu
  88976. }, false);
  88977. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  88978. }
  88979. /**
  88980. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  88981. * @param newJoystickSensibility defines the new sensibility
  88982. */
  88983. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  88984. this._joystickSensibility = newJoystickSensibility;
  88985. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  88986. };
  88987. VirtualJoystick.prototype._onPointerDown = function (e) {
  88988. var positionOnScreenCondition;
  88989. e.preventDefault();
  88990. if (this._leftJoystick === true) {
  88991. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  88992. }
  88993. else {
  88994. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  88995. }
  88996. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  88997. // First contact will be dedicated to the virtual joystick
  88998. this._joystickPointerID = e.pointerId;
  88999. this._joystickPointerStartPos.x = e.clientX;
  89000. this._joystickPointerStartPos.y = e.clientY;
  89001. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  89002. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  89003. this._deltaJoystickVector.x = 0;
  89004. this._deltaJoystickVector.y = 0;
  89005. this.pressed = true;
  89006. this._touches.add(e.pointerId.toString(), e);
  89007. }
  89008. else {
  89009. // You can only trigger the action buttons with a joystick declared
  89010. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  89011. this._action();
  89012. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  89013. }
  89014. }
  89015. };
  89016. VirtualJoystick.prototype._onPointerMove = function (e) {
  89017. // If the current pointer is the one associated to the joystick (first touch contact)
  89018. if (this._joystickPointerID == e.pointerId) {
  89019. this._joystickPointerPos.x = e.clientX;
  89020. this._joystickPointerPos.y = e.clientY;
  89021. this._deltaJoystickVector = this._joystickPointerPos.clone();
  89022. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  89023. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  89024. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  89025. switch (this._axisTargetedByLeftAndRight) {
  89026. case JoystickAxis.X:
  89027. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  89028. break;
  89029. case JoystickAxis.Y:
  89030. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  89031. break;
  89032. case JoystickAxis.Z:
  89033. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  89034. break;
  89035. }
  89036. var directionUpDown = this.reverseUpDown ? 1 : -1;
  89037. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  89038. switch (this._axisTargetedByUpAndDown) {
  89039. case JoystickAxis.X:
  89040. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  89041. break;
  89042. case JoystickAxis.Y:
  89043. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  89044. break;
  89045. case JoystickAxis.Z:
  89046. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  89047. break;
  89048. }
  89049. }
  89050. else {
  89051. var data = this._touches.get(e.pointerId.toString());
  89052. if (data) {
  89053. data.x = e.clientX;
  89054. data.y = e.clientY;
  89055. }
  89056. }
  89057. };
  89058. VirtualJoystick.prototype._onPointerUp = function (e) {
  89059. if (this._joystickPointerID == e.pointerId) {
  89060. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  89061. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  89062. this._joystickPointerID = -1;
  89063. this.pressed = false;
  89064. }
  89065. else {
  89066. var touch = this._touches.get(e.pointerId.toString());
  89067. if (touch) {
  89068. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89069. }
  89070. }
  89071. this._deltaJoystickVector.x = 0;
  89072. this._deltaJoystickVector.y = 0;
  89073. this._touches.remove(e.pointerId.toString());
  89074. };
  89075. /**
  89076. * Change the color of the virtual joystick
  89077. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  89078. */
  89079. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  89080. this._joystickColor = newColor;
  89081. };
  89082. /**
  89083. * Defines a callback to call when the joystick is touched
  89084. * @param action defines the callback
  89085. */
  89086. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  89087. this._action = action;
  89088. };
  89089. /**
  89090. * Defines which axis you'd like to control for left & right
  89091. * @param axis defines the axis to use
  89092. */
  89093. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  89094. switch (axis) {
  89095. case JoystickAxis.X:
  89096. case JoystickAxis.Y:
  89097. case JoystickAxis.Z:
  89098. this._axisTargetedByLeftAndRight = axis;
  89099. break;
  89100. default:
  89101. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89102. break;
  89103. }
  89104. };
  89105. /**
  89106. * Defines which axis you'd like to control for up & down
  89107. * @param axis defines the axis to use
  89108. */
  89109. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  89110. switch (axis) {
  89111. case JoystickAxis.X:
  89112. case JoystickAxis.Y:
  89113. case JoystickAxis.Z:
  89114. this._axisTargetedByUpAndDown = axis;
  89115. break;
  89116. default:
  89117. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89118. break;
  89119. }
  89120. };
  89121. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  89122. var _this = this;
  89123. if (this.pressed) {
  89124. this._touches.forEach(function (key, touch) {
  89125. if (touch.pointerId === _this._joystickPointerID) {
  89126. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  89127. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  89128. VirtualJoystick.vjCanvasContext.beginPath();
  89129. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89130. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89131. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  89132. VirtualJoystick.vjCanvasContext.stroke();
  89133. VirtualJoystick.vjCanvasContext.closePath();
  89134. VirtualJoystick.vjCanvasContext.beginPath();
  89135. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89136. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89137. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  89138. VirtualJoystick.vjCanvasContext.stroke();
  89139. VirtualJoystick.vjCanvasContext.closePath();
  89140. VirtualJoystick.vjCanvasContext.beginPath();
  89141. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89142. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  89143. VirtualJoystick.vjCanvasContext.stroke();
  89144. VirtualJoystick.vjCanvasContext.closePath();
  89145. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  89146. }
  89147. else {
  89148. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89149. VirtualJoystick.vjCanvasContext.beginPath();
  89150. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  89151. VirtualJoystick.vjCanvasContext.beginPath();
  89152. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  89153. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89154. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  89155. VirtualJoystick.vjCanvasContext.stroke();
  89156. VirtualJoystick.vjCanvasContext.closePath();
  89157. touch.prevX = touch.x;
  89158. touch.prevY = touch.y;
  89159. }
  89160. ;
  89161. });
  89162. }
  89163. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89164. };
  89165. /**
  89166. * Release internal HTML canvas
  89167. */
  89168. VirtualJoystick.prototype.releaseCanvas = function () {
  89169. if (VirtualJoystick.vjCanvas) {
  89170. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  89171. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  89172. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  89173. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  89174. window.removeEventListener("resize", this._onResize);
  89175. document.body.removeChild(VirtualJoystick.vjCanvas);
  89176. VirtualJoystick.vjCanvas = null;
  89177. }
  89178. };
  89179. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  89180. VirtualJoystick._globalJoystickIndex = 0;
  89181. return VirtualJoystick;
  89182. }());
  89183. BABYLON.VirtualJoystick = VirtualJoystick;
  89184. })(BABYLON || (BABYLON = {}));
  89185. //# sourceMappingURL=babylon.virtualJoystick.js.map
  89186. var BABYLON;
  89187. (function (BABYLON) {
  89188. // We're mainly based on the logic defined into the FreeCamera code
  89189. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  89190. __extends(VirtualJoysticksCamera, _super);
  89191. function VirtualJoysticksCamera(name, position, scene) {
  89192. var _this = _super.call(this, name, position, scene) || this;
  89193. _this.inputs.addVirtualJoystick();
  89194. return _this;
  89195. }
  89196. VirtualJoysticksCamera.prototype.getClassName = function () {
  89197. return "VirtualJoysticksCamera";
  89198. };
  89199. return VirtualJoysticksCamera;
  89200. }(BABYLON.FreeCamera));
  89201. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  89202. })(BABYLON || (BABYLON = {}));
  89203. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  89204. var BABYLON;
  89205. (function (BABYLON) {
  89206. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  89207. function FreeCameraVirtualJoystickInput() {
  89208. }
  89209. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  89210. return this._leftjoystick;
  89211. };
  89212. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  89213. return this._rightjoystick;
  89214. };
  89215. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  89216. if (this._leftjoystick) {
  89217. var camera = this.camera;
  89218. var speed = camera._computeLocalCameraSpeed() * 50;
  89219. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  89220. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  89221. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  89222. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  89223. if (!this._leftjoystick.pressed) {
  89224. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  89225. }
  89226. if (!this._rightjoystick.pressed) {
  89227. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  89228. }
  89229. }
  89230. };
  89231. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  89232. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  89233. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  89234. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  89235. this._leftjoystick.setJoystickSensibility(0.15);
  89236. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  89237. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  89238. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  89239. this._rightjoystick.reverseUpDown = true;
  89240. this._rightjoystick.setJoystickSensibility(0.05);
  89241. this._rightjoystick.setJoystickColor("yellow");
  89242. };
  89243. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  89244. this._leftjoystick.releaseCanvas();
  89245. this._rightjoystick.releaseCanvas();
  89246. };
  89247. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  89248. return "FreeCameraVirtualJoystickInput";
  89249. };
  89250. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  89251. return "virtualJoystick";
  89252. };
  89253. return FreeCameraVirtualJoystickInput;
  89254. }());
  89255. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  89256. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  89257. })(BABYLON || (BABYLON = {}));
  89258. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  89259. var BABYLON;
  89260. (function (BABYLON) {
  89261. var SimplificationSettings = /** @class */ (function () {
  89262. function SimplificationSettings(quality, distance, optimizeMesh) {
  89263. this.quality = quality;
  89264. this.distance = distance;
  89265. this.optimizeMesh = optimizeMesh;
  89266. }
  89267. return SimplificationSettings;
  89268. }());
  89269. BABYLON.SimplificationSettings = SimplificationSettings;
  89270. var SimplificationQueue = /** @class */ (function () {
  89271. function SimplificationQueue() {
  89272. this.running = false;
  89273. this._simplificationArray = [];
  89274. }
  89275. SimplificationQueue.prototype.addTask = function (task) {
  89276. this._simplificationArray.push(task);
  89277. };
  89278. SimplificationQueue.prototype.executeNext = function () {
  89279. var task = this._simplificationArray.pop();
  89280. if (task) {
  89281. this.running = true;
  89282. this.runSimplification(task);
  89283. }
  89284. else {
  89285. this.running = false;
  89286. }
  89287. };
  89288. SimplificationQueue.prototype.runSimplification = function (task) {
  89289. var _this = this;
  89290. if (task.parallelProcessing) {
  89291. //parallel simplifier
  89292. task.settings.forEach(function (setting) {
  89293. var simplifier = _this.getSimplifier(task);
  89294. simplifier.simplify(setting, function (newMesh) {
  89295. task.mesh.addLODLevel(setting.distance, newMesh);
  89296. newMesh.isVisible = true;
  89297. //check if it is the last
  89298. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  89299. //all done, run the success callback.
  89300. task.successCallback();
  89301. }
  89302. _this.executeNext();
  89303. });
  89304. });
  89305. }
  89306. else {
  89307. //single simplifier.
  89308. var simplifier = this.getSimplifier(task);
  89309. var runDecimation = function (setting, callback) {
  89310. simplifier.simplify(setting, function (newMesh) {
  89311. task.mesh.addLODLevel(setting.distance, newMesh);
  89312. newMesh.isVisible = true;
  89313. //run the next quality level
  89314. callback();
  89315. });
  89316. };
  89317. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  89318. runDecimation(task.settings[loop.index], function () {
  89319. loop.executeNext();
  89320. });
  89321. }, function () {
  89322. //execution ended, run the success callback.
  89323. if (task.successCallback) {
  89324. task.successCallback();
  89325. }
  89326. _this.executeNext();
  89327. });
  89328. }
  89329. };
  89330. SimplificationQueue.prototype.getSimplifier = function (task) {
  89331. switch (task.simplificationType) {
  89332. case SimplificationType.QUADRATIC:
  89333. default:
  89334. return new QuadraticErrorSimplification(task.mesh);
  89335. }
  89336. };
  89337. return SimplificationQueue;
  89338. }());
  89339. BABYLON.SimplificationQueue = SimplificationQueue;
  89340. /**
  89341. * The implemented types of simplification
  89342. * At the moment only Quadratic Error Decimation is implemented
  89343. */
  89344. var SimplificationType;
  89345. (function (SimplificationType) {
  89346. /** Quadratic error decimation */
  89347. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  89348. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  89349. var DecimationTriangle = /** @class */ (function () {
  89350. function DecimationTriangle(vertices) {
  89351. this.vertices = vertices;
  89352. this.error = new Array(4);
  89353. this.deleted = false;
  89354. this.isDirty = false;
  89355. this.deletePending = false;
  89356. this.borderFactor = 0;
  89357. }
  89358. return DecimationTriangle;
  89359. }());
  89360. BABYLON.DecimationTriangle = DecimationTriangle;
  89361. var DecimationVertex = /** @class */ (function () {
  89362. function DecimationVertex(position, id) {
  89363. this.position = position;
  89364. this.id = id;
  89365. this.isBorder = true;
  89366. this.q = new QuadraticMatrix();
  89367. this.triangleCount = 0;
  89368. this.triangleStart = 0;
  89369. this.originalOffsets = [];
  89370. }
  89371. DecimationVertex.prototype.updatePosition = function (newPosition) {
  89372. this.position.copyFrom(newPosition);
  89373. };
  89374. return DecimationVertex;
  89375. }());
  89376. BABYLON.DecimationVertex = DecimationVertex;
  89377. var QuadraticMatrix = /** @class */ (function () {
  89378. function QuadraticMatrix(data) {
  89379. this.data = new Array(10);
  89380. for (var i = 0; i < 10; ++i) {
  89381. if (data && data[i]) {
  89382. this.data[i] = data[i];
  89383. }
  89384. else {
  89385. this.data[i] = 0;
  89386. }
  89387. }
  89388. }
  89389. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  89390. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  89391. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  89392. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  89393. return det;
  89394. };
  89395. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  89396. for (var i = 0; i < 10; ++i) {
  89397. this.data[i] += matrix.data[i];
  89398. }
  89399. };
  89400. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  89401. for (var i = 0; i < 10; ++i) {
  89402. this.data[i] += data[i];
  89403. }
  89404. };
  89405. QuadraticMatrix.prototype.add = function (matrix) {
  89406. var m = new QuadraticMatrix();
  89407. for (var i = 0; i < 10; ++i) {
  89408. m.data[i] = this.data[i] + matrix.data[i];
  89409. }
  89410. return m;
  89411. };
  89412. QuadraticMatrix.FromData = function (a, b, c, d) {
  89413. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  89414. };
  89415. //returning an array to avoid garbage collection
  89416. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  89417. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  89418. };
  89419. return QuadraticMatrix;
  89420. }());
  89421. BABYLON.QuadraticMatrix = QuadraticMatrix;
  89422. var Reference = /** @class */ (function () {
  89423. function Reference(vertexId, triangleId) {
  89424. this.vertexId = vertexId;
  89425. this.triangleId = triangleId;
  89426. }
  89427. return Reference;
  89428. }());
  89429. BABYLON.Reference = Reference;
  89430. /**
  89431. * An implementation of the Quadratic Error simplification algorithm.
  89432. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  89433. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  89434. * @author RaananW
  89435. */
  89436. var QuadraticErrorSimplification = /** @class */ (function () {
  89437. function QuadraticErrorSimplification(_mesh) {
  89438. this._mesh = _mesh;
  89439. this.syncIterations = 5000;
  89440. this.aggressiveness = 7;
  89441. this.decimationIterations = 100;
  89442. this.boundingBoxEpsilon = BABYLON.Epsilon;
  89443. }
  89444. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  89445. var _this = this;
  89446. this.initDecimatedMesh();
  89447. //iterating through the submeshes array, one after the other.
  89448. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  89449. _this.initWithMesh(loop.index, function () {
  89450. _this.runDecimation(settings, loop.index, function () {
  89451. loop.executeNext();
  89452. });
  89453. }, settings.optimizeMesh);
  89454. }, function () {
  89455. setTimeout(function () {
  89456. successCallback(_this._reconstructedMesh);
  89457. }, 0);
  89458. });
  89459. };
  89460. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  89461. var _this = this;
  89462. var targetCount = ~~(this.triangles.length * settings.quality);
  89463. var deletedTriangles = 0;
  89464. var triangleCount = this.triangles.length;
  89465. var iterationFunction = function (iteration, callback) {
  89466. setTimeout(function () {
  89467. if (iteration % 5 === 0) {
  89468. _this.updateMesh(iteration === 0);
  89469. }
  89470. for (var i = 0; i < _this.triangles.length; ++i) {
  89471. _this.triangles[i].isDirty = false;
  89472. }
  89473. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  89474. var trianglesIterator = function (i) {
  89475. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  89476. var t = _this.triangles[tIdx];
  89477. if (!t)
  89478. return;
  89479. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  89480. return;
  89481. }
  89482. for (var j = 0; j < 3; ++j) {
  89483. if (t.error[j] < threshold) {
  89484. var deleted0 = [];
  89485. var deleted1 = [];
  89486. var v0 = t.vertices[j];
  89487. var v1 = t.vertices[(j + 1) % 3];
  89488. if (v0.isBorder || v1.isBorder)
  89489. continue;
  89490. var p = BABYLON.Vector3.Zero();
  89491. var n = BABYLON.Vector3.Zero();
  89492. var uv = BABYLON.Vector2.Zero();
  89493. var color = new BABYLON.Color4(0, 0, 0, 1);
  89494. _this.calculateError(v0, v1, p, n, uv, color);
  89495. var delTr = new Array();
  89496. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  89497. continue;
  89498. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  89499. continue;
  89500. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  89501. continue;
  89502. var uniqueArray = new Array();
  89503. delTr.forEach(function (deletedT) {
  89504. if (uniqueArray.indexOf(deletedT) === -1) {
  89505. deletedT.deletePending = true;
  89506. uniqueArray.push(deletedT);
  89507. }
  89508. });
  89509. if (uniqueArray.length % 2 !== 0) {
  89510. continue;
  89511. }
  89512. v0.q = v1.q.add(v0.q);
  89513. v0.updatePosition(p);
  89514. var tStart = _this.references.length;
  89515. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  89516. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  89517. var tCount = _this.references.length - tStart;
  89518. if (tCount <= v0.triangleCount) {
  89519. if (tCount) {
  89520. for (var c = 0; c < tCount; c++) {
  89521. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  89522. }
  89523. }
  89524. }
  89525. else {
  89526. v0.triangleStart = tStart;
  89527. }
  89528. v0.triangleCount = tCount;
  89529. break;
  89530. }
  89531. }
  89532. };
  89533. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  89534. }, 0);
  89535. };
  89536. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  89537. if (triangleCount - deletedTriangles <= targetCount)
  89538. loop.breakLoop();
  89539. else {
  89540. iterationFunction(loop.index, function () {
  89541. loop.executeNext();
  89542. });
  89543. }
  89544. }, function () {
  89545. setTimeout(function () {
  89546. //reconstruct this part of the mesh
  89547. _this.reconstructMesh(submeshIndex);
  89548. successCallback();
  89549. }, 0);
  89550. });
  89551. };
  89552. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  89553. var _this = this;
  89554. this.vertices = [];
  89555. this.triangles = [];
  89556. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  89557. var indices = this._mesh.getIndices();
  89558. var submesh = this._mesh.subMeshes[submeshIndex];
  89559. var findInVertices = function (positionToSearch) {
  89560. if (optimizeMesh) {
  89561. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  89562. if (_this.vertices[ii].position.equals(positionToSearch)) {
  89563. return _this.vertices[ii];
  89564. }
  89565. }
  89566. }
  89567. return null;
  89568. };
  89569. var vertexReferences = [];
  89570. var vertexInit = function (i) {
  89571. if (!positionData) {
  89572. return;
  89573. }
  89574. var offset = i + submesh.verticesStart;
  89575. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  89576. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  89577. vertex.originalOffsets.push(offset);
  89578. if (vertex.id === _this.vertices.length) {
  89579. _this.vertices.push(vertex);
  89580. }
  89581. vertexReferences.push(vertex.id);
  89582. };
  89583. //var totalVertices = mesh.getTotalVertices();
  89584. var totalVertices = submesh.verticesCount;
  89585. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  89586. var indicesInit = function (i) {
  89587. if (!indices) {
  89588. return;
  89589. }
  89590. var offset = (submesh.indexStart / 3) + i;
  89591. var pos = (offset * 3);
  89592. var i0 = indices[pos + 0];
  89593. var i1 = indices[pos + 1];
  89594. var i2 = indices[pos + 2];
  89595. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  89596. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  89597. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  89598. var triangle = new DecimationTriangle([v0, v1, v2]);
  89599. triangle.originalOffset = pos;
  89600. _this.triangles.push(triangle);
  89601. };
  89602. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  89603. _this.init(callback);
  89604. });
  89605. });
  89606. };
  89607. QuadraticErrorSimplification.prototype.init = function (callback) {
  89608. var _this = this;
  89609. var triangleInit1 = function (i) {
  89610. var t = _this.triangles[i];
  89611. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  89612. for (var j = 0; j < 3; j++) {
  89613. 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))));
  89614. }
  89615. };
  89616. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  89617. var triangleInit2 = function (i) {
  89618. var t = _this.triangles[i];
  89619. for (var j = 0; j < 3; ++j) {
  89620. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  89621. }
  89622. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89623. };
  89624. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  89625. callback();
  89626. });
  89627. });
  89628. };
  89629. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  89630. var newTriangles = [];
  89631. var i;
  89632. for (i = 0; i < this.vertices.length; ++i) {
  89633. this.vertices[i].triangleCount = 0;
  89634. }
  89635. var t;
  89636. var j;
  89637. for (i = 0; i < this.triangles.length; ++i) {
  89638. if (!this.triangles[i].deleted) {
  89639. t = this.triangles[i];
  89640. for (j = 0; j < 3; ++j) {
  89641. t.vertices[j].triangleCount = 1;
  89642. }
  89643. newTriangles.push(t);
  89644. }
  89645. }
  89646. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  89647. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  89648. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  89649. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  89650. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  89651. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  89652. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  89653. var vertexCount = 0;
  89654. for (i = 0; i < this.vertices.length; ++i) {
  89655. var vertex = this.vertices[i];
  89656. vertex.id = vertexCount;
  89657. if (vertex.triangleCount) {
  89658. vertex.originalOffsets.forEach(function (originalOffset) {
  89659. if (!normalData) {
  89660. return;
  89661. }
  89662. newPositionData.push(vertex.position.x);
  89663. newPositionData.push(vertex.position.y);
  89664. newPositionData.push(vertex.position.z);
  89665. newNormalData.push(normalData[originalOffset * 3]);
  89666. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  89667. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  89668. if (uvs && uvs.length) {
  89669. newUVsData.push(uvs[(originalOffset * 2)]);
  89670. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  89671. }
  89672. else if (colorsData && colorsData.length) {
  89673. newColorsData.push(colorsData[(originalOffset * 4)]);
  89674. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  89675. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  89676. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  89677. }
  89678. ++vertexCount;
  89679. });
  89680. }
  89681. }
  89682. var startingIndex = this._reconstructedMesh.getTotalIndices();
  89683. var startingVertex = this._reconstructedMesh.getTotalVertices();
  89684. var submeshesArray = this._reconstructedMesh.subMeshes;
  89685. this._reconstructedMesh.subMeshes = [];
  89686. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  89687. var originalIndices = this._mesh.getIndices();
  89688. for (i = 0; i < newTriangles.length; ++i) {
  89689. t = newTriangles[i]; //now get the new referencing point for each vertex
  89690. [0, 1, 2].forEach(function (idx) {
  89691. var id = originalIndices[t.originalOffset + idx];
  89692. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  89693. if (offset < 0)
  89694. offset = 0;
  89695. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  89696. });
  89697. }
  89698. //overwriting the old vertex buffers and indices.
  89699. this._reconstructedMesh.setIndices(newIndicesArray);
  89700. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  89701. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  89702. if (newUVsData.length > 0)
  89703. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  89704. if (newColorsData.length > 0)
  89705. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  89706. //create submesh
  89707. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  89708. if (submeshIndex > 0) {
  89709. this._reconstructedMesh.subMeshes = [];
  89710. submeshesArray.forEach(function (submesh) {
  89711. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  89712. });
  89713. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  89714. }
  89715. };
  89716. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  89717. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  89718. this._reconstructedMesh.material = this._mesh.material;
  89719. this._reconstructedMesh.parent = this._mesh.parent;
  89720. this._reconstructedMesh.isVisible = false;
  89721. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  89722. };
  89723. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  89724. for (var i = 0; i < vertex1.triangleCount; ++i) {
  89725. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  89726. if (t.deleted)
  89727. continue;
  89728. var s = this.references[vertex1.triangleStart + i].vertexId;
  89729. var v1 = t.vertices[(s + 1) % 3];
  89730. var v2 = t.vertices[(s + 2) % 3];
  89731. if ((v1 === vertex2 || v2 === vertex2)) {
  89732. deletedArray[i] = true;
  89733. delTr.push(t);
  89734. continue;
  89735. }
  89736. var d1 = v1.position.subtract(point);
  89737. d1 = d1.normalize();
  89738. var d2 = v2.position.subtract(point);
  89739. d2 = d2.normalize();
  89740. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  89741. return true;
  89742. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  89743. deletedArray[i] = false;
  89744. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  89745. return true;
  89746. }
  89747. return false;
  89748. };
  89749. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  89750. var newDeleted = deletedTriangles;
  89751. for (var i = 0; i < vertex.triangleCount; ++i) {
  89752. var ref = this.references[vertex.triangleStart + i];
  89753. var t = this.triangles[ref.triangleId];
  89754. if (t.deleted)
  89755. continue;
  89756. if (deletedArray[i] && t.deletePending) {
  89757. t.deleted = true;
  89758. newDeleted++;
  89759. continue;
  89760. }
  89761. t.vertices[ref.vertexId] = origVertex;
  89762. t.isDirty = true;
  89763. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  89764. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  89765. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  89766. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89767. this.references.push(ref);
  89768. }
  89769. return newDeleted;
  89770. };
  89771. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  89772. for (var i = 0; i < this.vertices.length; ++i) {
  89773. var vCount = [];
  89774. var vId = [];
  89775. var v = this.vertices[i];
  89776. var j;
  89777. for (j = 0; j < v.triangleCount; ++j) {
  89778. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  89779. for (var ii = 0; ii < 3; ii++) {
  89780. var ofs = 0;
  89781. var vv = triangle.vertices[ii];
  89782. while (ofs < vCount.length) {
  89783. if (vId[ofs] === vv.id)
  89784. break;
  89785. ++ofs;
  89786. }
  89787. if (ofs === vCount.length) {
  89788. vCount.push(1);
  89789. vId.push(vv.id);
  89790. }
  89791. else {
  89792. vCount[ofs]++;
  89793. }
  89794. }
  89795. }
  89796. for (j = 0; j < vCount.length; ++j) {
  89797. if (vCount[j] === 1) {
  89798. this.vertices[vId[j]].isBorder = true;
  89799. }
  89800. else {
  89801. this.vertices[vId[j]].isBorder = false;
  89802. }
  89803. }
  89804. }
  89805. };
  89806. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  89807. if (identifyBorders === void 0) { identifyBorders = false; }
  89808. var i;
  89809. if (!identifyBorders) {
  89810. var newTrianglesVector = [];
  89811. for (i = 0; i < this.triangles.length; ++i) {
  89812. if (!this.triangles[i].deleted) {
  89813. newTrianglesVector.push(this.triangles[i]);
  89814. }
  89815. }
  89816. this.triangles = newTrianglesVector;
  89817. }
  89818. for (i = 0; i < this.vertices.length; ++i) {
  89819. this.vertices[i].triangleCount = 0;
  89820. this.vertices[i].triangleStart = 0;
  89821. }
  89822. var t;
  89823. var j;
  89824. var v;
  89825. for (i = 0; i < this.triangles.length; ++i) {
  89826. t = this.triangles[i];
  89827. for (j = 0; j < 3; ++j) {
  89828. v = t.vertices[j];
  89829. v.triangleCount++;
  89830. }
  89831. }
  89832. var tStart = 0;
  89833. for (i = 0; i < this.vertices.length; ++i) {
  89834. this.vertices[i].triangleStart = tStart;
  89835. tStart += this.vertices[i].triangleCount;
  89836. this.vertices[i].triangleCount = 0;
  89837. }
  89838. var newReferences = new Array(this.triangles.length * 3);
  89839. for (i = 0; i < this.triangles.length; ++i) {
  89840. t = this.triangles[i];
  89841. for (j = 0; j < 3; ++j) {
  89842. v = t.vertices[j];
  89843. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  89844. v.triangleCount++;
  89845. }
  89846. }
  89847. this.references = newReferences;
  89848. if (identifyBorders) {
  89849. this.identifyBorder();
  89850. }
  89851. };
  89852. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  89853. var x = point.x;
  89854. var y = point.y;
  89855. var z = point.z;
  89856. 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
  89857. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  89858. };
  89859. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  89860. var q = vertex1.q.add(vertex2.q);
  89861. var border = vertex1.isBorder && vertex2.isBorder;
  89862. var error = 0;
  89863. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  89864. if (qDet !== 0 && !border) {
  89865. if (!pointResult) {
  89866. pointResult = BABYLON.Vector3.Zero();
  89867. }
  89868. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  89869. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  89870. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  89871. error = this.vertexError(q, pointResult);
  89872. }
  89873. else {
  89874. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  89875. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  89876. var error1 = this.vertexError(q, vertex1.position);
  89877. var error2 = this.vertexError(q, vertex2.position);
  89878. var error3 = this.vertexError(q, p3);
  89879. error = Math.min(error1, error2, error3);
  89880. if (error === error1) {
  89881. if (pointResult) {
  89882. pointResult.copyFrom(vertex1.position);
  89883. }
  89884. }
  89885. else if (error === error2) {
  89886. if (pointResult) {
  89887. pointResult.copyFrom(vertex2.position);
  89888. }
  89889. }
  89890. else {
  89891. if (pointResult) {
  89892. pointResult.copyFrom(p3);
  89893. }
  89894. }
  89895. }
  89896. return error;
  89897. };
  89898. return QuadraticErrorSimplification;
  89899. }());
  89900. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  89901. })(BABYLON || (BABYLON = {}));
  89902. //# sourceMappingURL=babylon.meshSimplification.js.map
  89903. var BABYLON;
  89904. (function (BABYLON) {
  89905. var MeshLODLevel = /** @class */ (function () {
  89906. function MeshLODLevel(distance, mesh) {
  89907. this.distance = distance;
  89908. this.mesh = mesh;
  89909. }
  89910. return MeshLODLevel;
  89911. }());
  89912. BABYLON.MeshLODLevel = MeshLODLevel;
  89913. })(BABYLON || (BABYLON = {}));
  89914. //# sourceMappingURL=babylon.meshLODLevel.js.map
  89915. var BABYLON;
  89916. (function (BABYLON) {
  89917. /**
  89918. * Defines the root class used to create scene optimization to use with SceneOptimizer
  89919. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89920. */
  89921. var SceneOptimization = /** @class */ (function () {
  89922. /**
  89923. * Creates the SceneOptimization object
  89924. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89925. * @param desc defines the description associated with the optimization
  89926. */
  89927. function SceneOptimization(
  89928. /**
  89929. * Defines the priority of this optimization (0 by default which means first in the list)
  89930. */
  89931. priority) {
  89932. if (priority === void 0) { priority = 0; }
  89933. this.priority = priority;
  89934. }
  89935. /**
  89936. * Gets a string describing the action executed by the current optimization
  89937. * @returns description string
  89938. */
  89939. SceneOptimization.prototype.getDescription = function () {
  89940. return "";
  89941. };
  89942. /**
  89943. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89944. * @param scene defines the current scene where to apply this optimization
  89945. * @param optimizer defines the current optimizer
  89946. * @returns true if everything that can be done was applied
  89947. */
  89948. SceneOptimization.prototype.apply = function (scene, optimizer) {
  89949. return true;
  89950. };
  89951. ;
  89952. return SceneOptimization;
  89953. }());
  89954. BABYLON.SceneOptimization = SceneOptimization;
  89955. /**
  89956. * Defines an optimization used to reduce the size of render target textures
  89957. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89958. */
  89959. var TextureOptimization = /** @class */ (function (_super) {
  89960. __extends(TextureOptimization, _super);
  89961. /**
  89962. * Creates the TextureOptimization object
  89963. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89964. * @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
  89965. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  89966. */
  89967. function TextureOptimization(
  89968. /**
  89969. * Defines the priority of this optimization (0 by default which means first in the list)
  89970. */
  89971. priority,
  89972. /**
  89973. * 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
  89974. */
  89975. maximumSize,
  89976. /**
  89977. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  89978. */
  89979. step) {
  89980. if (priority === void 0) { priority = 0; }
  89981. if (maximumSize === void 0) { maximumSize = 1024; }
  89982. if (step === void 0) { step = 0.5; }
  89983. var _this = _super.call(this, priority) || this;
  89984. _this.priority = priority;
  89985. _this.maximumSize = maximumSize;
  89986. _this.step = step;
  89987. return _this;
  89988. }
  89989. /**
  89990. * Gets a string describing the action executed by the current optimization
  89991. * @returns description string
  89992. */
  89993. TextureOptimization.prototype.getDescription = function () {
  89994. return "Reducing render target texture size to " + this.maximumSize;
  89995. };
  89996. /**
  89997. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89998. * @param scene defines the current scene where to apply this optimization
  89999. * @param optimizer defines the current optimizer
  90000. * @returns true if everything that can be done was applied
  90001. */
  90002. TextureOptimization.prototype.apply = function (scene, optimizer) {
  90003. var allDone = true;
  90004. for (var index = 0; index < scene.textures.length; index++) {
  90005. var texture = scene.textures[index];
  90006. if (!texture.canRescale || texture.getContext) {
  90007. continue;
  90008. }
  90009. var currentSize = texture.getSize();
  90010. var maxDimension = Math.max(currentSize.width, currentSize.height);
  90011. if (maxDimension > this.maximumSize) {
  90012. texture.scale(this.step);
  90013. allDone = false;
  90014. }
  90015. }
  90016. return allDone;
  90017. };
  90018. return TextureOptimization;
  90019. }(SceneOptimization));
  90020. BABYLON.TextureOptimization = TextureOptimization;
  90021. /**
  90022. * Defines an optimization used to increase or decrease the rendering resolution
  90023. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90024. */
  90025. var HardwareScalingOptimization = /** @class */ (function (_super) {
  90026. __extends(HardwareScalingOptimization, _super);
  90027. /**
  90028. * Creates the HardwareScalingOptimization object
  90029. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90030. * @param maximumScale defines the maximum scale to use (2 by default)
  90031. * @param step defines the step to use between two passes (0.5 by default)
  90032. */
  90033. function HardwareScalingOptimization(
  90034. /**
  90035. * Defines the priority of this optimization (0 by default which means first in the list)
  90036. */
  90037. priority,
  90038. /**
  90039. * Defines the maximum scale to use (2 by default)
  90040. */
  90041. maximumScale,
  90042. /**
  90043. * Defines the step to use between two passes (0.5 by default)
  90044. */
  90045. step) {
  90046. if (priority === void 0) { priority = 0; }
  90047. if (maximumScale === void 0) { maximumScale = 2; }
  90048. if (step === void 0) { step = 0.25; }
  90049. var _this = _super.call(this, priority) || this;
  90050. _this.priority = priority;
  90051. _this.maximumScale = maximumScale;
  90052. _this.step = step;
  90053. _this._currentScale = -1;
  90054. _this._directionOffset = 1;
  90055. return _this;
  90056. }
  90057. /**
  90058. * Gets a string describing the action executed by the current optimization
  90059. * @return description string
  90060. */
  90061. HardwareScalingOptimization.prototype.getDescription = function () {
  90062. return "Setting hardware scaling level to " + this._currentScale;
  90063. };
  90064. /**
  90065. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90066. * @param scene defines the current scene where to apply this optimization
  90067. * @param optimizer defines the current optimizer
  90068. * @returns true if everything that can be done was applied
  90069. */
  90070. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  90071. if (this._currentScale === -1) {
  90072. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  90073. if (this._currentScale > this.maximumScale) {
  90074. this._directionOffset = -1;
  90075. }
  90076. }
  90077. this._currentScale += this._directionOffset * this.step;
  90078. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  90079. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  90080. };
  90081. ;
  90082. return HardwareScalingOptimization;
  90083. }(SceneOptimization));
  90084. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  90085. /**
  90086. * Defines an optimization used to remove shadows
  90087. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90088. */
  90089. var ShadowsOptimization = /** @class */ (function (_super) {
  90090. __extends(ShadowsOptimization, _super);
  90091. function ShadowsOptimization() {
  90092. return _super !== null && _super.apply(this, arguments) || this;
  90093. }
  90094. /**
  90095. * Gets a string describing the action executed by the current optimization
  90096. * @return description string
  90097. */
  90098. ShadowsOptimization.prototype.getDescription = function () {
  90099. return "Turning shadows on/off";
  90100. };
  90101. /**
  90102. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90103. * @param scene defines the current scene where to apply this optimization
  90104. * @param optimizer defines the current optimizer
  90105. * @returns true if everything that can be done was applied
  90106. */
  90107. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  90108. scene.shadowsEnabled = optimizer.isInImprovementMode;
  90109. return true;
  90110. };
  90111. ;
  90112. return ShadowsOptimization;
  90113. }(SceneOptimization));
  90114. BABYLON.ShadowsOptimization = ShadowsOptimization;
  90115. /**
  90116. * Defines an optimization used to turn post-processes off
  90117. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90118. */
  90119. var PostProcessesOptimization = /** @class */ (function (_super) {
  90120. __extends(PostProcessesOptimization, _super);
  90121. function PostProcessesOptimization() {
  90122. return _super !== null && _super.apply(this, arguments) || this;
  90123. }
  90124. /**
  90125. * Gets a string describing the action executed by the current optimization
  90126. * @return description string
  90127. */
  90128. PostProcessesOptimization.prototype.getDescription = function () {
  90129. return "Turning post-processes on/off";
  90130. };
  90131. /**
  90132. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90133. * @param scene defines the current scene where to apply this optimization
  90134. * @param optimizer defines the current optimizer
  90135. * @returns true if everything that can be done was applied
  90136. */
  90137. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  90138. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  90139. return true;
  90140. };
  90141. ;
  90142. return PostProcessesOptimization;
  90143. }(SceneOptimization));
  90144. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  90145. /**
  90146. * Defines an optimization used to turn lens flares off
  90147. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90148. */
  90149. var LensFlaresOptimization = /** @class */ (function (_super) {
  90150. __extends(LensFlaresOptimization, _super);
  90151. function LensFlaresOptimization() {
  90152. return _super !== null && _super.apply(this, arguments) || this;
  90153. }
  90154. /**
  90155. * Gets a string describing the action executed by the current optimization
  90156. * @return description string
  90157. */
  90158. LensFlaresOptimization.prototype.getDescription = function () {
  90159. return "Turning lens flares on/off";
  90160. };
  90161. /**
  90162. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90163. * @param scene defines the current scene where to apply this optimization
  90164. * @param optimizer defines the current optimizer
  90165. * @returns true if everything that can be done was applied
  90166. */
  90167. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  90168. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  90169. return true;
  90170. };
  90171. ;
  90172. return LensFlaresOptimization;
  90173. }(SceneOptimization));
  90174. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  90175. /**
  90176. * Defines an optimization based on user defined callback.
  90177. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90178. */
  90179. var CustomOptimization = /** @class */ (function (_super) {
  90180. __extends(CustomOptimization, _super);
  90181. function CustomOptimization() {
  90182. return _super !== null && _super.apply(this, arguments) || this;
  90183. }
  90184. /**
  90185. * Gets a string describing the action executed by the current optimization
  90186. * @returns description string
  90187. */
  90188. CustomOptimization.prototype.getDescription = function () {
  90189. if (this.onGetDescription) {
  90190. return this.onGetDescription();
  90191. }
  90192. return "Running user defined callback";
  90193. };
  90194. /**
  90195. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90196. * @param scene defines the current scene where to apply this optimization
  90197. * @param optimizer defines the current optimizer
  90198. * @returns true if everything that can be done was applied
  90199. */
  90200. CustomOptimization.prototype.apply = function (scene, optimizer) {
  90201. if (this.onApply) {
  90202. return this.onApply(scene, optimizer);
  90203. }
  90204. return true;
  90205. };
  90206. ;
  90207. return CustomOptimization;
  90208. }(SceneOptimization));
  90209. BABYLON.CustomOptimization = CustomOptimization;
  90210. /**
  90211. * Defines an optimization used to turn particles off
  90212. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90213. */
  90214. var ParticlesOptimization = /** @class */ (function (_super) {
  90215. __extends(ParticlesOptimization, _super);
  90216. function ParticlesOptimization() {
  90217. return _super !== null && _super.apply(this, arguments) || this;
  90218. }
  90219. /**
  90220. * Gets a string describing the action executed by the current optimization
  90221. * @return description string
  90222. */
  90223. ParticlesOptimization.prototype.getDescription = function () {
  90224. return "Turning particles on/off";
  90225. };
  90226. /**
  90227. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90228. * @param scene defines the current scene where to apply this optimization
  90229. * @param optimizer defines the current optimizer
  90230. * @returns true if everything that can be done was applied
  90231. */
  90232. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  90233. scene.particlesEnabled = optimizer.isInImprovementMode;
  90234. return true;
  90235. };
  90236. ;
  90237. return ParticlesOptimization;
  90238. }(SceneOptimization));
  90239. BABYLON.ParticlesOptimization = ParticlesOptimization;
  90240. /**
  90241. * Defines an optimization used to turn render targets off
  90242. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90243. */
  90244. var RenderTargetsOptimization = /** @class */ (function (_super) {
  90245. __extends(RenderTargetsOptimization, _super);
  90246. function RenderTargetsOptimization() {
  90247. return _super !== null && _super.apply(this, arguments) || this;
  90248. }
  90249. /**
  90250. * Gets a string describing the action executed by the current optimization
  90251. * @return description string
  90252. */
  90253. RenderTargetsOptimization.prototype.getDescription = function () {
  90254. return "Turning render targets off";
  90255. };
  90256. /**
  90257. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90258. * @param scene defines the current scene where to apply this optimization
  90259. * @param optimizer defines the current optimizer
  90260. * @returns true if everything that can be done was applied
  90261. */
  90262. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  90263. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  90264. return true;
  90265. };
  90266. ;
  90267. return RenderTargetsOptimization;
  90268. }(SceneOptimization));
  90269. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  90270. /**
  90271. * Defines an optimization used to merge meshes with compatible materials
  90272. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90273. */
  90274. var MergeMeshesOptimization = /** @class */ (function (_super) {
  90275. __extends(MergeMeshesOptimization, _super);
  90276. function MergeMeshesOptimization() {
  90277. var _this = _super !== null && _super.apply(this, arguments) || this;
  90278. _this._canBeMerged = function (abstractMesh) {
  90279. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  90280. return false;
  90281. }
  90282. var mesh = abstractMesh;
  90283. if (!mesh.isVisible || !mesh.isEnabled()) {
  90284. return false;
  90285. }
  90286. if (mesh.instances.length > 0) {
  90287. return false;
  90288. }
  90289. if (mesh.skeleton || mesh.hasLODLevels) {
  90290. return false;
  90291. }
  90292. if (mesh.parent) {
  90293. return false;
  90294. }
  90295. return true;
  90296. };
  90297. return _this;
  90298. }
  90299. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  90300. /**
  90301. * Gets or sets a boolean which defines if optimization octree has to be updated
  90302. */
  90303. get: function () {
  90304. return MergeMeshesOptimization._UpdateSelectionTree;
  90305. },
  90306. /**
  90307. * Gets or sets a boolean which defines if optimization octree has to be updated
  90308. */
  90309. set: function (value) {
  90310. MergeMeshesOptimization._UpdateSelectionTree = value;
  90311. },
  90312. enumerable: true,
  90313. configurable: true
  90314. });
  90315. /**
  90316. * Gets a string describing the action executed by the current optimization
  90317. * @return description string
  90318. */
  90319. MergeMeshesOptimization.prototype.getDescription = function () {
  90320. return "Merging similar meshes together";
  90321. };
  90322. /**
  90323. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90324. * @param scene defines the current scene where to apply this optimization
  90325. * @param optimizer defines the current optimizer
  90326. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  90327. * @returns true if everything that can be done was applied
  90328. */
  90329. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  90330. var globalPool = scene.meshes.slice(0);
  90331. var globalLength = globalPool.length;
  90332. for (var index = 0; index < globalLength; index++) {
  90333. var currentPool = new Array();
  90334. var current = globalPool[index];
  90335. // Checks
  90336. if (!this._canBeMerged(current)) {
  90337. continue;
  90338. }
  90339. currentPool.push(current);
  90340. // Find compatible meshes
  90341. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  90342. var otherMesh = globalPool[subIndex];
  90343. if (!this._canBeMerged(otherMesh)) {
  90344. continue;
  90345. }
  90346. if (otherMesh.material !== current.material) {
  90347. continue;
  90348. }
  90349. if (otherMesh.checkCollisions !== current.checkCollisions) {
  90350. continue;
  90351. }
  90352. currentPool.push(otherMesh);
  90353. globalLength--;
  90354. globalPool.splice(subIndex, 1);
  90355. subIndex--;
  90356. }
  90357. if (currentPool.length < 2) {
  90358. continue;
  90359. }
  90360. // Merge meshes
  90361. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  90362. }
  90363. if (updateSelectionTree != undefined) {
  90364. if (updateSelectionTree) {
  90365. scene.createOrUpdateSelectionOctree();
  90366. }
  90367. }
  90368. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  90369. scene.createOrUpdateSelectionOctree();
  90370. }
  90371. return true;
  90372. };
  90373. ;
  90374. MergeMeshesOptimization._UpdateSelectionTree = false;
  90375. return MergeMeshesOptimization;
  90376. }(SceneOptimization));
  90377. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  90378. /**
  90379. * Defines a list of options used by SceneOptimizer
  90380. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90381. */
  90382. var SceneOptimizerOptions = /** @class */ (function () {
  90383. /**
  90384. * Creates a new list of options used by SceneOptimizer
  90385. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  90386. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  90387. */
  90388. function SceneOptimizerOptions(
  90389. /**
  90390. * Defines the target frame rate to reach (60 by default)
  90391. */
  90392. targetFrameRate,
  90393. /**
  90394. * Defines the interval between two checkes (2000ms by default)
  90395. */
  90396. trackerDuration) {
  90397. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  90398. if (trackerDuration === void 0) { trackerDuration = 2000; }
  90399. this.targetFrameRate = targetFrameRate;
  90400. this.trackerDuration = trackerDuration;
  90401. /**
  90402. * Gets the list of optimizations to apply
  90403. */
  90404. this.optimizations = new Array();
  90405. }
  90406. /**
  90407. * Add a new optimization
  90408. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  90409. * @returns the current SceneOptimizerOptions
  90410. */
  90411. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  90412. this.optimizations.push(optimization);
  90413. return this;
  90414. };
  90415. /**
  90416. * Add a new custom optimization
  90417. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  90418. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  90419. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90420. * @returns the current SceneOptimizerOptions
  90421. */
  90422. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  90423. if (priority === void 0) { priority = 0; }
  90424. var optimization = new CustomOptimization(priority);
  90425. optimization.onApply = onApply;
  90426. optimization.onGetDescription = onGetDescription;
  90427. this.optimizations.push(optimization);
  90428. return this;
  90429. };
  90430. /**
  90431. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  90432. * @param targetFrameRate defines the target frame rate (60 by default)
  90433. * @returns a SceneOptimizerOptions object
  90434. */
  90435. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  90436. var result = new SceneOptimizerOptions(targetFrameRate);
  90437. var priority = 0;
  90438. result.addOptimization(new MergeMeshesOptimization(priority));
  90439. result.addOptimization(new ShadowsOptimization(priority));
  90440. result.addOptimization(new LensFlaresOptimization(priority));
  90441. // Next priority
  90442. priority++;
  90443. result.addOptimization(new PostProcessesOptimization(priority));
  90444. result.addOptimization(new ParticlesOptimization(priority));
  90445. // Next priority
  90446. priority++;
  90447. result.addOptimization(new TextureOptimization(priority, 1024));
  90448. return result;
  90449. };
  90450. /**
  90451. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  90452. * @param targetFrameRate defines the target frame rate (60 by default)
  90453. * @returns a SceneOptimizerOptions object
  90454. */
  90455. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  90456. var result = new SceneOptimizerOptions(targetFrameRate);
  90457. var priority = 0;
  90458. result.addOptimization(new MergeMeshesOptimization(priority));
  90459. result.addOptimization(new ShadowsOptimization(priority));
  90460. result.addOptimization(new LensFlaresOptimization(priority));
  90461. // Next priority
  90462. priority++;
  90463. result.addOptimization(new PostProcessesOptimization(priority));
  90464. result.addOptimization(new ParticlesOptimization(priority));
  90465. // Next priority
  90466. priority++;
  90467. result.addOptimization(new TextureOptimization(priority, 512));
  90468. // Next priority
  90469. priority++;
  90470. result.addOptimization(new RenderTargetsOptimization(priority));
  90471. // Next priority
  90472. priority++;
  90473. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  90474. return result;
  90475. };
  90476. /**
  90477. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  90478. * @param targetFrameRate defines the target frame rate (60 by default)
  90479. * @returns a SceneOptimizerOptions object
  90480. */
  90481. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  90482. var result = new SceneOptimizerOptions(targetFrameRate);
  90483. var priority = 0;
  90484. result.addOptimization(new MergeMeshesOptimization(priority));
  90485. result.addOptimization(new ShadowsOptimization(priority));
  90486. result.addOptimization(new LensFlaresOptimization(priority));
  90487. // Next priority
  90488. priority++;
  90489. result.addOptimization(new PostProcessesOptimization(priority));
  90490. result.addOptimization(new ParticlesOptimization(priority));
  90491. // Next priority
  90492. priority++;
  90493. result.addOptimization(new TextureOptimization(priority, 256));
  90494. // Next priority
  90495. priority++;
  90496. result.addOptimization(new RenderTargetsOptimization(priority));
  90497. // Next priority
  90498. priority++;
  90499. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  90500. return result;
  90501. };
  90502. return SceneOptimizerOptions;
  90503. }());
  90504. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  90505. /**
  90506. * Class used to run optimizations in order to reach a target frame rate
  90507. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90508. */
  90509. var SceneOptimizer = /** @class */ (function () {
  90510. /**
  90511. * Creates a new SceneOptimizer
  90512. * @param scene defines the scene to work on
  90513. * @param options defines the options to use with the SceneOptimizer
  90514. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  90515. * @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)
  90516. */
  90517. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  90518. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  90519. if (improvementMode === void 0) { improvementMode = false; }
  90520. var _this = this;
  90521. this._isRunning = false;
  90522. this._currentPriorityLevel = 0;
  90523. this._targetFrameRate = 60;
  90524. this._trackerDuration = 2000;
  90525. this._currentFrameRate = 0;
  90526. this._improvementMode = false;
  90527. /**
  90528. * Defines an observable called when the optimizer reaches the target frame rate
  90529. */
  90530. this.onSuccessObservable = new BABYLON.Observable();
  90531. /**
  90532. * Defines an observable called when the optimizer enables an optimization
  90533. */
  90534. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  90535. /**
  90536. * Defines an observable called when the optimizer is not able to reach the target frame rate
  90537. */
  90538. this.onFailureObservable = new BABYLON.Observable();
  90539. if (!options) {
  90540. this._options = new SceneOptimizerOptions();
  90541. }
  90542. else {
  90543. this._options = options;
  90544. }
  90545. if (this._options.targetFrameRate) {
  90546. this._targetFrameRate = this._options.targetFrameRate;
  90547. }
  90548. if (this._options.trackerDuration) {
  90549. this._trackerDuration = this._options.trackerDuration;
  90550. }
  90551. if (autoGeneratePriorities) {
  90552. var priority = 0;
  90553. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  90554. var optim = _a[_i];
  90555. optim.priority = priority++;
  90556. }
  90557. }
  90558. this._improvementMode = improvementMode;
  90559. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90560. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  90561. _this._sceneDisposeObserver = null;
  90562. _this.dispose();
  90563. });
  90564. }
  90565. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  90566. /**
  90567. * Gets a boolean indicating if the optimizer is in improvement mode
  90568. */
  90569. get: function () {
  90570. return this._improvementMode;
  90571. },
  90572. enumerable: true,
  90573. configurable: true
  90574. });
  90575. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  90576. /**
  90577. * Gets the current priority level (0 at start)
  90578. */
  90579. get: function () {
  90580. return this._currentPriorityLevel;
  90581. },
  90582. enumerable: true,
  90583. configurable: true
  90584. });
  90585. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  90586. /**
  90587. * Gets the current frame rate checked by the SceneOptimizer
  90588. */
  90589. get: function () {
  90590. return this._currentFrameRate;
  90591. },
  90592. enumerable: true,
  90593. configurable: true
  90594. });
  90595. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  90596. /**
  90597. * Gets or sets the current target frame rate (60 by default)
  90598. */
  90599. get: function () {
  90600. return this._targetFrameRate;
  90601. },
  90602. /**
  90603. * Gets or sets the current target frame rate (60 by default)
  90604. */
  90605. set: function (value) {
  90606. this._targetFrameRate = value;
  90607. },
  90608. enumerable: true,
  90609. configurable: true
  90610. });
  90611. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  90612. /**
  90613. * Gets or sets the current interval between two checks (every 2000ms by default)
  90614. */
  90615. get: function () {
  90616. return this._trackerDuration;
  90617. },
  90618. /**
  90619. * Gets or sets the current interval between two checks (every 2000ms by default)
  90620. */
  90621. set: function (value) {
  90622. this._trackerDuration = value;
  90623. },
  90624. enumerable: true,
  90625. configurable: true
  90626. });
  90627. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  90628. /**
  90629. * Gets the list of active optimizations
  90630. */
  90631. get: function () {
  90632. return this._options.optimizations;
  90633. },
  90634. enumerable: true,
  90635. configurable: true
  90636. });
  90637. /**
  90638. * Stops the current optimizer
  90639. */
  90640. SceneOptimizer.prototype.stop = function () {
  90641. this._isRunning = false;
  90642. };
  90643. /**
  90644. * Reset the optimizer to initial step (current priority level = 0)
  90645. */
  90646. SceneOptimizer.prototype.reset = function () {
  90647. this._currentPriorityLevel = 0;
  90648. };
  90649. /**
  90650. * Start the optimizer. By default it will try to reach a specific framerate
  90651. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  90652. */
  90653. SceneOptimizer.prototype.start = function () {
  90654. var _this = this;
  90655. if (this._isRunning) {
  90656. return;
  90657. }
  90658. this._isRunning = true;
  90659. // Let's wait for the scene to be ready before running our check
  90660. this._scene.executeWhenReady(function () {
  90661. setTimeout(function () {
  90662. _this._checkCurrentState();
  90663. }, _this._trackerDuration);
  90664. });
  90665. };
  90666. SceneOptimizer.prototype._checkCurrentState = function () {
  90667. var _this = this;
  90668. if (!this._isRunning) {
  90669. return;
  90670. }
  90671. var scene = this._scene;
  90672. var options = this._options;
  90673. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  90674. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  90675. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  90676. this._isRunning = false;
  90677. this.onSuccessObservable.notifyObservers(this);
  90678. return;
  90679. }
  90680. // Apply current level of optimizations
  90681. var allDone = true;
  90682. var noOptimizationApplied = true;
  90683. for (var index = 0; index < options.optimizations.length; index++) {
  90684. var optimization = options.optimizations[index];
  90685. if (optimization.priority === this._currentPriorityLevel) {
  90686. noOptimizationApplied = false;
  90687. allDone = allDone && optimization.apply(scene, this);
  90688. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  90689. }
  90690. }
  90691. // If no optimization was applied, this is a failure :(
  90692. if (noOptimizationApplied) {
  90693. this._isRunning = false;
  90694. this.onFailureObservable.notifyObservers(this);
  90695. return;
  90696. }
  90697. // If all optimizations were done, move to next level
  90698. if (allDone) {
  90699. this._currentPriorityLevel++;
  90700. }
  90701. // Let's the system running for a specific amount of time before checking FPS
  90702. scene.executeWhenReady(function () {
  90703. setTimeout(function () {
  90704. _this._checkCurrentState();
  90705. }, _this._trackerDuration);
  90706. });
  90707. };
  90708. /**
  90709. * Release all resources
  90710. */
  90711. SceneOptimizer.prototype.dispose = function () {
  90712. this.stop();
  90713. this.onSuccessObservable.clear();
  90714. this.onFailureObservable.clear();
  90715. this.onNewOptimizationAppliedObservable.clear();
  90716. if (this._sceneDisposeObserver) {
  90717. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  90718. }
  90719. };
  90720. /**
  90721. * Helper function to create a SceneOptimizer with one single line of code
  90722. * @param scene defines the scene to work on
  90723. * @param options defines the options to use with the SceneOptimizer
  90724. * @param onSuccess defines a callback to call on success
  90725. * @param onFailure defines a callback to call on failure
  90726. * @returns the new SceneOptimizer object
  90727. */
  90728. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  90729. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  90730. if (onSuccess) {
  90731. optimizer.onSuccessObservable.add(function () {
  90732. onSuccess();
  90733. });
  90734. }
  90735. if (onFailure) {
  90736. optimizer.onFailureObservable.add(function () {
  90737. onFailure();
  90738. });
  90739. }
  90740. optimizer.start();
  90741. return optimizer;
  90742. };
  90743. return SceneOptimizer;
  90744. }());
  90745. BABYLON.SceneOptimizer = SceneOptimizer;
  90746. })(BABYLON || (BABYLON = {}));
  90747. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  90748. var BABYLON;
  90749. (function (BABYLON) {
  90750. var OutlineRenderer = /** @class */ (function () {
  90751. function OutlineRenderer(scene) {
  90752. this.zOffset = 1;
  90753. this._scene = scene;
  90754. }
  90755. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  90756. var _this = this;
  90757. if (useOverlay === void 0) { useOverlay = false; }
  90758. var scene = this._scene;
  90759. var engine = this._scene.getEngine();
  90760. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  90761. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  90762. return;
  90763. }
  90764. var mesh = subMesh.getRenderingMesh();
  90765. var material = subMesh.getMaterial();
  90766. if (!material || !scene.activeCamera) {
  90767. return;
  90768. }
  90769. engine.enableEffect(this._effect);
  90770. // Logarithmic depth
  90771. if (material.useLogarithmicDepth) {
  90772. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  90773. }
  90774. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  90775. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  90776. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  90777. // Bones
  90778. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  90779. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  90780. }
  90781. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  90782. // Alpha test
  90783. if (material && material.needAlphaTesting()) {
  90784. var alphaTexture = material.getAlphaTestTexture();
  90785. if (alphaTexture) {
  90786. this._effect.setTexture("diffuseSampler", alphaTexture);
  90787. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  90788. }
  90789. }
  90790. engine.setZOffset(-this.zOffset);
  90791. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  90792. engine.setZOffset(0);
  90793. };
  90794. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  90795. var defines = [];
  90796. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  90797. var mesh = subMesh.getMesh();
  90798. var material = subMesh.getMaterial();
  90799. if (material) {
  90800. // Alpha test
  90801. if (material.needAlphaTesting()) {
  90802. defines.push("#define ALPHATEST");
  90803. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90804. attribs.push(BABYLON.VertexBuffer.UVKind);
  90805. defines.push("#define UV1");
  90806. }
  90807. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  90808. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90809. defines.push("#define UV2");
  90810. }
  90811. }
  90812. //Logarithmic depth
  90813. if (material.useLogarithmicDepth) {
  90814. defines.push("#define LOGARITHMICDEPTH");
  90815. }
  90816. }
  90817. // Bones
  90818. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  90819. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  90820. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  90821. if (mesh.numBoneInfluencers > 4) {
  90822. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  90823. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  90824. }
  90825. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  90826. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  90827. }
  90828. else {
  90829. defines.push("#define NUM_BONE_INFLUENCERS 0");
  90830. }
  90831. // Instances
  90832. if (useInstances) {
  90833. defines.push("#define INSTANCES");
  90834. attribs.push("world0");
  90835. attribs.push("world1");
  90836. attribs.push("world2");
  90837. attribs.push("world3");
  90838. }
  90839. // Get correct effect
  90840. var join = defines.join("\n");
  90841. if (this._cachedDefines !== join) {
  90842. this._cachedDefines = join;
  90843. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  90844. }
  90845. return this._effect.isReady();
  90846. };
  90847. return OutlineRenderer;
  90848. }());
  90849. BABYLON.OutlineRenderer = OutlineRenderer;
  90850. })(BABYLON || (BABYLON = {}));
  90851. //# sourceMappingURL=babylon.outlineRenderer.js.map
  90852. var BABYLON;
  90853. (function (BABYLON) {
  90854. var FaceAdjacencies = /** @class */ (function () {
  90855. function FaceAdjacencies() {
  90856. this.edges = new Array();
  90857. this.edgesConnectedCount = 0;
  90858. }
  90859. return FaceAdjacencies;
  90860. }());
  90861. var EdgesRenderer = /** @class */ (function () {
  90862. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  90863. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  90864. if (epsilon === void 0) { epsilon = 0.95; }
  90865. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  90866. this.edgesWidthScalerForOrthographic = 1000.0;
  90867. this.edgesWidthScalerForPerspective = 50.0;
  90868. this._linesPositions = new Array();
  90869. this._linesNormals = new Array();
  90870. this._linesIndices = new Array();
  90871. this._buffers = {};
  90872. this._checkVerticesInsteadOfIndices = false;
  90873. this._source = source;
  90874. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  90875. this._epsilon = epsilon;
  90876. this._prepareRessources();
  90877. this._generateEdgesLines();
  90878. }
  90879. EdgesRenderer.prototype._prepareRessources = function () {
  90880. if (this._lineShader) {
  90881. return;
  90882. }
  90883. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  90884. attributes: ["position", "normal"],
  90885. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  90886. });
  90887. this._lineShader.disableDepthWrite = true;
  90888. this._lineShader.backFaceCulling = false;
  90889. };
  90890. EdgesRenderer.prototype._rebuild = function () {
  90891. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  90892. if (buffer) {
  90893. buffer._rebuild();
  90894. }
  90895. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  90896. if (buffer) {
  90897. buffer._rebuild();
  90898. }
  90899. var scene = this._source.getScene();
  90900. var engine = scene.getEngine();
  90901. this._ib = engine.createIndexBuffer(this._linesIndices);
  90902. };
  90903. EdgesRenderer.prototype.dispose = function () {
  90904. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  90905. if (buffer) {
  90906. buffer.dispose();
  90907. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  90908. }
  90909. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  90910. if (buffer) {
  90911. buffer.dispose();
  90912. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  90913. }
  90914. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  90915. this._lineShader.dispose();
  90916. };
  90917. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  90918. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  90919. return 0;
  90920. }
  90921. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  90922. return 1;
  90923. }
  90924. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  90925. return 2;
  90926. }
  90927. return -1;
  90928. };
  90929. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  90930. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  90931. return 0;
  90932. }
  90933. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  90934. return 1;
  90935. }
  90936. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  90937. return 2;
  90938. }
  90939. return -1;
  90940. };
  90941. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  90942. var needToCreateLine;
  90943. if (edge === undefined) {
  90944. needToCreateLine = true;
  90945. }
  90946. else {
  90947. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  90948. needToCreateLine = dotProduct < this._epsilon;
  90949. }
  90950. if (needToCreateLine) {
  90951. var offset = this._linesPositions.length / 3;
  90952. var normal = p0.subtract(p1);
  90953. normal.normalize();
  90954. // Positions
  90955. this._linesPositions.push(p0.x);
  90956. this._linesPositions.push(p0.y);
  90957. this._linesPositions.push(p0.z);
  90958. this._linesPositions.push(p0.x);
  90959. this._linesPositions.push(p0.y);
  90960. this._linesPositions.push(p0.z);
  90961. this._linesPositions.push(p1.x);
  90962. this._linesPositions.push(p1.y);
  90963. this._linesPositions.push(p1.z);
  90964. this._linesPositions.push(p1.x);
  90965. this._linesPositions.push(p1.y);
  90966. this._linesPositions.push(p1.z);
  90967. // Normals
  90968. this._linesNormals.push(p1.x);
  90969. this._linesNormals.push(p1.y);
  90970. this._linesNormals.push(p1.z);
  90971. this._linesNormals.push(-1);
  90972. this._linesNormals.push(p1.x);
  90973. this._linesNormals.push(p1.y);
  90974. this._linesNormals.push(p1.z);
  90975. this._linesNormals.push(1);
  90976. this._linesNormals.push(p0.x);
  90977. this._linesNormals.push(p0.y);
  90978. this._linesNormals.push(p0.z);
  90979. this._linesNormals.push(-1);
  90980. this._linesNormals.push(p0.x);
  90981. this._linesNormals.push(p0.y);
  90982. this._linesNormals.push(p0.z);
  90983. this._linesNormals.push(1);
  90984. // Indices
  90985. this._linesIndices.push(offset);
  90986. this._linesIndices.push(offset + 1);
  90987. this._linesIndices.push(offset + 2);
  90988. this._linesIndices.push(offset);
  90989. this._linesIndices.push(offset + 2);
  90990. this._linesIndices.push(offset + 3);
  90991. }
  90992. };
  90993. EdgesRenderer.prototype._generateEdgesLines = function () {
  90994. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  90995. var indices = this._source.getIndices();
  90996. if (!indices || !positions) {
  90997. return;
  90998. }
  90999. // First let's find adjacencies
  91000. var adjacencies = new Array();
  91001. var faceNormals = new Array();
  91002. var index;
  91003. var faceAdjacencies;
  91004. // Prepare faces
  91005. for (index = 0; index < indices.length; index += 3) {
  91006. faceAdjacencies = new FaceAdjacencies();
  91007. var p0Index = indices[index];
  91008. var p1Index = indices[index + 1];
  91009. var p2Index = indices[index + 2];
  91010. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  91011. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  91012. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  91013. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  91014. faceNormal.normalize();
  91015. faceNormals.push(faceNormal);
  91016. adjacencies.push(faceAdjacencies);
  91017. }
  91018. // Scan
  91019. for (index = 0; index < adjacencies.length; index++) {
  91020. faceAdjacencies = adjacencies[index];
  91021. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  91022. var otherFaceAdjacencies = adjacencies[otherIndex];
  91023. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  91024. break;
  91025. }
  91026. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  91027. continue;
  91028. }
  91029. var otherP0 = indices[otherIndex * 3];
  91030. var otherP1 = indices[otherIndex * 3 + 1];
  91031. var otherP2 = indices[otherIndex * 3 + 2];
  91032. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  91033. var otherEdgeIndex = 0;
  91034. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  91035. continue;
  91036. }
  91037. switch (edgeIndex) {
  91038. case 0:
  91039. if (this._checkVerticesInsteadOfIndices) {
  91040. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91041. }
  91042. else {
  91043. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  91044. }
  91045. break;
  91046. case 1:
  91047. if (this._checkVerticesInsteadOfIndices) {
  91048. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91049. }
  91050. else {
  91051. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  91052. }
  91053. break;
  91054. case 2:
  91055. if (this._checkVerticesInsteadOfIndices) {
  91056. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91057. }
  91058. else {
  91059. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  91060. }
  91061. break;
  91062. }
  91063. if (otherEdgeIndex === -1) {
  91064. continue;
  91065. }
  91066. faceAdjacencies.edges[edgeIndex] = otherIndex;
  91067. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  91068. faceAdjacencies.edgesConnectedCount++;
  91069. otherFaceAdjacencies.edgesConnectedCount++;
  91070. if (faceAdjacencies.edgesConnectedCount === 3) {
  91071. break;
  91072. }
  91073. }
  91074. }
  91075. }
  91076. // Create lines
  91077. for (index = 0; index < adjacencies.length; index++) {
  91078. // 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
  91079. var current = adjacencies[index];
  91080. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  91081. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  91082. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  91083. }
  91084. // Merge into a single mesh
  91085. var engine = this._source.getScene().getEngine();
  91086. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  91087. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  91088. this._ib = engine.createIndexBuffer(this._linesIndices);
  91089. this._indicesCount = this._linesIndices.length;
  91090. };
  91091. EdgesRenderer.prototype.render = function () {
  91092. var scene = this._source.getScene();
  91093. if (!this._lineShader.isReady() || !scene.activeCamera) {
  91094. return;
  91095. }
  91096. var engine = scene.getEngine();
  91097. this._lineShader._preBind();
  91098. // VBOs
  91099. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  91100. scene.resetCachedMaterial();
  91101. this._lineShader.setColor4("color", this._source.edgesColor);
  91102. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  91103. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  91104. }
  91105. else {
  91106. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  91107. }
  91108. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  91109. this._lineShader.bind(this._source.getWorldMatrix());
  91110. // Draw order
  91111. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  91112. this._lineShader.unbind();
  91113. engine.setDepthWrite(true);
  91114. };
  91115. return EdgesRenderer;
  91116. }());
  91117. BABYLON.EdgesRenderer = EdgesRenderer;
  91118. })(BABYLON || (BABYLON = {}));
  91119. //# sourceMappingURL=babylon.edgesRenderer.js.map
  91120. var __assign = (this && this.__assign) || Object.assign || function(t) {
  91121. for (var s, i = 1, n = arguments.length; i < n; i++) {
  91122. s = arguments[i];
  91123. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  91124. t[p] = s[p];
  91125. }
  91126. return t;
  91127. };
  91128. var BABYLON;
  91129. (function (BABYLON) {
  91130. /**
  91131. * The effect layer Helps adding post process effect blended with the main pass.
  91132. *
  91133. * This can be for instance use to generate glow or higlight effects on the scene.
  91134. *
  91135. * The effect layer class can not be used directly and is intented to inherited from to be
  91136. * customized per effects.
  91137. */
  91138. var EffectLayer = /** @class */ (function () {
  91139. /**
  91140. * Instantiates a new effect Layer and references it in the scene.
  91141. * @param name The name of the layer
  91142. * @param scene The scene to use the layer in
  91143. */
  91144. function EffectLayer(
  91145. /** The Friendly of the effect in the scene */
  91146. name, scene) {
  91147. this._vertexBuffers = {};
  91148. this._maxSize = 0;
  91149. this._mainTextureDesiredSize = { width: 0, height: 0 };
  91150. this._shouldRender = true;
  91151. this._postProcesses = [];
  91152. this._textures = [];
  91153. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  91154. /**
  91155. * The clear color of the texture used to generate the glow map.
  91156. */
  91157. this.neutralColor = new BABYLON.Color4();
  91158. /**
  91159. * Specifies wether the highlight layer is enabled or not.
  91160. */
  91161. this.isEnabled = true;
  91162. /**
  91163. * An event triggered when the effect layer has been disposed.
  91164. */
  91165. this.onDisposeObservable = new BABYLON.Observable();
  91166. /**
  91167. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  91168. */
  91169. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  91170. /**
  91171. * An event triggered when the generated texture is being merged in the scene.
  91172. */
  91173. this.onBeforeComposeObservable = new BABYLON.Observable();
  91174. /**
  91175. * An event triggered when the generated texture has been merged in the scene.
  91176. */
  91177. this.onAfterComposeObservable = new BABYLON.Observable();
  91178. /**
  91179. * An event triggered when the efffect layer changes its size.
  91180. */
  91181. this.onSizeChangedObservable = new BABYLON.Observable();
  91182. this.name = name;
  91183. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91184. this._engine = scene.getEngine();
  91185. this._maxSize = this._engine.getCaps().maxTextureSize;
  91186. this._scene.effectLayers.push(this);
  91187. // Generate Buffers
  91188. this._generateIndexBuffer();
  91189. this._genrateVertexBuffer();
  91190. }
  91191. Object.defineProperty(EffectLayer.prototype, "camera", {
  91192. /**
  91193. * Gets the camera attached to the layer.
  91194. */
  91195. get: function () {
  91196. return this._effectLayerOptions.camera;
  91197. },
  91198. enumerable: true,
  91199. configurable: true
  91200. });
  91201. /**
  91202. * Initializes the effect layer with the required options.
  91203. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  91204. */
  91205. EffectLayer.prototype._init = function (options) {
  91206. // Adapt options
  91207. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91208. this._setMainTextureSize();
  91209. this._createMainTexture();
  91210. this._createTextureAndPostProcesses();
  91211. this._mergeEffect = this._createMergeEffect();
  91212. };
  91213. /**
  91214. * Generates the index buffer of the full screen quad blending to the main canvas.
  91215. */
  91216. EffectLayer.prototype._generateIndexBuffer = function () {
  91217. // Indices
  91218. var indices = [];
  91219. indices.push(0);
  91220. indices.push(1);
  91221. indices.push(2);
  91222. indices.push(0);
  91223. indices.push(2);
  91224. indices.push(3);
  91225. this._indexBuffer = this._engine.createIndexBuffer(indices);
  91226. };
  91227. /**
  91228. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  91229. */
  91230. EffectLayer.prototype._genrateVertexBuffer = function () {
  91231. // VBO
  91232. var vertices = [];
  91233. vertices.push(1, 1);
  91234. vertices.push(-1, 1);
  91235. vertices.push(-1, -1);
  91236. vertices.push(1, -1);
  91237. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  91238. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  91239. };
  91240. /**
  91241. * Sets the main texture desired size which is the closest power of two
  91242. * of the engine canvas size.
  91243. */
  91244. EffectLayer.prototype._setMainTextureSize = function () {
  91245. if (this._effectLayerOptions.mainTextureFixedSize) {
  91246. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  91247. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  91248. }
  91249. else {
  91250. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  91251. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  91252. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  91253. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  91254. }
  91255. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  91256. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  91257. };
  91258. /**
  91259. * Creates the main texture for the effect layer.
  91260. */
  91261. EffectLayer.prototype._createMainTexture = function () {
  91262. var _this = this;
  91263. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  91264. width: this._mainTextureDesiredSize.width,
  91265. height: this._mainTextureDesiredSize.height
  91266. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  91267. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  91268. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91269. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91270. this._mainTexture.anisotropicFilteringLevel = 1;
  91271. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91272. this._mainTexture.renderParticles = false;
  91273. this._mainTexture.renderList = null;
  91274. this._mainTexture.ignoreCameraViewport = true;
  91275. // Custom render function
  91276. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  91277. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  91278. var index;
  91279. var engine = _this._scene.getEngine();
  91280. if (depthOnlySubMeshes.length) {
  91281. engine.setColorWrite(false);
  91282. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  91283. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  91284. }
  91285. engine.setColorWrite(true);
  91286. }
  91287. for (index = 0; index < opaqueSubMeshes.length; index++) {
  91288. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  91289. }
  91290. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  91291. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  91292. }
  91293. for (index = 0; index < transparentSubMeshes.length; index++) {
  91294. _this._renderSubMesh(transparentSubMeshes.data[index]);
  91295. }
  91296. };
  91297. this._mainTexture.onClearObservable.add(function (engine) {
  91298. engine.clear(_this.neutralColor, true, true, true);
  91299. });
  91300. };
  91301. /**
  91302. * Checks for the readiness of the element composing the layer.
  91303. * @param subMesh the mesh to check for
  91304. * @param useInstances specify wether or not to use instances to render the mesh
  91305. * @param emissiveTexture the associated emissive texture used to generate the glow
  91306. * @return true if ready otherwise, false
  91307. */
  91308. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  91309. var material = subMesh.getMaterial();
  91310. if (!material) {
  91311. return false;
  91312. }
  91313. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  91314. return false;
  91315. }
  91316. var defines = [];
  91317. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91318. var mesh = subMesh.getMesh();
  91319. var uv1 = false;
  91320. var uv2 = false;
  91321. // Alpha test
  91322. if (material && material.needAlphaTesting()) {
  91323. var alphaTexture = material.getAlphaTestTexture();
  91324. if (alphaTexture) {
  91325. defines.push("#define ALPHATEST");
  91326. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91327. alphaTexture.coordinatesIndex === 1) {
  91328. defines.push("#define DIFFUSEUV2");
  91329. uv2 = true;
  91330. }
  91331. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91332. defines.push("#define DIFFUSEUV1");
  91333. uv1 = true;
  91334. }
  91335. }
  91336. }
  91337. // Emissive
  91338. if (emissiveTexture) {
  91339. defines.push("#define EMISSIVE");
  91340. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91341. emissiveTexture.coordinatesIndex === 1) {
  91342. defines.push("#define EMISSIVEUV2");
  91343. uv2 = true;
  91344. }
  91345. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91346. defines.push("#define EMISSIVEUV1");
  91347. uv1 = true;
  91348. }
  91349. }
  91350. if (uv1) {
  91351. attribs.push(BABYLON.VertexBuffer.UVKind);
  91352. defines.push("#define UV1");
  91353. }
  91354. if (uv2) {
  91355. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91356. defines.push("#define UV2");
  91357. }
  91358. // Bones
  91359. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  91360. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  91361. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  91362. if (mesh.numBoneInfluencers > 4) {
  91363. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  91364. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  91365. }
  91366. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  91367. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  91368. }
  91369. else {
  91370. defines.push("#define NUM_BONE_INFLUENCERS 0");
  91371. }
  91372. // Morph targets
  91373. var manager = mesh.morphTargetManager;
  91374. var morphInfluencers = 0;
  91375. if (manager) {
  91376. if (manager.numInfluencers > 0) {
  91377. defines.push("#define MORPHTARGETS");
  91378. morphInfluencers = manager.numInfluencers;
  91379. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  91380. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  91381. }
  91382. }
  91383. // Instances
  91384. if (useInstances) {
  91385. defines.push("#define INSTANCES");
  91386. attribs.push("world0");
  91387. attribs.push("world1");
  91388. attribs.push("world2");
  91389. attribs.push("world3");
  91390. }
  91391. // Get correct effect
  91392. var join = defines.join("\n");
  91393. if (this._cachedDefines !== join) {
  91394. this._cachedDefines = join;
  91395. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  91396. }
  91397. return this._effectLayerMapGenerationEffect.isReady();
  91398. };
  91399. /**
  91400. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  91401. */
  91402. EffectLayer.prototype.render = function () {
  91403. var currentEffect = this._mergeEffect;
  91404. // Check
  91405. if (!currentEffect.isReady())
  91406. return;
  91407. for (var i = 0; i < this._postProcesses.length; i++) {
  91408. if (!this._postProcesses[i].isReady()) {
  91409. return;
  91410. }
  91411. }
  91412. var engine = this._scene.getEngine();
  91413. this.onBeforeComposeObservable.notifyObservers(this);
  91414. // Render
  91415. engine.enableEffect(currentEffect);
  91416. engine.setState(false);
  91417. // VBOs
  91418. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  91419. // Cache
  91420. var previousAlphaMode = engine.getAlphaMode();
  91421. // Go Blend.
  91422. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  91423. // Blends the map on the main canvas.
  91424. this._internalRender(currentEffect);
  91425. // Restore Alpha
  91426. engine.setAlphaMode(previousAlphaMode);
  91427. this.onAfterComposeObservable.notifyObservers(this);
  91428. // Handle size changes.
  91429. var size = this._mainTexture.getSize();
  91430. this._setMainTextureSize();
  91431. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  91432. // Recreate RTT and post processes on size change.
  91433. this.onSizeChangedObservable.notifyObservers(this);
  91434. this._disposeTextureAndPostProcesses();
  91435. this._createMainTexture();
  91436. this._createTextureAndPostProcesses();
  91437. }
  91438. };
  91439. /**
  91440. * Determine if a given mesh will be used in the current effect.
  91441. * @param mesh mesh to test
  91442. * @returns true if the mesh will be used
  91443. */
  91444. EffectLayer.prototype.hasMesh = function (mesh) {
  91445. return true;
  91446. };
  91447. /**
  91448. * Returns true if the layer contains information to display, otherwise false.
  91449. * @returns true if the glow layer should be rendered
  91450. */
  91451. EffectLayer.prototype.shouldRender = function () {
  91452. return this.isEnabled && this._shouldRender;
  91453. };
  91454. /**
  91455. * Returns true if the mesh should render, otherwise false.
  91456. * @param mesh The mesh to render
  91457. * @returns true if it should render otherwise false
  91458. */
  91459. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  91460. return true;
  91461. };
  91462. /**
  91463. * Returns true if the mesh should render, otherwise false.
  91464. * @param mesh The mesh to render
  91465. * @returns true if it should render otherwise false
  91466. */
  91467. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  91468. return true;
  91469. };
  91470. /**
  91471. * Renders the submesh passed in parameter to the generation map.
  91472. */
  91473. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  91474. var _this = this;
  91475. if (!this.shouldRender()) {
  91476. return;
  91477. }
  91478. var material = subMesh.getMaterial();
  91479. var mesh = subMesh.getRenderingMesh();
  91480. var scene = this._scene;
  91481. var engine = scene.getEngine();
  91482. if (!material) {
  91483. return;
  91484. }
  91485. // Do not block in blend mode.
  91486. if (material.needAlphaBlendingForMesh(mesh)) {
  91487. return;
  91488. }
  91489. // Culling
  91490. engine.setState(material.backFaceCulling);
  91491. // Managing instances
  91492. var batch = mesh._getInstancesRenderList(subMesh._id);
  91493. if (batch.mustReturn) {
  91494. return;
  91495. }
  91496. // Early Exit per mesh
  91497. if (!this._shouldRenderMesh(mesh)) {
  91498. return;
  91499. }
  91500. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  91501. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  91502. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  91503. engine.enableEffect(this._effectLayerMapGenerationEffect);
  91504. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  91505. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  91506. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  91507. // Alpha test
  91508. if (material && material.needAlphaTesting()) {
  91509. var alphaTexture = material.getAlphaTestTexture();
  91510. if (alphaTexture) {
  91511. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  91512. var textureMatrix = alphaTexture.getTextureMatrix();
  91513. if (textureMatrix) {
  91514. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  91515. }
  91516. }
  91517. }
  91518. // Glow emissive only
  91519. if (this._emissiveTextureAndColor.texture) {
  91520. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  91521. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  91522. }
  91523. // Bones
  91524. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  91525. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  91526. }
  91527. // Morph targets
  91528. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  91529. // Draw
  91530. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  91531. }
  91532. else {
  91533. // Need to reset refresh rate of the shadowMap
  91534. this._mainTexture.resetRefreshCounter();
  91535. }
  91536. };
  91537. /**
  91538. * Rebuild the required buffers.
  91539. * @hidden Internal use only.
  91540. */
  91541. EffectLayer.prototype._rebuild = function () {
  91542. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91543. if (vb) {
  91544. vb._rebuild();
  91545. }
  91546. this._generateIndexBuffer();
  91547. };
  91548. /**
  91549. * Dispose only the render target textures and post process.
  91550. */
  91551. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  91552. this._mainTexture.dispose();
  91553. for (var i = 0; i < this._postProcesses.length; i++) {
  91554. if (this._postProcesses[i]) {
  91555. this._postProcesses[i].dispose();
  91556. }
  91557. }
  91558. this._postProcesses = [];
  91559. for (var i = 0; i < this._textures.length; i++) {
  91560. if (this._textures[i]) {
  91561. this._textures[i].dispose();
  91562. }
  91563. }
  91564. this._textures = [];
  91565. };
  91566. /**
  91567. * Dispose the highlight layer and free resources.
  91568. */
  91569. EffectLayer.prototype.dispose = function () {
  91570. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91571. if (vertexBuffer) {
  91572. vertexBuffer.dispose();
  91573. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  91574. }
  91575. if (this._indexBuffer) {
  91576. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  91577. this._indexBuffer = null;
  91578. }
  91579. // Clean textures and post processes
  91580. this._disposeTextureAndPostProcesses();
  91581. // Remove from scene
  91582. var index = this._scene.effectLayers.indexOf(this, 0);
  91583. if (index > -1) {
  91584. this._scene.effectLayers.splice(index, 1);
  91585. }
  91586. // Callback
  91587. this.onDisposeObservable.notifyObservers(this);
  91588. this.onDisposeObservable.clear();
  91589. this.onBeforeRenderMainTextureObservable.clear();
  91590. this.onBeforeComposeObservable.clear();
  91591. this.onAfterComposeObservable.clear();
  91592. this.onSizeChangedObservable.clear();
  91593. };
  91594. /**
  91595. * Gets the class name of the effect layer
  91596. * @returns the string with the class name of the effect layer
  91597. */
  91598. EffectLayer.prototype.getClassName = function () {
  91599. return "EffectLayer";
  91600. };
  91601. /**
  91602. * Creates an effect layer from parsed effect layer data
  91603. * @param parsedEffectLayer defines effect layer data
  91604. * @param scene defines the current scene
  91605. * @param rootUrl defines the root URL containing the effect layer information
  91606. * @returns a parsed effect Layer
  91607. */
  91608. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  91609. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  91610. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  91611. };
  91612. __decorate([
  91613. BABYLON.serialize()
  91614. ], EffectLayer.prototype, "name", void 0);
  91615. __decorate([
  91616. BABYLON.serializeAsColor4()
  91617. ], EffectLayer.prototype, "neutralColor", void 0);
  91618. __decorate([
  91619. BABYLON.serialize()
  91620. ], EffectLayer.prototype, "isEnabled", void 0);
  91621. __decorate([
  91622. BABYLON.serializeAsCameraReference()
  91623. ], EffectLayer.prototype, "camera", null);
  91624. return EffectLayer;
  91625. }());
  91626. BABYLON.EffectLayer = EffectLayer;
  91627. })(BABYLON || (BABYLON = {}));
  91628. //# sourceMappingURL=babylon.effectLayer.js.map
  91629. var BABYLON;
  91630. (function (BABYLON) {
  91631. /**
  91632. * Special Glow Blur post process only blurring the alpha channel
  91633. * It enforces keeping the most luminous color in the color channel.
  91634. */
  91635. var GlowBlurPostProcess = /** @class */ (function (_super) {
  91636. __extends(GlowBlurPostProcess, _super);
  91637. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  91638. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  91639. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  91640. _this.direction = direction;
  91641. _this.kernel = kernel;
  91642. _this.onApplyObservable.add(function (effect) {
  91643. effect.setFloat2("screenSize", _this.width, _this.height);
  91644. effect.setVector2("direction", _this.direction);
  91645. effect.setFloat("blurWidth", _this.kernel);
  91646. });
  91647. return _this;
  91648. }
  91649. return GlowBlurPostProcess;
  91650. }(BABYLON.PostProcess));
  91651. /**
  91652. * The highlight layer Helps adding a glow effect around a mesh.
  91653. *
  91654. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  91655. * glowy meshes to your scene.
  91656. *
  91657. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  91658. */
  91659. var HighlightLayer = /** @class */ (function (_super) {
  91660. __extends(HighlightLayer, _super);
  91661. /**
  91662. * Instantiates a new highlight Layer and references it to the scene..
  91663. * @param name The name of the layer
  91664. * @param scene The scene to use the layer in
  91665. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  91666. */
  91667. function HighlightLayer(name, scene, options) {
  91668. var _this = _super.call(this, name, scene) || this;
  91669. _this.name = name;
  91670. /**
  91671. * Specifies whether or not the inner glow is ACTIVE in the layer.
  91672. */
  91673. _this.innerGlow = true;
  91674. /**
  91675. * Specifies whether or not the outer glow is ACTIVE in the layer.
  91676. */
  91677. _this.outerGlow = true;
  91678. /**
  91679. * An event triggered when the highlight layer is being blurred.
  91680. */
  91681. _this.onBeforeBlurObservable = new BABYLON.Observable();
  91682. /**
  91683. * An event triggered when the highlight layer has been blurred.
  91684. */
  91685. _this.onAfterBlurObservable = new BABYLON.Observable();
  91686. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  91687. _this._meshes = {};
  91688. _this._excludedMeshes = {};
  91689. _this.neutralColor = HighlightLayer.NeutralColor;
  91690. // Warn on stencil
  91691. if (!_this._engine.isStencilEnable) {
  91692. 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 }");
  91693. }
  91694. // Adapt options
  91695. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91696. // Initialize the layer
  91697. _this._init({
  91698. alphaBlendingMode: _this._options.alphaBlendingMode,
  91699. camera: _this._options.camera,
  91700. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  91701. mainTextureRatio: _this._options.mainTextureRatio
  91702. });
  91703. // Do not render as long as no meshes have been added
  91704. _this._shouldRender = false;
  91705. return _this;
  91706. }
  91707. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  91708. /**
  91709. * Gets the horizontal size of the blur.
  91710. */
  91711. get: function () {
  91712. return this._horizontalBlurPostprocess.kernel;
  91713. },
  91714. /**
  91715. * Specifies the horizontal size of the blur.
  91716. */
  91717. set: function (value) {
  91718. this._horizontalBlurPostprocess.kernel = value;
  91719. },
  91720. enumerable: true,
  91721. configurable: true
  91722. });
  91723. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  91724. /**
  91725. * Gets the vertical size of the blur.
  91726. */
  91727. get: function () {
  91728. return this._verticalBlurPostprocess.kernel;
  91729. },
  91730. /**
  91731. * Specifies the vertical size of the blur.
  91732. */
  91733. set: function (value) {
  91734. this._verticalBlurPostprocess.kernel = value;
  91735. },
  91736. enumerable: true,
  91737. configurable: true
  91738. });
  91739. /**
  91740. * Get the effect name of the layer.
  91741. * @return The effect name
  91742. */
  91743. HighlightLayer.prototype.getEffectName = function () {
  91744. return HighlightLayer.EffectName;
  91745. };
  91746. /**
  91747. * Create the merge effect. This is the shader use to blit the information back
  91748. * to the main canvas at the end of the scene rendering.
  91749. */
  91750. HighlightLayer.prototype._createMergeEffect = function () {
  91751. // Effect
  91752. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  91753. };
  91754. /**
  91755. * Creates the render target textures and post processes used in the highlight layer.
  91756. */
  91757. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  91758. var _this = this;
  91759. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  91760. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  91761. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  91762. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  91763. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  91764. width: blurTextureWidth,
  91765. height: blurTextureHeight
  91766. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91767. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91768. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91769. this._blurTexture.anisotropicFilteringLevel = 16;
  91770. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  91771. this._blurTexture.renderParticles = false;
  91772. this._blurTexture.ignoreCameraViewport = true;
  91773. this._textures = [this._blurTexture];
  91774. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  91775. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91776. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  91777. effect.setTexture("textureSampler", _this._mainTexture);
  91778. });
  91779. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91780. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91781. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91782. });
  91783. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91784. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  91785. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91786. });
  91787. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91788. }
  91789. else {
  91790. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  91791. width: blurTextureWidth,
  91792. height: blurTextureHeight
  91793. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91794. this._horizontalBlurPostprocess.width = blurTextureWidth;
  91795. this._horizontalBlurPostprocess.height = blurTextureHeight;
  91796. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91797. effect.setTexture("textureSampler", _this._mainTexture);
  91798. });
  91799. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  91800. width: blurTextureWidth,
  91801. height: blurTextureHeight
  91802. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91803. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91804. }
  91805. this._mainTexture.onAfterUnbindObservable.add(function () {
  91806. _this.onBeforeBlurObservable.notifyObservers(_this);
  91807. var internalTexture = _this._blurTexture.getInternalTexture();
  91808. if (internalTexture) {
  91809. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  91810. }
  91811. _this.onAfterBlurObservable.notifyObservers(_this);
  91812. });
  91813. // Prevent autoClear.
  91814. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  91815. };
  91816. /**
  91817. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  91818. */
  91819. HighlightLayer.prototype.needStencil = function () {
  91820. return true;
  91821. };
  91822. /**
  91823. * Checks for the readiness of the element composing the layer.
  91824. * @param subMesh the mesh to check for
  91825. * @param useInstances specify wether or not to use instances to render the mesh
  91826. * @param emissiveTexture the associated emissive texture used to generate the glow
  91827. * @return true if ready otherwise, false
  91828. */
  91829. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  91830. var material = subMesh.getMaterial();
  91831. var mesh = subMesh.getRenderingMesh();
  91832. if (!material || !mesh || !this._meshes) {
  91833. return false;
  91834. }
  91835. var emissiveTexture = null;
  91836. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  91837. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  91838. emissiveTexture = material.emissiveTexture;
  91839. }
  91840. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  91841. };
  91842. /**
  91843. * Implementation specific of rendering the generating effect on the main canvas.
  91844. * @param effect The effect used to render through
  91845. */
  91846. HighlightLayer.prototype._internalRender = function (effect) {
  91847. // Texture
  91848. effect.setTexture("textureSampler", this._blurTexture);
  91849. // Cache
  91850. var engine = this._engine;
  91851. var previousStencilBuffer = engine.getStencilBuffer();
  91852. var previousStencilFunction = engine.getStencilFunction();
  91853. var previousStencilMask = engine.getStencilMask();
  91854. var previousStencilOperationPass = engine.getStencilOperationPass();
  91855. var previousStencilOperationFail = engine.getStencilOperationFail();
  91856. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  91857. var previousStencilReference = engine.getStencilFunctionReference();
  91858. // Stencil operations
  91859. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  91860. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  91861. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  91862. // Draw order
  91863. engine.setStencilMask(0x00);
  91864. engine.setStencilBuffer(true);
  91865. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  91866. // 2 passes inner outer
  91867. if (this.outerGlow) {
  91868. effect.setFloat("offset", 0);
  91869. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  91870. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91871. }
  91872. if (this.innerGlow) {
  91873. effect.setFloat("offset", 1);
  91874. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  91875. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91876. }
  91877. // Restore Cache
  91878. engine.setStencilFunction(previousStencilFunction);
  91879. engine.setStencilMask(previousStencilMask);
  91880. engine.setStencilBuffer(previousStencilBuffer);
  91881. engine.setStencilOperationPass(previousStencilOperationPass);
  91882. engine.setStencilOperationFail(previousStencilOperationFail);
  91883. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  91884. engine.setStencilFunctionReference(previousStencilReference);
  91885. };
  91886. /**
  91887. * Returns true if the layer contains information to display, otherwise false.
  91888. */
  91889. HighlightLayer.prototype.shouldRender = function () {
  91890. if (_super.prototype.shouldRender.call(this)) {
  91891. return this._meshes ? true : false;
  91892. }
  91893. return false;
  91894. };
  91895. /**
  91896. * Returns true if the mesh should render, otherwise false.
  91897. * @param mesh The mesh to render
  91898. * @returns true if it should render otherwise false
  91899. */
  91900. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  91901. // Excluded Mesh
  91902. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  91903. return false;
  91904. }
  91905. ;
  91906. return true;
  91907. };
  91908. /**
  91909. * Sets the required values for both the emissive texture and and the main color.
  91910. */
  91911. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  91912. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  91913. if (highlightLayerMesh) {
  91914. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  91915. }
  91916. else {
  91917. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  91918. }
  91919. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  91920. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  91921. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  91922. }
  91923. else {
  91924. this._emissiveTextureAndColor.texture = null;
  91925. }
  91926. };
  91927. /**
  91928. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  91929. * @param mesh The mesh to exclude from the highlight layer
  91930. */
  91931. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  91932. if (!this._excludedMeshes) {
  91933. return;
  91934. }
  91935. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  91936. if (!meshExcluded) {
  91937. this._excludedMeshes[mesh.uniqueId] = {
  91938. mesh: mesh,
  91939. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  91940. mesh.getEngine().setStencilBuffer(false);
  91941. }),
  91942. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  91943. mesh.getEngine().setStencilBuffer(true);
  91944. }),
  91945. };
  91946. }
  91947. };
  91948. /**
  91949. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  91950. * @param mesh The mesh to highlight
  91951. */
  91952. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  91953. if (!this._excludedMeshes) {
  91954. return;
  91955. }
  91956. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  91957. if (meshExcluded) {
  91958. if (meshExcluded.beforeRender) {
  91959. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  91960. }
  91961. if (meshExcluded.afterRender) {
  91962. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  91963. }
  91964. }
  91965. this._excludedMeshes[mesh.uniqueId] = null;
  91966. };
  91967. /**
  91968. * Determine if a given mesh will be highlighted by the current HighlightLayer
  91969. * @param mesh mesh to test
  91970. * @returns true if the mesh will be highlighted by the current HighlightLayer
  91971. */
  91972. HighlightLayer.prototype.hasMesh = function (mesh) {
  91973. if (!this._meshes) {
  91974. return false;
  91975. }
  91976. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  91977. };
  91978. /**
  91979. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  91980. * @param mesh The mesh to highlight
  91981. * @param color The color of the highlight
  91982. * @param glowEmissiveOnly Extract the glow from the emissive texture
  91983. */
  91984. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  91985. var _this = this;
  91986. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  91987. if (!this._meshes) {
  91988. return;
  91989. }
  91990. var meshHighlight = this._meshes[mesh.uniqueId];
  91991. if (meshHighlight) {
  91992. meshHighlight.color = color;
  91993. }
  91994. else {
  91995. this._meshes[mesh.uniqueId] = {
  91996. mesh: mesh,
  91997. color: color,
  91998. // Lambda required for capture due to Observable this context
  91999. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  92000. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  92001. _this._defaultStencilReference(mesh);
  92002. }
  92003. else {
  92004. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  92005. }
  92006. }),
  92007. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  92008. glowEmissiveOnly: glowEmissiveOnly
  92009. };
  92010. }
  92011. this._shouldRender = true;
  92012. };
  92013. /**
  92014. * Remove a mesh from the highlight layer in order to make it stop glowing.
  92015. * @param mesh The mesh to highlight
  92016. */
  92017. HighlightLayer.prototype.removeMesh = function (mesh) {
  92018. if (!this._meshes) {
  92019. return;
  92020. }
  92021. var meshHighlight = this._meshes[mesh.uniqueId];
  92022. if (meshHighlight) {
  92023. if (meshHighlight.observerHighlight) {
  92024. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92025. }
  92026. if (meshHighlight.observerDefault) {
  92027. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92028. }
  92029. delete this._meshes[mesh.uniqueId];
  92030. }
  92031. this._shouldRender = false;
  92032. for (var meshHighlightToCheck in this._meshes) {
  92033. if (this._meshes[meshHighlightToCheck]) {
  92034. this._shouldRender = true;
  92035. break;
  92036. }
  92037. }
  92038. };
  92039. /**
  92040. * Force the stencil to the normal expected value for none glowing parts
  92041. */
  92042. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  92043. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  92044. };
  92045. /**
  92046. * Free any resources and references associated to a mesh.
  92047. * Internal use
  92048. * @param mesh The mesh to free.
  92049. */
  92050. HighlightLayer.prototype._disposeMesh = function (mesh) {
  92051. this.removeMesh(mesh);
  92052. this.removeExcludedMesh(mesh);
  92053. };
  92054. /**
  92055. * Dispose the highlight layer and free resources.
  92056. */
  92057. HighlightLayer.prototype.dispose = function () {
  92058. if (this._meshes) {
  92059. // Clean mesh references
  92060. for (var id in this._meshes) {
  92061. var meshHighlight = this._meshes[id];
  92062. if (meshHighlight && meshHighlight.mesh) {
  92063. if (meshHighlight.observerHighlight) {
  92064. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92065. }
  92066. if (meshHighlight.observerDefault) {
  92067. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92068. }
  92069. }
  92070. }
  92071. this._meshes = null;
  92072. }
  92073. if (this._excludedMeshes) {
  92074. for (var id in this._excludedMeshes) {
  92075. var meshHighlight = this._excludedMeshes[id];
  92076. if (meshHighlight) {
  92077. if (meshHighlight.beforeRender) {
  92078. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  92079. }
  92080. if (meshHighlight.afterRender) {
  92081. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  92082. }
  92083. }
  92084. }
  92085. this._excludedMeshes = null;
  92086. }
  92087. _super.prototype.dispose.call(this);
  92088. };
  92089. /**
  92090. * Gets the class name of the effect layer
  92091. * @returns the string with the class name of the effect layer
  92092. */
  92093. HighlightLayer.prototype.getClassName = function () {
  92094. return "HighlightLayer";
  92095. };
  92096. /**
  92097. * Serializes this Highlight layer
  92098. * @returns a serialized Highlight layer object
  92099. */
  92100. HighlightLayer.prototype.serialize = function () {
  92101. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92102. serializationObject.customType = "BABYLON.HighlightLayer";
  92103. // Highlighted meshes
  92104. serializationObject.meshes = [];
  92105. if (this._meshes) {
  92106. for (var m in this._meshes) {
  92107. var mesh = this._meshes[m];
  92108. if (mesh) {
  92109. serializationObject.meshes.push({
  92110. glowEmissiveOnly: mesh.glowEmissiveOnly,
  92111. color: mesh.color.asArray(),
  92112. meshId: mesh.mesh.id
  92113. });
  92114. }
  92115. }
  92116. }
  92117. // Excluded meshes
  92118. serializationObject.excludedMeshes = [];
  92119. if (this._excludedMeshes) {
  92120. for (var e in this._excludedMeshes) {
  92121. var excludedMesh = this._excludedMeshes[e];
  92122. if (excludedMesh) {
  92123. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  92124. }
  92125. }
  92126. }
  92127. return serializationObject;
  92128. };
  92129. /**
  92130. * Creates a Highlight layer from parsed Highlight layer data
  92131. * @param parsedHightlightLayer defines the Highlight layer data
  92132. * @param scene defines the current scene
  92133. * @param rootUrl defines the root URL containing the Highlight layer information
  92134. * @returns a parsed Highlight layer
  92135. */
  92136. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  92137. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  92138. var index;
  92139. // Excluded meshes
  92140. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  92141. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  92142. if (mesh) {
  92143. hl.addExcludedMesh(mesh);
  92144. }
  92145. }
  92146. // Included meshes
  92147. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  92148. var highlightedMesh = parsedHightlightLayer.meshes[index];
  92149. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  92150. if (mesh) {
  92151. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  92152. }
  92153. }
  92154. return hl;
  92155. };
  92156. /**
  92157. * Effect Name of the highlight layer.
  92158. */
  92159. HighlightLayer.EffectName = "HighlightLayer";
  92160. /**
  92161. * The neutral color used during the preparation of the glow effect.
  92162. * This is black by default as the blend operation is a blend operation.
  92163. */
  92164. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  92165. /**
  92166. * Stencil value used for glowing meshes.
  92167. */
  92168. HighlightLayer.GlowingMeshStencilReference = 0x02;
  92169. /**
  92170. * Stencil value used for the other meshes in the scene.
  92171. */
  92172. HighlightLayer.NormalMeshStencilReference = 0x01;
  92173. __decorate([
  92174. BABYLON.serialize()
  92175. ], HighlightLayer.prototype, "innerGlow", void 0);
  92176. __decorate([
  92177. BABYLON.serialize()
  92178. ], HighlightLayer.prototype, "outerGlow", void 0);
  92179. __decorate([
  92180. BABYLON.serialize()
  92181. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  92182. __decorate([
  92183. BABYLON.serialize()
  92184. ], HighlightLayer.prototype, "blurVerticalSize", null);
  92185. __decorate([
  92186. BABYLON.serialize("options")
  92187. ], HighlightLayer.prototype, "_options", void 0);
  92188. return HighlightLayer;
  92189. }(BABYLON.EffectLayer));
  92190. BABYLON.HighlightLayer = HighlightLayer;
  92191. })(BABYLON || (BABYLON = {}));
  92192. //# sourceMappingURL=babylon.highlightLayer.js.map
  92193. var BABYLON;
  92194. (function (BABYLON) {
  92195. /**
  92196. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  92197. *
  92198. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  92199. * glowy meshes to your scene.
  92200. *
  92201. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  92202. */
  92203. var GlowLayer = /** @class */ (function (_super) {
  92204. __extends(GlowLayer, _super);
  92205. /**
  92206. * Instantiates a new glow Layer and references it to the scene.
  92207. * @param name The name of the layer
  92208. * @param scene The scene to use the layer in
  92209. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  92210. */
  92211. function GlowLayer(name, scene, options) {
  92212. var _this = _super.call(this, name, scene) || this;
  92213. _this._intensity = 1.0;
  92214. _this._includedOnlyMeshes = [];
  92215. _this._excludedMeshes = [];
  92216. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  92217. // Adapt options
  92218. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  92219. // Initialize the layer
  92220. _this._init({
  92221. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  92222. camera: _this._options.camera,
  92223. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  92224. mainTextureRatio: _this._options.mainTextureRatio
  92225. });
  92226. return _this;
  92227. }
  92228. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  92229. /**
  92230. * Gets the kernel size of the blur.
  92231. */
  92232. get: function () {
  92233. return this._horizontalBlurPostprocess1.kernel;
  92234. },
  92235. /**
  92236. * Sets the kernel size of the blur.
  92237. */
  92238. set: function (value) {
  92239. this._horizontalBlurPostprocess1.kernel = value;
  92240. this._verticalBlurPostprocess1.kernel = value;
  92241. this._horizontalBlurPostprocess2.kernel = value;
  92242. this._verticalBlurPostprocess2.kernel = value;
  92243. },
  92244. enumerable: true,
  92245. configurable: true
  92246. });
  92247. Object.defineProperty(GlowLayer.prototype, "intensity", {
  92248. /**
  92249. * Gets the glow intensity.
  92250. */
  92251. get: function () {
  92252. return this._intensity;
  92253. },
  92254. /**
  92255. * Sets the glow intensity.
  92256. */
  92257. set: function (value) {
  92258. this._intensity = value;
  92259. },
  92260. enumerable: true,
  92261. configurable: true
  92262. });
  92263. /**
  92264. * Get the effect name of the layer.
  92265. * @return The effect name
  92266. */
  92267. GlowLayer.prototype.getEffectName = function () {
  92268. return GlowLayer.EffectName;
  92269. };
  92270. /**
  92271. * Create the merge effect. This is the shader use to blit the information back
  92272. * to the main canvas at the end of the scene rendering.
  92273. */
  92274. GlowLayer.prototype._createMergeEffect = function () {
  92275. // Effect
  92276. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  92277. };
  92278. /**
  92279. * Creates the render target textures and post processes used in the glow layer.
  92280. */
  92281. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  92282. var _this = this;
  92283. var blurTextureWidth = this._mainTextureDesiredSize.width;
  92284. var blurTextureHeight = this._mainTextureDesiredSize.height;
  92285. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  92286. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  92287. var textureType = 0;
  92288. if (this._engine.getCaps().textureHalfFloatRender) {
  92289. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92290. }
  92291. else {
  92292. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  92293. }
  92294. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  92295. width: blurTextureWidth,
  92296. height: blurTextureHeight
  92297. }, this._scene, false, true, textureType);
  92298. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92299. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92300. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92301. this._blurTexture1.renderParticles = false;
  92302. this._blurTexture1.ignoreCameraViewport = true;
  92303. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  92304. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  92305. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  92306. width: blurTextureWidth2,
  92307. height: blurTextureHeight2
  92308. }, this._scene, false, true, textureType);
  92309. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92310. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92311. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92312. this._blurTexture2.renderParticles = false;
  92313. this._blurTexture2.ignoreCameraViewport = true;
  92314. this._textures = [this._blurTexture1, this._blurTexture2];
  92315. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92316. width: blurTextureWidth,
  92317. height: blurTextureHeight
  92318. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92319. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  92320. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  92321. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  92322. effect.setTexture("textureSampler", _this._mainTexture);
  92323. });
  92324. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92325. width: blurTextureWidth,
  92326. height: blurTextureHeight
  92327. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92328. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92329. width: blurTextureWidth2,
  92330. height: blurTextureHeight2
  92331. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92332. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  92333. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  92334. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  92335. effect.setTexture("textureSampler", _this._blurTexture1);
  92336. });
  92337. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92338. width: blurTextureWidth2,
  92339. height: blurTextureHeight2
  92340. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92341. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92342. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  92343. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92344. this._mainTexture.samples = this._options.mainTextureSamples;
  92345. this._mainTexture.onAfterUnbindObservable.add(function () {
  92346. var internalTexture = _this._blurTexture1.getInternalTexture();
  92347. if (internalTexture) {
  92348. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  92349. internalTexture = _this._blurTexture2.getInternalTexture();
  92350. if (internalTexture) {
  92351. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  92352. }
  92353. }
  92354. });
  92355. // Prevent autoClear.
  92356. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  92357. };
  92358. /**
  92359. * Checks for the readiness of the element composing the layer.
  92360. * @param subMesh the mesh to check for
  92361. * @param useInstances specify wether or not to use instances to render the mesh
  92362. * @param emissiveTexture the associated emissive texture used to generate the glow
  92363. * @return true if ready otherwise, false
  92364. */
  92365. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  92366. var material = subMesh.getMaterial();
  92367. var mesh = subMesh.getRenderingMesh();
  92368. if (!material || !mesh) {
  92369. return false;
  92370. }
  92371. var emissiveTexture = material.emissiveTexture;
  92372. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  92373. };
  92374. /**
  92375. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  92376. */
  92377. GlowLayer.prototype.needStencil = function () {
  92378. return false;
  92379. };
  92380. /**
  92381. * Implementation specific of rendering the generating effect on the main canvas.
  92382. * @param effect The effect used to render through
  92383. */
  92384. GlowLayer.prototype._internalRender = function (effect) {
  92385. // Texture
  92386. effect.setTexture("textureSampler", this._blurTexture1);
  92387. effect.setTexture("textureSampler2", this._blurTexture2);
  92388. effect.setFloat("offset", this._intensity);
  92389. // Cache
  92390. var engine = this._engine;
  92391. var previousStencilBuffer = engine.getStencilBuffer();
  92392. // Draw order
  92393. engine.setStencilBuffer(false);
  92394. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92395. // Draw order
  92396. engine.setStencilBuffer(previousStencilBuffer);
  92397. };
  92398. /**
  92399. * Sets the required values for both the emissive texture and and the main color.
  92400. */
  92401. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92402. var textureLevel = 1.0;
  92403. if (this.customEmissiveTextureSelector) {
  92404. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  92405. }
  92406. else {
  92407. if (material) {
  92408. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92409. if (this._emissiveTextureAndColor.texture) {
  92410. textureLevel = this._emissiveTextureAndColor.texture.level;
  92411. }
  92412. }
  92413. else {
  92414. this._emissiveTextureAndColor.texture = null;
  92415. }
  92416. }
  92417. if (this.customEmissiveColorSelector) {
  92418. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  92419. }
  92420. else {
  92421. if (material.emissiveColor) {
  92422. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  92423. }
  92424. else {
  92425. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92426. }
  92427. }
  92428. };
  92429. /**
  92430. * Returns true if the mesh should render, otherwise false.
  92431. * @param mesh The mesh to render
  92432. * @returns true if it should render otherwise false
  92433. */
  92434. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  92435. return this.hasMesh(mesh);
  92436. };
  92437. /**
  92438. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  92439. * @param mesh The mesh to exclude from the glow layer
  92440. */
  92441. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  92442. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  92443. this._excludedMeshes.push(mesh.uniqueId);
  92444. }
  92445. };
  92446. /**
  92447. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  92448. * @param mesh The mesh to remove
  92449. */
  92450. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  92451. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  92452. if (index !== -1) {
  92453. this._excludedMeshes.splice(index, 1);
  92454. }
  92455. };
  92456. /**
  92457. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  92458. * @param mesh The mesh to include in the glow layer
  92459. */
  92460. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  92461. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  92462. this._includedOnlyMeshes.push(mesh.uniqueId);
  92463. }
  92464. };
  92465. /**
  92466. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  92467. * @param mesh The mesh to remove
  92468. */
  92469. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  92470. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  92471. if (index !== -1) {
  92472. this._includedOnlyMeshes.splice(index, 1);
  92473. }
  92474. };
  92475. /**
  92476. * Determine if a given mesh will be used in the glow layer
  92477. * @param mesh The mesh to test
  92478. * @returns true if the mesh will be highlighted by the current glow layer
  92479. */
  92480. GlowLayer.prototype.hasMesh = function (mesh) {
  92481. // Included Mesh
  92482. if (this._includedOnlyMeshes.length) {
  92483. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  92484. }
  92485. ;
  92486. // Excluded Mesh
  92487. if (this._excludedMeshes.length) {
  92488. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  92489. }
  92490. ;
  92491. return true;
  92492. };
  92493. /**
  92494. * Free any resources and references associated to a mesh.
  92495. * Internal use
  92496. * @param mesh The mesh to free.
  92497. */
  92498. GlowLayer.prototype._disposeMesh = function (mesh) {
  92499. this.removeIncludedOnlyMesh(mesh);
  92500. this.removeExcludedMesh(mesh);
  92501. };
  92502. /**
  92503. * Gets the class name of the effect layer
  92504. * @returns the string with the class name of the effect layer
  92505. */
  92506. GlowLayer.prototype.getClassName = function () {
  92507. return "GlowLayer";
  92508. };
  92509. /**
  92510. * Serializes this glow layer
  92511. * @returns a serialized glow layer object
  92512. */
  92513. GlowLayer.prototype.serialize = function () {
  92514. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92515. serializationObject.customType = "BABYLON.GlowLayer";
  92516. var index;
  92517. // Included meshes
  92518. serializationObject.includedMeshes = [];
  92519. if (this._includedOnlyMeshes.length) {
  92520. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  92521. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  92522. if (mesh) {
  92523. serializationObject.includedMeshes.push(mesh.id);
  92524. }
  92525. }
  92526. }
  92527. // Excluded meshes
  92528. serializationObject.excludedMeshes = [];
  92529. if (this._excludedMeshes.length) {
  92530. for (index = 0; index < this._excludedMeshes.length; index++) {
  92531. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  92532. if (mesh) {
  92533. serializationObject.excludedMeshes.push(mesh.id);
  92534. }
  92535. }
  92536. }
  92537. return serializationObject;
  92538. };
  92539. /**
  92540. * Creates a Glow Layer from parsed glow layer data
  92541. * @param parsedGlowLayer defines glow layer data
  92542. * @param scene defines the current scene
  92543. * @param rootUrl defines the root URL containing the glow layer information
  92544. * @returns a parsed Glow Layer
  92545. */
  92546. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  92547. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  92548. var index;
  92549. // Excluded meshes
  92550. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  92551. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  92552. if (mesh) {
  92553. gl.addExcludedMesh(mesh);
  92554. }
  92555. }
  92556. // Included meshes
  92557. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  92558. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  92559. if (mesh) {
  92560. gl.addIncludedOnlyMesh(mesh);
  92561. }
  92562. }
  92563. return gl;
  92564. };
  92565. /**
  92566. * Effect Name of the layer.
  92567. */
  92568. GlowLayer.EffectName = "GlowLayer";
  92569. /**
  92570. * The default blur kernel size used for the glow.
  92571. */
  92572. GlowLayer.DefaultBlurKernelSize = 32;
  92573. /**
  92574. * The default texture size ratio used for the glow.
  92575. */
  92576. GlowLayer.DefaultTextureRatio = 0.5;
  92577. __decorate([
  92578. BABYLON.serialize()
  92579. ], GlowLayer.prototype, "blurKernelSize", null);
  92580. __decorate([
  92581. BABYLON.serialize()
  92582. ], GlowLayer.prototype, "intensity", null);
  92583. __decorate([
  92584. BABYLON.serialize("options")
  92585. ], GlowLayer.prototype, "_options", void 0);
  92586. return GlowLayer;
  92587. }(BABYLON.EffectLayer));
  92588. BABYLON.GlowLayer = GlowLayer;
  92589. })(BABYLON || (BABYLON = {}));
  92590. //# sourceMappingURL=babylon.glowLayer.js.map
  92591. var BABYLON;
  92592. (function (BABYLON) {
  92593. /**
  92594. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  92595. */
  92596. var AssetTaskState;
  92597. (function (AssetTaskState) {
  92598. /**
  92599. * Initialization
  92600. */
  92601. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  92602. /**
  92603. * Running
  92604. */
  92605. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  92606. /**
  92607. * Done
  92608. */
  92609. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  92610. /**
  92611. * Error
  92612. */
  92613. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  92614. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  92615. /**
  92616. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  92617. */
  92618. var AbstractAssetTask = /** @class */ (function () {
  92619. /**
  92620. * Creates a new {BABYLON.AssetsManager}
  92621. * @param name defines the name of the task
  92622. */
  92623. function AbstractAssetTask(
  92624. /**
  92625. * Task name
  92626. */ name) {
  92627. this.name = name;
  92628. this._isCompleted = false;
  92629. this._taskState = AssetTaskState.INIT;
  92630. }
  92631. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  92632. /**
  92633. * Get if the task is completed
  92634. */
  92635. get: function () {
  92636. return this._isCompleted;
  92637. },
  92638. enumerable: true,
  92639. configurable: true
  92640. });
  92641. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  92642. /**
  92643. * Gets the current state of the task
  92644. */
  92645. get: function () {
  92646. return this._taskState;
  92647. },
  92648. enumerable: true,
  92649. configurable: true
  92650. });
  92651. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  92652. /**
  92653. * Gets the current error object (if task is in error)
  92654. */
  92655. get: function () {
  92656. return this._errorObject;
  92657. },
  92658. enumerable: true,
  92659. configurable: true
  92660. });
  92661. /**
  92662. * Internal only
  92663. * @hidden
  92664. */
  92665. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  92666. if (this._errorObject) {
  92667. return;
  92668. }
  92669. this._errorObject = {
  92670. message: message,
  92671. exception: exception
  92672. };
  92673. };
  92674. /**
  92675. * Execute the current task
  92676. * @param scene defines the scene where you want your assets to be loaded
  92677. * @param onSuccess is a callback called when the task is successfully executed
  92678. * @param onError is a callback called if an error occurs
  92679. */
  92680. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  92681. var _this = this;
  92682. this._taskState = AssetTaskState.RUNNING;
  92683. this.runTask(scene, function () {
  92684. _this.onDoneCallback(onSuccess, onError);
  92685. }, function (msg, exception) {
  92686. _this.onErrorCallback(onError, msg, exception);
  92687. });
  92688. };
  92689. /**
  92690. * Execute the current task
  92691. * @param scene defines the scene where you want your assets to be loaded
  92692. * @param onSuccess is a callback called when the task is successfully executed
  92693. * @param onError is a callback called if an error occurs
  92694. */
  92695. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92696. throw new Error("runTask is not implemented");
  92697. };
  92698. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  92699. this._taskState = AssetTaskState.ERROR;
  92700. this._errorObject = {
  92701. message: message,
  92702. exception: exception
  92703. };
  92704. if (this.onError) {
  92705. this.onError(this, message, exception);
  92706. }
  92707. onError();
  92708. };
  92709. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  92710. try {
  92711. this._taskState = AssetTaskState.DONE;
  92712. this._isCompleted = true;
  92713. if (this.onSuccess) {
  92714. this.onSuccess(this);
  92715. }
  92716. onSuccess();
  92717. }
  92718. catch (e) {
  92719. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  92720. }
  92721. };
  92722. return AbstractAssetTask;
  92723. }());
  92724. BABYLON.AbstractAssetTask = AbstractAssetTask;
  92725. /**
  92726. * Class used to share progress information about assets loading
  92727. */
  92728. var AssetsProgressEvent = /** @class */ (function () {
  92729. /**
  92730. * Creates a {BABYLON.AssetsProgressEvent}
  92731. * @param remainingCount defines the number of remaining tasks to process
  92732. * @param totalCount defines the total number of tasks
  92733. * @param task defines the task that was just processed
  92734. */
  92735. function AssetsProgressEvent(remainingCount, totalCount, task) {
  92736. this.remainingCount = remainingCount;
  92737. this.totalCount = totalCount;
  92738. this.task = task;
  92739. }
  92740. return AssetsProgressEvent;
  92741. }());
  92742. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  92743. /**
  92744. * Define a task used by {BABYLON.AssetsManager} to load meshes
  92745. */
  92746. var MeshAssetTask = /** @class */ (function (_super) {
  92747. __extends(MeshAssetTask, _super);
  92748. /**
  92749. * Creates a new {BABYLON.MeshAssetTask}
  92750. * @param name defines the name of the task
  92751. * @param meshesNames defines the list of mesh's names you want to load
  92752. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  92753. * @param sceneFilename defines the filename of the scene to load from
  92754. */
  92755. function MeshAssetTask(
  92756. /**
  92757. * Defines the name of the task
  92758. */
  92759. name,
  92760. /**
  92761. * Defines the list of mesh's names you want to load
  92762. */
  92763. meshesNames,
  92764. /**
  92765. * Defines the root url to use as a base to load your meshes and associated resources
  92766. */
  92767. rootUrl,
  92768. /**
  92769. * Defines the filename of the scene to load from
  92770. */
  92771. sceneFilename) {
  92772. var _this = _super.call(this, name) || this;
  92773. _this.name = name;
  92774. _this.meshesNames = meshesNames;
  92775. _this.rootUrl = rootUrl;
  92776. _this.sceneFilename = sceneFilename;
  92777. return _this;
  92778. }
  92779. /**
  92780. * Execute the current task
  92781. * @param scene defines the scene where you want your assets to be loaded
  92782. * @param onSuccess is a callback called when the task is successfully executed
  92783. * @param onError is a callback called if an error occurs
  92784. */
  92785. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92786. var _this = this;
  92787. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  92788. _this.loadedMeshes = meshes;
  92789. _this.loadedParticleSystems = particleSystems;
  92790. _this.loadedSkeletons = skeletons;
  92791. onSuccess();
  92792. }, null, function (scene, message, exception) {
  92793. onError(message, exception);
  92794. });
  92795. };
  92796. return MeshAssetTask;
  92797. }(AbstractAssetTask));
  92798. BABYLON.MeshAssetTask = MeshAssetTask;
  92799. /**
  92800. * Define a task used by {BABYLON.AssetsManager} to load text content
  92801. */
  92802. var TextFileAssetTask = /** @class */ (function (_super) {
  92803. __extends(TextFileAssetTask, _super);
  92804. /**
  92805. * Creates a new TextFileAssetTask object
  92806. * @param name defines the name of the task
  92807. * @param url defines the location of the file to load
  92808. */
  92809. function TextFileAssetTask(
  92810. /**
  92811. * Defines the name of the task
  92812. */
  92813. name,
  92814. /**
  92815. * Defines the location of the file to load
  92816. */
  92817. url) {
  92818. var _this = _super.call(this, name) || this;
  92819. _this.name = name;
  92820. _this.url = url;
  92821. return _this;
  92822. }
  92823. /**
  92824. * Execute the current task
  92825. * @param scene defines the scene where you want your assets to be loaded
  92826. * @param onSuccess is a callback called when the task is successfully executed
  92827. * @param onError is a callback called if an error occurs
  92828. */
  92829. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92830. var _this = this;
  92831. scene._loadFile(this.url, function (data) {
  92832. _this.text = data;
  92833. onSuccess();
  92834. }, undefined, false, false, function (request, exception) {
  92835. if (request) {
  92836. onError(request.status + " " + request.statusText, exception);
  92837. }
  92838. });
  92839. };
  92840. return TextFileAssetTask;
  92841. }(AbstractAssetTask));
  92842. BABYLON.TextFileAssetTask = TextFileAssetTask;
  92843. /**
  92844. * Define a task used by {BABYLON.AssetsManager} to load binary data
  92845. */
  92846. var BinaryFileAssetTask = /** @class */ (function (_super) {
  92847. __extends(BinaryFileAssetTask, _super);
  92848. /**
  92849. * Creates a new BinaryFileAssetTask object
  92850. * @param name defines the name of the new task
  92851. * @param url defines the location of the file to load
  92852. */
  92853. function BinaryFileAssetTask(
  92854. /**
  92855. * Defines the name of the task
  92856. */
  92857. name,
  92858. /**
  92859. * Defines the location of the file to load
  92860. */
  92861. url) {
  92862. var _this = _super.call(this, name) || this;
  92863. _this.name = name;
  92864. _this.url = url;
  92865. return _this;
  92866. }
  92867. /**
  92868. * Execute the current task
  92869. * @param scene defines the scene where you want your assets to be loaded
  92870. * @param onSuccess is a callback called when the task is successfully executed
  92871. * @param onError is a callback called if an error occurs
  92872. */
  92873. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92874. var _this = this;
  92875. scene._loadFile(this.url, function (data) {
  92876. _this.data = data;
  92877. onSuccess();
  92878. }, undefined, true, true, function (request, exception) {
  92879. if (request) {
  92880. onError(request.status + " " + request.statusText, exception);
  92881. }
  92882. });
  92883. };
  92884. return BinaryFileAssetTask;
  92885. }(AbstractAssetTask));
  92886. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  92887. /**
  92888. * Define a task used by {BABYLON.AssetsManager} to load images
  92889. */
  92890. var ImageAssetTask = /** @class */ (function (_super) {
  92891. __extends(ImageAssetTask, _super);
  92892. /**
  92893. * Creates a new ImageAssetTask
  92894. * @param name defines the name of the task
  92895. * @param url defines the location of the image to load
  92896. */
  92897. function ImageAssetTask(
  92898. /**
  92899. * Defines the name of the task
  92900. */
  92901. name,
  92902. /**
  92903. * Defines the location of the image to load
  92904. */
  92905. url) {
  92906. var _this = _super.call(this, name) || this;
  92907. _this.name = name;
  92908. _this.url = url;
  92909. return _this;
  92910. }
  92911. /**
  92912. * Execute the current task
  92913. * @param scene defines the scene where you want your assets to be loaded
  92914. * @param onSuccess is a callback called when the task is successfully executed
  92915. * @param onError is a callback called if an error occurs
  92916. */
  92917. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92918. var _this = this;
  92919. var img = new Image();
  92920. BABYLON.Tools.SetCorsBehavior(this.url, img);
  92921. img.onload = function () {
  92922. _this.image = img;
  92923. onSuccess();
  92924. };
  92925. img.onerror = function (err) {
  92926. onError("Error loading image", err);
  92927. };
  92928. img.src = this.url;
  92929. };
  92930. return ImageAssetTask;
  92931. }(AbstractAssetTask));
  92932. BABYLON.ImageAssetTask = ImageAssetTask;
  92933. /**
  92934. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  92935. */
  92936. var TextureAssetTask = /** @class */ (function (_super) {
  92937. __extends(TextureAssetTask, _super);
  92938. /**
  92939. * Creates a new TextureAssetTask object
  92940. * @param name defines the name of the task
  92941. * @param url defines the location of the file to load
  92942. * @param noMipmap defines if mipmap should not be generated (default is false)
  92943. * @param invertY defines if texture must be inverted on Y axis (default is false)
  92944. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  92945. */
  92946. function TextureAssetTask(
  92947. /**
  92948. * Defines the name of the task
  92949. */
  92950. name,
  92951. /**
  92952. * Defines the location of the file to load
  92953. */
  92954. url,
  92955. /**
  92956. * Defines if mipmap should not be generated (default is false)
  92957. */
  92958. noMipmap,
  92959. /**
  92960. * Defines if texture must be inverted on Y axis (default is false)
  92961. */
  92962. invertY,
  92963. /**
  92964. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  92965. */
  92966. samplingMode) {
  92967. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  92968. var _this = _super.call(this, name) || this;
  92969. _this.name = name;
  92970. _this.url = url;
  92971. _this.noMipmap = noMipmap;
  92972. _this.invertY = invertY;
  92973. _this.samplingMode = samplingMode;
  92974. return _this;
  92975. }
  92976. /**
  92977. * Execute the current task
  92978. * @param scene defines the scene where you want your assets to be loaded
  92979. * @param onSuccess is a callback called when the task is successfully executed
  92980. * @param onError is a callback called if an error occurs
  92981. */
  92982. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92983. var onload = function () {
  92984. onSuccess();
  92985. };
  92986. var onerror = function (message, exception) {
  92987. onError(message, exception);
  92988. };
  92989. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  92990. };
  92991. return TextureAssetTask;
  92992. }(AbstractAssetTask));
  92993. BABYLON.TextureAssetTask = TextureAssetTask;
  92994. /**
  92995. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  92996. */
  92997. var CubeTextureAssetTask = /** @class */ (function (_super) {
  92998. __extends(CubeTextureAssetTask, _super);
  92999. /**
  93000. * Creates a new CubeTextureAssetTask
  93001. * @param name defines the name of the task
  93002. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93003. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93004. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93005. * @param files defines the explicit list of files (undefined by default)
  93006. */
  93007. function CubeTextureAssetTask(
  93008. /**
  93009. * Defines the name of the task
  93010. */
  93011. name,
  93012. /**
  93013. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93014. */
  93015. url,
  93016. /**
  93017. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93018. */
  93019. extensions,
  93020. /**
  93021. * Defines if mipmaps should not be generated (default is false)
  93022. */
  93023. noMipmap,
  93024. /**
  93025. * Defines the explicit list of files (undefined by default)
  93026. */
  93027. files) {
  93028. var _this = _super.call(this, name) || this;
  93029. _this.name = name;
  93030. _this.url = url;
  93031. _this.extensions = extensions;
  93032. _this.noMipmap = noMipmap;
  93033. _this.files = files;
  93034. return _this;
  93035. }
  93036. /**
  93037. * Execute the current task
  93038. * @param scene defines the scene where you want your assets to be loaded
  93039. * @param onSuccess is a callback called when the task is successfully executed
  93040. * @param onError is a callback called if an error occurs
  93041. */
  93042. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93043. var onload = function () {
  93044. onSuccess();
  93045. };
  93046. var onerror = function (message, exception) {
  93047. onError(message, exception);
  93048. };
  93049. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  93050. };
  93051. return CubeTextureAssetTask;
  93052. }(AbstractAssetTask));
  93053. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  93054. /**
  93055. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  93056. */
  93057. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  93058. __extends(HDRCubeTextureAssetTask, _super);
  93059. /**
  93060. * Creates a new HDRCubeTextureAssetTask object
  93061. * @param name defines the name of the task
  93062. * @param url defines the location of the file to load
  93063. * @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.
  93064. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93065. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93066. * @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)
  93067. * @param reserved Internal use only
  93068. */
  93069. function HDRCubeTextureAssetTask(
  93070. /**
  93071. * Defines the name of the task
  93072. */
  93073. name,
  93074. /**
  93075. * Defines the location of the file to load
  93076. */
  93077. url,
  93078. /**
  93079. * Defines the desired size (the more it increases the longer the generation will be)
  93080. */
  93081. size,
  93082. /**
  93083. * Defines if mipmaps should not be generated (default is false)
  93084. */
  93085. noMipmap,
  93086. /**
  93087. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93088. */
  93089. generateHarmonics,
  93090. /**
  93091. * 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)
  93092. */
  93093. gammaSpace,
  93094. /**
  93095. * Internal Use Only
  93096. */
  93097. reserved) {
  93098. if (noMipmap === void 0) { noMipmap = false; }
  93099. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93100. if (gammaSpace === void 0) { gammaSpace = false; }
  93101. if (reserved === void 0) { reserved = false; }
  93102. var _this = _super.call(this, name) || this;
  93103. _this.name = name;
  93104. _this.url = url;
  93105. _this.size = size;
  93106. _this.noMipmap = noMipmap;
  93107. _this.generateHarmonics = generateHarmonics;
  93108. _this.gammaSpace = gammaSpace;
  93109. _this.reserved = reserved;
  93110. return _this;
  93111. }
  93112. /**
  93113. * Execute the current task
  93114. * @param scene defines the scene where you want your assets to be loaded
  93115. * @param onSuccess is a callback called when the task is successfully executed
  93116. * @param onError is a callback called if an error occurs
  93117. */
  93118. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  93119. var onload = function () {
  93120. onSuccess();
  93121. };
  93122. var onerror = function (message, exception) {
  93123. onError(message, exception);
  93124. };
  93125. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  93126. };
  93127. return HDRCubeTextureAssetTask;
  93128. }(AbstractAssetTask));
  93129. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  93130. /**
  93131. * This class can be used to easily import assets into a scene
  93132. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  93133. */
  93134. var AssetsManager = /** @class */ (function () {
  93135. /**
  93136. * Creates a new AssetsManager
  93137. * @param scene defines the scene to work on
  93138. */
  93139. function AssetsManager(scene) {
  93140. this._isLoading = false;
  93141. this._tasks = new Array();
  93142. this._waitingTasksCount = 0;
  93143. this._totalTasksCount = 0;
  93144. /**
  93145. * Observable called when all tasks are processed
  93146. */
  93147. this.onTaskSuccessObservable = new BABYLON.Observable();
  93148. /**
  93149. * Observable called when a task had an error
  93150. */
  93151. this.onTaskErrorObservable = new BABYLON.Observable();
  93152. /**
  93153. * Observable called when a task is successful
  93154. */
  93155. this.onTasksDoneObservable = new BABYLON.Observable();
  93156. /**
  93157. * Observable called when a task is done (whatever the result is)
  93158. */
  93159. this.onProgressObservable = new BABYLON.Observable();
  93160. /**
  93161. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  93162. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  93163. */
  93164. this.useDefaultLoadingScreen = true;
  93165. this._scene = scene;
  93166. }
  93167. /**
  93168. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  93169. * @param taskName defines the name of the new task
  93170. * @param meshesNames defines the name of meshes to load
  93171. * @param rootUrl defines the root url to use to locate files
  93172. * @param sceneFilename defines the filename of the scene file
  93173. * @returns a new {BABYLON.MeshAssetTask} object
  93174. */
  93175. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  93176. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  93177. this._tasks.push(task);
  93178. return task;
  93179. };
  93180. /**
  93181. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  93182. * @param taskName defines the name of the new task
  93183. * @param url defines the url of the file to load
  93184. * @returns a new {BABYLON.TextFileAssetTask} object
  93185. */
  93186. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  93187. var task = new TextFileAssetTask(taskName, url);
  93188. this._tasks.push(task);
  93189. return task;
  93190. };
  93191. /**
  93192. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  93193. * @param taskName defines the name of the new task
  93194. * @param url defines the url of the file to load
  93195. * @returns a new {BABYLON.BinaryFileAssetTask} object
  93196. */
  93197. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  93198. var task = new BinaryFileAssetTask(taskName, url);
  93199. this._tasks.push(task);
  93200. return task;
  93201. };
  93202. /**
  93203. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  93204. * @param taskName defines the name of the new task
  93205. * @param url defines the url of the file to load
  93206. * @returns a new {BABYLON.ImageAssetTask} object
  93207. */
  93208. AssetsManager.prototype.addImageTask = function (taskName, url) {
  93209. var task = new ImageAssetTask(taskName, url);
  93210. this._tasks.push(task);
  93211. return task;
  93212. };
  93213. /**
  93214. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  93215. * @param taskName defines the name of the new task
  93216. * @param url defines the url of the file to load
  93217. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93218. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  93219. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  93220. * @returns a new {BABYLON.TextureAssetTask} object
  93221. */
  93222. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  93223. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93224. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  93225. this._tasks.push(task);
  93226. return task;
  93227. };
  93228. /**
  93229. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  93230. * @param taskName defines the name of the new task
  93231. * @param url defines the url of the file to load
  93232. * @param extensions defines the extension to use to load the cube map (can be null)
  93233. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93234. * @param files defines the list of files to load (can be null)
  93235. * @returns a new {BABYLON.CubeTextureAssetTask} object
  93236. */
  93237. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  93238. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  93239. this._tasks.push(task);
  93240. return task;
  93241. };
  93242. /**
  93243. *
  93244. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  93245. * @param taskName defines the name of the new task
  93246. * @param url defines the url of the file to load
  93247. * @param size defines the size you want for the cubemap (can be null)
  93248. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93249. * @param generateHarmonics defines if you want to automatically generate (true by default)
  93250. * @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)
  93251. * @param reserved Internal use only
  93252. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  93253. */
  93254. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  93255. if (noMipmap === void 0) { noMipmap = false; }
  93256. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93257. if (gammaSpace === void 0) { gammaSpace = false; }
  93258. if (reserved === void 0) { reserved = false; }
  93259. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  93260. this._tasks.push(task);
  93261. return task;
  93262. };
  93263. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  93264. var _this = this;
  93265. this._waitingTasksCount--;
  93266. try {
  93267. if (task.taskState === AssetTaskState.DONE) {
  93268. // Let's remove successfull tasks
  93269. BABYLON.Tools.SetImmediate(function () {
  93270. var index = _this._tasks.indexOf(task);
  93271. if (index > -1) {
  93272. _this._tasks.splice(index, 1);
  93273. }
  93274. });
  93275. }
  93276. if (this.onProgress) {
  93277. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  93278. }
  93279. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  93280. }
  93281. catch (e) {
  93282. BABYLON.Tools.Error("Error running progress callbacks.");
  93283. console.log(e);
  93284. }
  93285. if (this._waitingTasksCount === 0) {
  93286. try {
  93287. if (this.onFinish) {
  93288. this.onFinish(this._tasks);
  93289. }
  93290. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93291. }
  93292. catch (e) {
  93293. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  93294. console.log(e);
  93295. }
  93296. this._isLoading = false;
  93297. this._scene.getEngine().hideLoadingUI();
  93298. }
  93299. };
  93300. AssetsManager.prototype._runTask = function (task) {
  93301. var _this = this;
  93302. var done = function () {
  93303. try {
  93304. if (_this.onTaskSuccess) {
  93305. _this.onTaskSuccess(task);
  93306. }
  93307. _this.onTaskSuccessObservable.notifyObservers(task);
  93308. _this._decreaseWaitingTasksCount(task);
  93309. }
  93310. catch (e) {
  93311. error("Error executing task success callbacks", e);
  93312. }
  93313. };
  93314. var error = function (message, exception) {
  93315. task._setErrorObject(message, exception);
  93316. if (_this.onTaskError) {
  93317. _this.onTaskError(task);
  93318. }
  93319. _this.onTaskErrorObservable.notifyObservers(task);
  93320. _this._decreaseWaitingTasksCount(task);
  93321. };
  93322. task.run(this._scene, done, error);
  93323. };
  93324. /**
  93325. * Reset the {BABYLON.AssetsManager} and remove all tasks
  93326. * @return the current instance of the {BABYLON.AssetsManager}
  93327. */
  93328. AssetsManager.prototype.reset = function () {
  93329. this._isLoading = false;
  93330. this._tasks = new Array();
  93331. return this;
  93332. };
  93333. /**
  93334. * Start the loading process
  93335. * @return the current instance of the {BABYLON.AssetsManager}
  93336. */
  93337. AssetsManager.prototype.load = function () {
  93338. if (this._isLoading) {
  93339. return this;
  93340. }
  93341. this._isLoading = true;
  93342. this._waitingTasksCount = this._tasks.length;
  93343. this._totalTasksCount = this._tasks.length;
  93344. if (this._waitingTasksCount === 0) {
  93345. this._isLoading = false;
  93346. if (this.onFinish) {
  93347. this.onFinish(this._tasks);
  93348. }
  93349. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93350. return this;
  93351. }
  93352. if (this.useDefaultLoadingScreen) {
  93353. this._scene.getEngine().displayLoadingUI();
  93354. }
  93355. for (var index = 0; index < this._tasks.length; index++) {
  93356. var task = this._tasks[index];
  93357. this._runTask(task);
  93358. }
  93359. return this;
  93360. };
  93361. return AssetsManager;
  93362. }());
  93363. BABYLON.AssetsManager = AssetsManager;
  93364. })(BABYLON || (BABYLON = {}));
  93365. //# sourceMappingURL=babylon.assetsManager.js.map
  93366. var BABYLON;
  93367. (function (BABYLON) {
  93368. var serializedGeometries = [];
  93369. var serializeGeometry = function (geometry, serializationGeometries) {
  93370. if (serializedGeometries[geometry.id]) {
  93371. return;
  93372. }
  93373. if (geometry.doNotSerialize) {
  93374. return;
  93375. }
  93376. if (geometry instanceof BABYLON.BoxGeometry) {
  93377. serializationGeometries.boxes.push(geometry.serialize());
  93378. }
  93379. else if (geometry instanceof BABYLON.SphereGeometry) {
  93380. serializationGeometries.spheres.push(geometry.serialize());
  93381. }
  93382. else if (geometry instanceof BABYLON.CylinderGeometry) {
  93383. serializationGeometries.cylinders.push(geometry.serialize());
  93384. }
  93385. else if (geometry instanceof BABYLON.TorusGeometry) {
  93386. serializationGeometries.toruses.push(geometry.serialize());
  93387. }
  93388. else if (geometry instanceof BABYLON.GroundGeometry) {
  93389. serializationGeometries.grounds.push(geometry.serialize());
  93390. }
  93391. else if (geometry instanceof BABYLON.Plane) {
  93392. serializationGeometries.planes.push(geometry.serialize());
  93393. }
  93394. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  93395. serializationGeometries.torusKnots.push(geometry.serialize());
  93396. }
  93397. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  93398. throw new Error("Unknown primitive type");
  93399. }
  93400. else {
  93401. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  93402. }
  93403. serializedGeometries[geometry.id] = true;
  93404. };
  93405. var serializeMesh = function (mesh, serializationScene) {
  93406. var serializationObject = {};
  93407. // Geometry
  93408. var geometry = mesh._geometry;
  93409. if (geometry) {
  93410. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  93411. // 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
  93412. serializeGeometry(geometry, serializationScene.geometries);
  93413. }
  93414. }
  93415. // Custom
  93416. if (mesh.serialize) {
  93417. mesh.serialize(serializationObject);
  93418. }
  93419. return serializationObject;
  93420. };
  93421. var finalizeSingleMesh = function (mesh, serializationObject) {
  93422. //only works if the mesh is already loaded
  93423. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93424. //serialize material
  93425. if (mesh.material) {
  93426. if (mesh.material instanceof BABYLON.StandardMaterial) {
  93427. serializationObject.materials = serializationObject.materials || [];
  93428. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93429. serializationObject.materials.push(mesh.material.serialize());
  93430. }
  93431. }
  93432. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  93433. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  93434. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93435. serializationObject.multiMaterials.push(mesh.material.serialize());
  93436. }
  93437. }
  93438. }
  93439. //serialize geometry
  93440. var geometry = mesh._geometry;
  93441. if (geometry) {
  93442. if (!serializationObject.geometries) {
  93443. serializationObject.geometries = {};
  93444. serializationObject.geometries.boxes = [];
  93445. serializationObject.geometries.spheres = [];
  93446. serializationObject.geometries.cylinders = [];
  93447. serializationObject.geometries.toruses = [];
  93448. serializationObject.geometries.grounds = [];
  93449. serializationObject.geometries.planes = [];
  93450. serializationObject.geometries.torusKnots = [];
  93451. serializationObject.geometries.vertexData = [];
  93452. }
  93453. serializeGeometry(geometry, serializationObject.geometries);
  93454. }
  93455. // Skeletons
  93456. if (mesh.skeleton) {
  93457. serializationObject.skeletons = serializationObject.skeletons || [];
  93458. serializationObject.skeletons.push(mesh.skeleton.serialize());
  93459. }
  93460. //serialize the actual mesh
  93461. serializationObject.meshes = serializationObject.meshes || [];
  93462. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93463. }
  93464. };
  93465. var SceneSerializer = /** @class */ (function () {
  93466. function SceneSerializer() {
  93467. }
  93468. SceneSerializer.ClearCache = function () {
  93469. serializedGeometries = [];
  93470. };
  93471. SceneSerializer.Serialize = function (scene) {
  93472. var serializationObject = {};
  93473. SceneSerializer.ClearCache();
  93474. // Scene
  93475. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  93476. serializationObject.autoClear = scene.autoClear;
  93477. serializationObject.clearColor = scene.clearColor.asArray();
  93478. serializationObject.ambientColor = scene.ambientColor.asArray();
  93479. serializationObject.gravity = scene.gravity.asArray();
  93480. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  93481. serializationObject.workerCollisions = scene.workerCollisions;
  93482. // Fog
  93483. if (scene.fogMode && scene.fogMode !== 0) {
  93484. serializationObject.fogMode = scene.fogMode;
  93485. serializationObject.fogColor = scene.fogColor.asArray();
  93486. serializationObject.fogStart = scene.fogStart;
  93487. serializationObject.fogEnd = scene.fogEnd;
  93488. serializationObject.fogDensity = scene.fogDensity;
  93489. }
  93490. //Physics
  93491. if (scene.isPhysicsEnabled()) {
  93492. var physicEngine = scene.getPhysicsEngine();
  93493. if (physicEngine) {
  93494. serializationObject.physicsEnabled = true;
  93495. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  93496. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  93497. }
  93498. }
  93499. // Metadata
  93500. if (scene.metadata) {
  93501. serializationObject.metadata = scene.metadata;
  93502. }
  93503. // Morph targets
  93504. serializationObject.morphTargetManagers = [];
  93505. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  93506. var abstractMesh = _a[_i];
  93507. var manager = abstractMesh.morphTargetManager;
  93508. if (manager) {
  93509. serializationObject.morphTargetManagers.push(manager.serialize());
  93510. }
  93511. }
  93512. // Lights
  93513. serializationObject.lights = [];
  93514. var index;
  93515. var light;
  93516. for (index = 0; index < scene.lights.length; index++) {
  93517. light = scene.lights[index];
  93518. if (!light.doNotSerialize) {
  93519. serializationObject.lights.push(light.serialize());
  93520. }
  93521. }
  93522. // Cameras
  93523. serializationObject.cameras = [];
  93524. for (index = 0; index < scene.cameras.length; index++) {
  93525. var camera = scene.cameras[index];
  93526. if (!camera.doNotSerialize) {
  93527. serializationObject.cameras.push(camera.serialize());
  93528. }
  93529. }
  93530. if (scene.activeCamera) {
  93531. serializationObject.activeCameraID = scene.activeCamera.id;
  93532. }
  93533. // Animations
  93534. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  93535. // Materials
  93536. serializationObject.materials = [];
  93537. serializationObject.multiMaterials = [];
  93538. var material;
  93539. for (index = 0; index < scene.materials.length; index++) {
  93540. material = scene.materials[index];
  93541. if (!material.doNotSerialize) {
  93542. serializationObject.materials.push(material.serialize());
  93543. }
  93544. }
  93545. // MultiMaterials
  93546. serializationObject.multiMaterials = [];
  93547. for (index = 0; index < scene.multiMaterials.length; index++) {
  93548. var multiMaterial = scene.multiMaterials[index];
  93549. serializationObject.multiMaterials.push(multiMaterial.serialize());
  93550. }
  93551. // Environment texture
  93552. if (scene.environmentTexture) {
  93553. serializationObject.environmentTexture = scene.environmentTexture.name;
  93554. }
  93555. // Skeletons
  93556. serializationObject.skeletons = [];
  93557. for (index = 0; index < scene.skeletons.length; index++) {
  93558. var skeleton = scene.skeletons[index];
  93559. if (!skeleton.doNotSerialize) {
  93560. serializationObject.skeletons.push(skeleton.serialize());
  93561. }
  93562. }
  93563. // Transform nodes
  93564. serializationObject.transformNodes = [];
  93565. for (index = 0; index < scene.transformNodes.length; index++) {
  93566. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  93567. }
  93568. // Geometries
  93569. serializationObject.geometries = {};
  93570. serializationObject.geometries.boxes = [];
  93571. serializationObject.geometries.spheres = [];
  93572. serializationObject.geometries.cylinders = [];
  93573. serializationObject.geometries.toruses = [];
  93574. serializationObject.geometries.grounds = [];
  93575. serializationObject.geometries.planes = [];
  93576. serializationObject.geometries.torusKnots = [];
  93577. serializationObject.geometries.vertexData = [];
  93578. serializedGeometries = [];
  93579. var geometries = scene.getGeometries();
  93580. for (index = 0; index < geometries.length; index++) {
  93581. var geometry = geometries[index];
  93582. if (geometry.isReady()) {
  93583. serializeGeometry(geometry, serializationObject.geometries);
  93584. }
  93585. }
  93586. // Meshes
  93587. serializationObject.meshes = [];
  93588. for (index = 0; index < scene.meshes.length; index++) {
  93589. var abstractMesh = scene.meshes[index];
  93590. if (abstractMesh instanceof BABYLON.Mesh) {
  93591. var mesh = abstractMesh;
  93592. if (!mesh.doNotSerialize) {
  93593. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93594. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93595. }
  93596. }
  93597. }
  93598. }
  93599. // Particles Systems
  93600. serializationObject.particleSystems = [];
  93601. for (index = 0; index < scene.particleSystems.length; index++) {
  93602. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  93603. }
  93604. // Lens flares
  93605. serializationObject.lensFlareSystems = [];
  93606. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  93607. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  93608. }
  93609. // Shadows
  93610. serializationObject.shadowGenerators = [];
  93611. for (index = 0; index < scene.lights.length; index++) {
  93612. light = scene.lights[index];
  93613. var shadowGenerator = light.getShadowGenerator();
  93614. if (shadowGenerator) {
  93615. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  93616. }
  93617. }
  93618. // Action Manager
  93619. if (scene.actionManager) {
  93620. serializationObject.actions = scene.actionManager.serialize("scene");
  93621. }
  93622. // Audio
  93623. serializationObject.sounds = [];
  93624. for (index = 0; index < scene.soundTracks.length; index++) {
  93625. var soundtrack = scene.soundTracks[index];
  93626. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  93627. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  93628. }
  93629. }
  93630. // Effect layers
  93631. serializationObject.effectLayers = [];
  93632. for (index = 0; index < scene.effectLayers.length; index++) {
  93633. var layer = scene.effectLayers[index];
  93634. if (layer.serialize) {
  93635. serializationObject.effectLayers.push(layer.serialize());
  93636. }
  93637. }
  93638. return serializationObject;
  93639. };
  93640. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  93641. if (withParents === void 0) { withParents = false; }
  93642. if (withChildren === void 0) { withChildren = false; }
  93643. var serializationObject = {};
  93644. SceneSerializer.ClearCache();
  93645. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  93646. if (withParents || withChildren) {
  93647. //deliberate for loop! not for each, appended should be processed as well.
  93648. for (var i = 0; i < toSerialize.length; ++i) {
  93649. if (withChildren) {
  93650. toSerialize[i].getDescendants().forEach(function (node) {
  93651. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  93652. toSerialize.push(node);
  93653. }
  93654. });
  93655. }
  93656. //make sure the array doesn't contain the object already
  93657. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  93658. toSerialize.push(toSerialize[i].parent);
  93659. }
  93660. }
  93661. }
  93662. toSerialize.forEach(function (mesh) {
  93663. finalizeSingleMesh(mesh, serializationObject);
  93664. });
  93665. return serializationObject;
  93666. };
  93667. return SceneSerializer;
  93668. }());
  93669. BABYLON.SceneSerializer = SceneSerializer;
  93670. })(BABYLON || (BABYLON = {}));
  93671. //# sourceMappingURL=babylon.sceneSerializer.js.map
  93672. var BABYLON;
  93673. (function (BABYLON) {
  93674. var ReflectionProbe = /** @class */ (function () {
  93675. function ReflectionProbe(name, size, scene, generateMipMaps) {
  93676. if (generateMipMaps === void 0) { generateMipMaps = true; }
  93677. var _this = this;
  93678. this.name = name;
  93679. this._viewMatrix = BABYLON.Matrix.Identity();
  93680. this._target = BABYLON.Vector3.Zero();
  93681. this._add = BABYLON.Vector3.Zero();
  93682. this._invertYAxis = false;
  93683. this.position = BABYLON.Vector3.Zero();
  93684. this._scene = scene;
  93685. this._scene.reflectionProbes.push(this);
  93686. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  93687. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  93688. switch (faceIndex) {
  93689. case 0:
  93690. _this._add.copyFromFloats(1, 0, 0);
  93691. break;
  93692. case 1:
  93693. _this._add.copyFromFloats(-1, 0, 0);
  93694. break;
  93695. case 2:
  93696. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  93697. break;
  93698. case 3:
  93699. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  93700. break;
  93701. case 4:
  93702. _this._add.copyFromFloats(0, 0, 1);
  93703. break;
  93704. case 5:
  93705. _this._add.copyFromFloats(0, 0, -1);
  93706. break;
  93707. }
  93708. if (_this._attachedMesh) {
  93709. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  93710. }
  93711. _this.position.addToRef(_this._add, _this._target);
  93712. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  93713. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  93714. scene._forcedViewPosition = _this.position;
  93715. });
  93716. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  93717. scene._forcedViewPosition = null;
  93718. scene.updateTransformMatrix(true);
  93719. });
  93720. if (scene.activeCamera) {
  93721. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  93722. }
  93723. }
  93724. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  93725. get: function () {
  93726. return this._renderTargetTexture.samples;
  93727. },
  93728. set: function (value) {
  93729. this._renderTargetTexture.samples = value;
  93730. },
  93731. enumerable: true,
  93732. configurable: true
  93733. });
  93734. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  93735. get: function () {
  93736. return this._renderTargetTexture.refreshRate;
  93737. },
  93738. set: function (value) {
  93739. this._renderTargetTexture.refreshRate = value;
  93740. },
  93741. enumerable: true,
  93742. configurable: true
  93743. });
  93744. ReflectionProbe.prototype.getScene = function () {
  93745. return this._scene;
  93746. };
  93747. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  93748. get: function () {
  93749. return this._renderTargetTexture;
  93750. },
  93751. enumerable: true,
  93752. configurable: true
  93753. });
  93754. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  93755. get: function () {
  93756. return this._renderTargetTexture.renderList;
  93757. },
  93758. enumerable: true,
  93759. configurable: true
  93760. });
  93761. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  93762. this._attachedMesh = mesh;
  93763. };
  93764. /**
  93765. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  93766. *
  93767. * @param renderingGroupId The rendering group id corresponding to its index
  93768. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  93769. */
  93770. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  93771. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  93772. };
  93773. ReflectionProbe.prototype.dispose = function () {
  93774. var index = this._scene.reflectionProbes.indexOf(this);
  93775. if (index !== -1) {
  93776. // Remove from the scene if found
  93777. this._scene.reflectionProbes.splice(index, 1);
  93778. }
  93779. if (this._renderTargetTexture) {
  93780. this._renderTargetTexture.dispose();
  93781. this._renderTargetTexture = null;
  93782. }
  93783. };
  93784. return ReflectionProbe;
  93785. }());
  93786. BABYLON.ReflectionProbe = ReflectionProbe;
  93787. })(BABYLON || (BABYLON = {}));
  93788. //# sourceMappingURL=babylon.reflectionProbe.js.map
  93789. var BABYLON;
  93790. (function (BABYLON) {
  93791. var Layer = /** @class */ (function () {
  93792. function Layer(name, imgUrl, scene, isBackground, color) {
  93793. this.name = name;
  93794. this.scale = new BABYLON.Vector2(1, 1);
  93795. this.offset = new BABYLON.Vector2(0, 0);
  93796. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  93797. this.layerMask = 0x0FFFFFFF;
  93798. this._vertexBuffers = {};
  93799. // Events
  93800. /**
  93801. * An event triggered when the layer is disposed.
  93802. */
  93803. this.onDisposeObservable = new BABYLON.Observable();
  93804. /**
  93805. * An event triggered before rendering the scene
  93806. */
  93807. this.onBeforeRenderObservable = new BABYLON.Observable();
  93808. /**
  93809. * An event triggered after rendering the scene
  93810. */
  93811. this.onAfterRenderObservable = new BABYLON.Observable();
  93812. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  93813. this.isBackground = isBackground === undefined ? true : isBackground;
  93814. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  93815. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  93816. this._scene.layers.push(this);
  93817. var engine = this._scene.getEngine();
  93818. // VBO
  93819. var vertices = [];
  93820. vertices.push(1, 1);
  93821. vertices.push(-1, 1);
  93822. vertices.push(-1, -1);
  93823. vertices.push(1, -1);
  93824. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  93825. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  93826. this._createIndexBuffer();
  93827. // Effects
  93828. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  93829. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  93830. }
  93831. Object.defineProperty(Layer.prototype, "onDispose", {
  93832. set: function (callback) {
  93833. if (this._onDisposeObserver) {
  93834. this.onDisposeObservable.remove(this._onDisposeObserver);
  93835. }
  93836. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  93837. },
  93838. enumerable: true,
  93839. configurable: true
  93840. });
  93841. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  93842. set: function (callback) {
  93843. if (this._onBeforeRenderObserver) {
  93844. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  93845. }
  93846. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  93847. },
  93848. enumerable: true,
  93849. configurable: true
  93850. });
  93851. Object.defineProperty(Layer.prototype, "onAfterRender", {
  93852. set: function (callback) {
  93853. if (this._onAfterRenderObserver) {
  93854. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  93855. }
  93856. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  93857. },
  93858. enumerable: true,
  93859. configurable: true
  93860. });
  93861. Layer.prototype._createIndexBuffer = function () {
  93862. var engine = this._scene.getEngine();
  93863. // Indices
  93864. var indices = [];
  93865. indices.push(0);
  93866. indices.push(1);
  93867. indices.push(2);
  93868. indices.push(0);
  93869. indices.push(2);
  93870. indices.push(3);
  93871. this._indexBuffer = engine.createIndexBuffer(indices);
  93872. };
  93873. Layer.prototype._rebuild = function () {
  93874. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93875. if (vb) {
  93876. vb._rebuild();
  93877. }
  93878. this._createIndexBuffer();
  93879. };
  93880. Layer.prototype.render = function () {
  93881. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  93882. // Check
  93883. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  93884. return;
  93885. var engine = this._scene.getEngine();
  93886. this.onBeforeRenderObservable.notifyObservers(this);
  93887. // Render
  93888. engine.enableEffect(currentEffect);
  93889. engine.setState(false);
  93890. // Texture
  93891. currentEffect.setTexture("textureSampler", this.texture);
  93892. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  93893. // Color
  93894. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  93895. // Scale / offset
  93896. currentEffect.setVector2("offset", this.offset);
  93897. currentEffect.setVector2("scale", this.scale);
  93898. // VBOs
  93899. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  93900. // Draw order
  93901. if (!this.alphaTest) {
  93902. engine.setAlphaMode(this.alphaBlendingMode);
  93903. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93904. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  93905. }
  93906. else {
  93907. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93908. }
  93909. this.onAfterRenderObservable.notifyObservers(this);
  93910. };
  93911. Layer.prototype.dispose = function () {
  93912. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93913. if (vertexBuffer) {
  93914. vertexBuffer.dispose();
  93915. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  93916. }
  93917. if (this._indexBuffer) {
  93918. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  93919. this._indexBuffer = null;
  93920. }
  93921. if (this.texture) {
  93922. this.texture.dispose();
  93923. this.texture = null;
  93924. }
  93925. // Remove from scene
  93926. var index = this._scene.layers.indexOf(this);
  93927. this._scene.layers.splice(index, 1);
  93928. // Callback
  93929. this.onDisposeObservable.notifyObservers(this);
  93930. this.onDisposeObservable.clear();
  93931. this.onAfterRenderObservable.clear();
  93932. this.onBeforeRenderObservable.clear();
  93933. };
  93934. return Layer;
  93935. }());
  93936. BABYLON.Layer = Layer;
  93937. })(BABYLON || (BABYLON = {}));
  93938. //# sourceMappingURL=babylon.layer.js.map
  93939. var BABYLON;
  93940. (function (BABYLON) {
  93941. var TextureTools = /** @class */ (function () {
  93942. function TextureTools() {
  93943. }
  93944. /**
  93945. * Uses the GPU to create a copy texture rescaled at a given size
  93946. * @param texture Texture to copy from
  93947. * @param width Desired width
  93948. * @param height Desired height
  93949. * @return Generated texture
  93950. */
  93951. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  93952. if (useBilinearMode === void 0) { useBilinearMode = true; }
  93953. var scene = texture.getScene();
  93954. var engine = scene.getEngine();
  93955. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  93956. rtt.wrapU = texture.wrapU;
  93957. rtt.wrapV = texture.wrapV;
  93958. rtt.uOffset = texture.uOffset;
  93959. rtt.vOffset = texture.vOffset;
  93960. rtt.uScale = texture.uScale;
  93961. rtt.vScale = texture.vScale;
  93962. rtt.uAng = texture.uAng;
  93963. rtt.vAng = texture.vAng;
  93964. rtt.wAng = texture.wAng;
  93965. rtt.coordinatesIndex = texture.coordinatesIndex;
  93966. rtt.level = texture.level;
  93967. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  93968. rtt._texture.isReady = false;
  93969. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93970. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93971. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  93972. passPostProcess.getEffect().executeWhenCompiled(function () {
  93973. passPostProcess.onApply = function (effect) {
  93974. effect.setTexture("textureSampler", texture);
  93975. };
  93976. var internalTexture = rtt.getInternalTexture();
  93977. if (internalTexture) {
  93978. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  93979. engine.unBindFramebuffer(internalTexture);
  93980. rtt.disposeFramebufferObjects();
  93981. passPostProcess.dispose();
  93982. internalTexture.isReady = true;
  93983. }
  93984. });
  93985. return rtt;
  93986. };
  93987. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  93988. if (!scene._environmentBRDFTexture) {
  93989. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  93990. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93991. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93992. scene._environmentBRDFTexture = texture;
  93993. }
  93994. return scene._environmentBRDFTexture;
  93995. };
  93996. TextureTools._environmentBRDFBase64Texture = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR4Xu19Z7PtTHbW1g3jMMbGmGDAZAMm5xxMLDAU0WSKWOQcCoqccw6eGdtgk4yNbZxnvvAL+Af8Af6AsQl+06ako9X36dXPSi3pnPu+cz/cOntL3S1pq5+w1mrpLs/eud9fvn27rf9evPPwFz+v22S7fGZ/n7/70G79J5/Xv/qzbLP+Pnvvoc/6Tz7jX/15/c62LfeH7fofbpfP3l/ct36Wf+u4+D37+XYb++G26LPsr/zFttnPuh37bm1bt0f7MvtlnOx4uv0H4fty8UUsz77rfn/57u32cgXvDv72eQf0tl0+G38b0Nf9K4Dl704MEfA16KsE8Gw9JgD+DQE8EA0DT2b7GwK4GHnF4a8iguXZt9/vL5/dbisJbEq/uwD5vIK/fbbAv4N9U/8nJIDNCazKvBLBGwdwu62OhajxmQSAx6gqNp5HCg9wPan2nwSNjhLD8ux/3u8vP3y7vbwDAYjtR8AzFyDqLu1Q+YEINnew23rPCYiKb+q/K7o4AVT4tg0t/h4ydJZfkQASQ/d5b9fZ/Z1ENmuPn/cwYCYEELBguKC3nRkCnE0AFOwOKCOAR/sH/L4hgFMpbSWP5dn/uN9ffs7t9mJ5cAHoBLTyszBAFJ/F/xIKdASw5wgaEWDMLySxAk4svf6L+4QAGPiJCziNAPb4f3UZ2dh/m+z7BK4SAPYrxf5FB6ABPgCUAfANAZwKyscc7IEA/vv9/uLzbreXzx9cQCMACAl00m8jAlF7ov6SCMQ8gJsMFFBnCECSg5H6TxJAU3vPAbwhgFfz9AABeOEDBcIbB3AqPzwQwH+731/8sNvt5Ydut5e3B2C/fG9P+jESgGz/RgxG9r9VAwTUUh0goQDafUz+DYnAnSha5l99Z1l/yQVswAZSGIAugNd/9xBgCw9E8aECkHUB22QPHIAVDlQdQAMWAibhBgZAasAVHUAI8Cqg96Tm0bj3VBS9jwd7IIBvuN9ffMHt9vLTbreXy+32QlwAhgMIeuNzKwOqCoB2Aa00KHE+EsIeDuj4H2N+Hf/TfAC6A4nhgQCQDDwiaKDXiq9KgBEJNPArAtCk0AEd2mpAizW3/lYIoANpBPg3BPA+hjs/9eXZV+0E8Bm32wsJA9aEoBCAuAABPiEAC/yDC4gSgRgKRHkAlgsI6v7iEFqJEMgBwb4BGkEfEEDnDlReoAP/SQRgOYIB+IYDMEE/SQBbXoLNr0jhq4qOZc0PHBSf5oKW519xvz//kbfby8+83V68ABfwniIBgwgQ/HoRUMv8w5qAoQqgk4DWQiCw+63eD8k/XAPQgK5s/5a5xzAAqgR6wY9k+ZEMtCOoJABb230hEHMFWQdgAl0Ap/+uc6tKBrrP/n0AuwfiNwTwNKguHHV5/qX3+/M1B/Ddb7cXax7g2e324vaQB3hhkMAW92tHoFb96cVAbimwkgQ0Vv7R+D8iACfuxzKfLvnNlAAjAsBwwP2MwLQAD9sbYJME0AFcg5uBPSAA0x0AobhtcDKDA0j3KYDhk7Hp8uKj9/vzH3C7vfget9uLT9nDgDUZuOYCLBJA8MNKPyGGIftPrL+4gy3eh5p/lwRUYYAs9Fn7tM/E9lvJwCH2DxJ/mPTr4nyyLiDtBgTAGCrgNuPzNuETgN+suEEAFhng9lkCoICMLH7V0isCeEMCxylrefkl9/uzz90J4NNUGLDmAnYXINUBrf5dCCAuQCcCvYVAYPk3G++VAveVfkIAFRLolgbr2F9ifP33pAqAV/fHRF4HcAS7AKlAAEIYFNwITOszs/wMsB6II4BXFZ0QwBsSOEYCDwTw2TsBfPrt9uLlqzCgcwFABI0EVCiANl8Uvq0JWNsi2JPZ/0YKsOiHxftsW4v51ZqAaBWgZf91PsBL/jFHwEqBR1cCiuJ3gAfCmCEA3cf8rmz8AMZHIoA3JDBPAsuHVgL4jNvt+UoCH34ggK0asIYBGArsAB7AD+reQgCl+GwZ8LaNlP3MEEDaSg4ACMGr/+ulwV4JsAEfLH42/vdKgWElAJ4QpBl+LAlKErHwt+oGMgTA2ngE4IUIOH3dGr/hAKT/m/UBdSJYPuVL7vflU26352sScCWAD+0EsCcDVxewKjfmAzAsENVn4EfgdySgnYB81yEAgL4RA8T8mTUASAAYBgylQAkL8K/+zL6rsl8qF6ArAeS7WRGoAB8Sf7isN/VZqTs6jQ5wXlweWfyqpQ8I4I0TmCCAT/3I/b48u92ef9bt9nwNAdZE4FoOFALYXcAGegkDMByAzzQEgJh+cAIs/legH0IA5QTCPADE+7ISkD0TgA/8sBIgLQfOgF/F9kPcr+J8fIYguyCILQRKgV4DNviOzoKqeJS0u4AA3pBAjQSWT//I/b5OmC0MWB3ASgBrGLA+IryvDNxCgRXo+wKhjgwk8bcTwUACsJ09ANRVAALwCxmEoFcrAUsuAJ4M1E8BDuHABAHomJ8RgACrZfQLyT9dBWi2OOEG9NJd/TDQ8HAQuBE97ZhjGKy6o+imnU+4gDckkCeB5cMfud/v6zr9Dz84gOdCAM/3JwQhF9CAD25gBWWz/8wNgMpj3K9Lfy0foMMBVffXyT4r+cceC9bvCcDFP0311QrATPkvWgosYQFLAuoqQEcQuw3v2si25F+M1RkZXLUU+CgBmCBOEsCbvECOBJbP+Oj9fv+u2+3Zp91uz9cy4Kfebs/3ROD6iPD2b10YJCXB+0PyrgsHdtBuRACfBeTN+uM+suJPSEDbfh3/oxPoHgwiC3/06j8Eutj69sAQqj++I0CUfvIpwCEvYCT90O4Pn1XsT5Ve1/+dcp9FBh3woqXBSEJkvjHHEOUPqJPAjUUCeOMGfCJYPvOj9/t7//d2e7YmAlcS2B3A8xcPYcBm/7ULEDIQew+5gS0EIEA31R8Uf6gAoBsgKwBd9ddvBBJAs6XARgLQXQ2o7T8+IETe+9eRACg7rhCMVgCiE8D4O9wOCb2ubOht1/vYd2ubzLlgKbBHEDSnAMfL6durVm8qBPwXWz7rY/f7/X/fbsvL2+3Zqv4QAjzfw4COAMAJbEC3wC8koBJ9lAhgxZ+4hi3Oh/f8dU8EqtV/JhHgWn9cC4CJQZXZp6GAk/1nawMkrrcqAiwPIIA2FwOB2oaAF5UkcX+GADBs0I5gsNbBQqCorJcFJjqWKvhNMjky0Aek7/LZH7vf3/vO2215vruAD91uz/dSYCOAPQzYkoD7vw34sFIQw4LNymNSUKk8Wv0hCYhkoJ74Q6BboO9eDKoWAHXvBiCvAdPZf4nt3QqA924AbfXV8t8uN4Bt2We029WkoErWpSoCSm11TM8AOYA5uRS4RAITIQDDavaYHxCcm5exfM7H7vd3v2N9McDt9uxDD//WKsAG/ue32/M1DEACuO3g1jkBsf57fqCL/7UbIISAio85AAG0VQEYiIC9DJTYfy/+Dx8HlpeDRK8G90IBHQbgWgD2WT8LoOJ7NyeA5JEkAwwxmuqzur5X6y+sBEwDMggrqoBNH7c68Puk/fI9Vwfwvx4e6H724oEA1iSg5AAaAewlweeyLmAnAHQCTfU1CTAH4GyTMt+QDMRFQFEYQB71lXUAOjHYlvTqh4N2xe5yASoh2PpaJUGDBDrLr9cGIDlY1l+vDlQOAQHckYMiA68KMFsGtOy65RCGsMIDT+QqJoD3yUwCy/f+6P3+7koAt50AXrwigM0FrIuEoBrwHMMAUhmQUKAlAwHo7VmAPURo9h/r//ozLv1V7/5v6wGMV4B3rwYPXEBqIZAQwp4TYDE+LQlqtQfw6my/LgsyZaeLg7wVgmDnWQ5AA5ZWCDRx7ECzyn3udgFptFCIgTlyFRMEUCKgA+O/jl2Xz/3o/f7Otz88QvpszQOsLmAPARoBSDVgud02AthdwPZ5BSxUBVr8L3kAVHrvs076KSLQi3/M9QCJ7H/G/rf4n8X41XIgcwHecuBMDgAe+BHA6uQgqnvbF5DB5hwUQM3vQgIWkKOVftH+gAC6cz0RXZ9MjmD5fh/ZCWCd1CsB7CSwhgArAUgIIC5AQoDOCewJwab+CH79WR4C0mQAZT4hEQS9DgfEztNkoEECDfi6FAhZflb6Q1XXqwHDEECpvZX4a0qP1l7bfAS98cQfzQUo9a4mASMC0CsIm6JGK/2i/QkCuFK9PxmIYPm8nQDu795uy3K7LTvwVyJAB7ARwJoAVLkA7QIkJ9A5AQS95Ad2YmgvAJWwQFcBpB38pUuB9wVKbAWgCXwV86Mz2ICKTwUWFgOxMEBicr0eoBwCGBUADfxsDsAiA+zflNay31ZcfnAdAAXgDGkcdAcfZCJYfuCX3O9vf/vtthHAmgcQF7ATwOoAtn9IACsRSDkQ/wqIIUGoXYEQQ/sL5IDJP539776DwodVAGlr5QBgP8sDdApP3gSUXQa8/rZsRaBeHmy+HwDyCI1MUNlZzX9iJSBO9igJGJYCo4RdIqMfJQ4Ztq8C7FXjHuSnQ92XH/yvdwJ4Z68ErOXAlQRW0O9/JRG42v9GBHsuAImAqv+uzDo30C3yAfVHoHeg9xyAp/7wlp+WFCSWv1sOTBb+0EoAZP5DImBrApAUMFHolQG19c+EAkbpjyUEdQ6gm/QEsCzZFxKDlWNwprJVWfBm/1WAvWrcQ0ie7Lz80H91v7/9v263+9sPI2zrAZAEdvXvXMBKBJIIFDcgyUAEvHICg/o7wA/Bvyt35wCc2F9Cg03RvRyAA34N8hD0xsIfXP7bQgDMFSgyYO8GsF4N/hQ5ALak1yUGRQDZZJ5VWXgKEsie8yQuH63b8vn/8oEA3lsJYJ2EQgD73xX4z9bs/74gaHMBQgA7+DsXAJWBBniHCLTtNx2AUnkG/LYNiUCpvX7wp6sIOHF/lwgkNf8UGagwYMgLMBdgLQCyVgOyciCGCs5nz/Jr8EXOQOcQZEbrfjjTU8qaCBseMyx4vxPB8iP+RU8A24Kg9R8Qgaj/av8lDBgcwApQ+QdVgW0bKr3+jsk//AztzBKgtv4K+Kj08rl7JFgt9BnCAIsQcD2AsQAolQj0CAGAqhOFCK5u3cA+84dyIJLCPm6buAgoBa5qDoDF6wzUkZ13iSDKKwTamSKZSf29cuzJUwq7LV/wz18RwH2Nl9dKABLArv6bC5B/+9OBGxmsIIR1AQ3w2gk4RECTfwBulgC0rP96/FYJUOv9SzkAB/xuKTBY/qsTgZ0LILF/s/RW9v81ywEwhbeAwUIH6hRwGp+wEOhqoF49fojqQoPlR/+z+/3t77jd3n3rdru999CzEYAQAYJfXACEAqL8W5lQgA5uoJUK9zxBB3ii9ALiYT2AjvuN72wFILP+XdlP8gLKFeg6f5QM3AC+VlMMZ9ABGuN+VePHWL6tHVD23or3tQPo2iWfBRgShDp0ELcBjmIAbwTWqEzIJvLM6kEDEFcD9erxCzg3my4/9p/e7299x+323lu32+oAtjwAhgE7Cazqv7mAvRLQcgG7A9B5AAwHus87CWBYsIKFfe+eCSBgt2J+7QBQ+VsogOU/9fIPBvLhASEF8AHwlhPQ2wVYFhmo/Wby74QyYLcmQAEbbbue2FcnAb28QTmHQKBwNVCvHv8IESw//h/f7299pyIA7QIE/LsTeIbqL59hPUADvHIBG8jBIWgn0L4rsKMj2Noomz8QgZELsCoAAnh0Caj8lup7ib9tX+ZBoKgUmFkWTGJ8S/UHZa/kAHT+QGaeoeQmMUC/CoAzVYAjYDvSNwPCq8fPnINus/zEfwQE8O7tdt8dwGZjIQQQ9Y9cwAB+RQIC4I4MdvvdLL+O//E7LgLykn6q3Efjf6X8bOUfkoNYcQZ8z/KzBUBYCqT/YQgjBuOBHxPs7JHh7JoAy/IzWz+xEtBKBEYg8fIGw+SeQQQ+CzHZP+oWXWPU/8z9y0/+h/f729/5kAN4791X/6/cpl4SCsDfLRQwHEBLCmJFYH92vssNgBPo7D8qv4CekIHpAjKgx1iffGbKb5UAQwdguIAtz2KsEWj7vIQggNON91lYoIFN2mznYKj9UBmwQgXLLcDstRTdBchEFWAWcLP9MgC9cuzM8aXN8lP//v3+9v/uCUDyAM0FIBFADqAjAsgFiAvYwK3/MfAL8InSd/Yfy37Qpyv3OSTgxf8C5vZXPfF3aB2AA3hJGg5LghMOgCUBo8SgEAyC3Irvh5xAwhW0cT1iQBKYWds/QQLdeVUQcrEjeGoiWH7633sggHfWJOAaAkglYL/wLQyQf3tYsCp9CwmgFIgOgIJ/JwMdBuB3cQTDX4z9wR2whN+WE9idh67761p/F/8bpb8O/OotQCsJDhZfji0qT9p0LsCI83X9H8E9KH8iCSiTrQO29bwAAbvlCipPAw4T/oRKQAVElbaMJ472t7jnqnEjrlt+1t+539/6P4oAxLquawIkF7Bb/40M9hAAHcD2GVzABmBYKSgxfyMGAbROCipl1w6gs/8ZF0Cy/UIOOr7vHAIu9iHP/2v77yX9ROUt29+AHVUCnDJgtvSn8wXsnQGzIUAW3F27qFS4z2CrD07wCogqbR8LtGecUwR4vX/5OX/7FQFsOYC9FCiToBGAEAH83ZwA5AM06BspiPKrNQIt/kcg69iffBegNqVXb/wdQgIMC0DltUuQ+L+Bmz0OrNTdK/91+4JVf15SEPMCYRkwEfc3stBxurMS0AoTMKRocaV8cKw6jpcFsdUn2/8qRT8buGeP55HC8vP+5v3+1v99cADvvfNQBZB4dO24Kv5GAntSUOz/+n1wAis4wAnoMAC/N9svSUKsBABgmwPAbQTwWzsW/2vAI6j14h+1CEjnBYZFQWSxj+sEVFyPjgBBrhf+aOtPY39vRaBVJlQ2vyOGIATQsb6etBguDMSQyAF4IMhUAmZANNNnUNSqBDvtzzif6HSWL/wbuwN4eycA4gDEBQgRYPzfSGC3/BYBdOCHxKBHBAJoAbdWfIz1I9XXsf5g9y0yAJB7iUDPCaC6e2EA2ngMGyIHwAgBldncf4ID0EDXVp1NYmbnrclOtyfDhiPOoCO4CEXB/rOBfOZ4yy/8a7sDAALY1gKAfWMEgOovoNdk0IArKr+7gwH02gWQ2L4t/sEEoLL2IQnoFX96HYC4CIz/jcSgAJSVAtu2RPZ/SPRBHkC7AkYEqceC2fqBfdKaCcHAAeAkpKVBCANcElBVgBQRTC4HngHOTJ+rQo2jhEbP6xf/VU4AmBza7L+EAZgLgGSgxP8dGQDwmQOQbS2xp6oEWAnQn1seIEMCJO4fsv8Q2w/JQU0IJMvPiCCT/NPuQP/noJ0rAFBa23VSr1N/vQhIgxzzB9odMMIAkGvFZPF6JkyIlJeFFl6IcRYYX0ciOOOcll/6l+/3t/7fngPYy4BSCmyT0SGAlgvY4/+BAET10fZjUhAWCg2AV8nBEPQ6D6DJgSUAoQ/G+Dr+T9l/pfg0HxAs/e3WBUhbsihIgHKkHGiGCQHYO/UHomDgdd0BcRkZlYtyAFlgZNtlzqkSJcwc1xr/6FjLL/tLPQG8t+YA3tuXBKPiqISgAB//bjZdkoNE/Rs5EAIYXIAKCwYHYJADlvhalp8RgS4PogNwFN8jgo1A2LoALxRw1gA09TbCAjckQHBZlQEFwEoS0Iv1S3mAYFGPlwOIJn+0v+ocPohEsHzRX9gJYM0BvPvwTyoB2gGsP6iEAowANsBJWAAVgRYeAPCb/WdkAKEAttNJwRbzM+UPQI8K36k9Kf3RagBTe2vhj3o8uAFXLxUGxTdXBrK1AIltTZ2JzUe7Lp/Ralvxvrb5kcWP9nv2fwBzIRF4FRFkx/XcwRljHCGm5Vf++fv9re+63d4xCABVRhOAJoOtRCguQKoCmghwv7L/mBPQwB/KfMQhCEF0ym8RAUkIToUAxrP/gxOwSoDGmn9WCjTzASw3kHQA5poA7Q4g3n+MEMAChiadiopXwHZV26usvB43e/7Lr/pznADakmBdDcB8AFj+5ggcF4AhgAlwwyUM6m+pPgF8U3BS6jOdAAkJ3HUAO5C7ZKBT99/IVDsGhwyY3e8qNfhCERXDa5BrlW/ftaoqe265Ar0U+PIQQCUzqwqYBYfnSK4AcuW8sjmHaMzl1/zZnQDeud3eXRcCrfH/ngNYbyxzAKL8nQNAMiC5gI0gBNz42XIBAnAkBACwqDyWByPlp2BPWP7WD0Crs/5ewq+1JaBnWX8rEajbDiVAlbNpwHRyAJ4D6EqECQcQWfxo/0wI4E3wcPJnUbSLXqH5A26qHaD9kb7ssKaj+nV/ZiSALRG4rwhsJLBfUKt/k3yAJMGwEtCFBGD/PTIY4n6d8ANyaEk/Q/nPUv8h+WeRgXYCVgIwSwbK3osKi4PonEGUC2C2Pngc2LL73Xanlj9bBTg7BIgAFe2vuoxZS14B7wy/DCT8xX/qfn/rrYccwLtrElA7AJkgkrDSJUHJfO/Z/wZ4Kx8g4IXyYKfm0i9QfkoSJK5HghALr51Ce2Jwv0ad9BvAj1WCidKfZf1x3UDnvPQ90HYf7o1WfSQMGbOpU1D3H6oCynpjPE7VfSccpoalMEHNdAxFKkDLgDzTRo5ZaXukz1E34f1Gy2/8kzEB6MUlsjCoCwWMEAAdgOcGTECrnECn+JYTgPyABn0U82vwt7hfJft0rK9DAlHooTSolH94GxBUAnTSL/reAbz6UBADt344SDkIJBIT5E62HgnEAwgFmjq3ChFkAJUFd7Zd9fwsdZ89nnX85Tf/8Z0A1hwAOgDJAxBbuU1usboYCoiCKvWX+L/lAUDlNUG0bD8Bt7dviP9Vf0v9LbV3XQCz/3qbZf2d0h8D+JAPYDb/RAfArL1l92W7Z/OjEICpOZvkw7bES0EisET7M0RxRNkzx78qJGj37rf+MUUA+zoAnQjs1gTAhJNyFy4X7kBtkYHKB0ifDMgrLiADfJMESGa/Cwe0/a+CHsmA5QQ8N6ByAzJZh1IhEobOAegsvwaVDhEKDkCre0cielYbau4SQfIZggyIM0DMtMkc6ywnMHMsduzlt/+R+/2tt2+3d8QBiAtQSUBaEVDxPyYB22cEuiYDQgJtLUFk7539ke1vgAeAR05gC3ekbAclwuaEjEVA3XoAAnLpT6sBCuStrUrIpqsBHhkwcBOVTecFJAteCAFSyk/GzapwBOJofwV0mbEQkNX2p/X9HX9IEcB7eyLw3q8IlPgSbV/LBThEIMreQJkhAeYOIsDrsELV8VmIgHX9ITGo1L+BnxGB5wQY6IvKLzZZCKD7nsj8m+sADjoAVHk9ga19tF1CzSk5GO8T9MCUAdpZbSqEUW17lpNYfucfvN/fBgfwLlQBcEnwdkA9cdGiCjCgGrCpZhACDMSA6wL28dewgKl6GzuI963EXwtf1Nr/wQ0YMb+bCJwAPgKc5gPIPeiImeUC4B5J2zbZnGXBQjI4Mdk2HFNPYqv9MNlJCJByAzPPEezIiUAe7a8ANjPWGYpePc52Db/799/vb7/zKgQQAnhvDwH0cwFWLqBluwkRYJ7AqgoMTiHjApTqR9ZfbLxbCbCUX1wOKQGiO8ASn7XdKgMimL2SoG4nkxGVnqk+OoeBDHR4AN87EmCWnlULBGiBuiNJMFC5RJB8HsACRgYwZ7WpEEY2pNEuYOoYv/f37Q7g3dvtnT3+39YC6BBAv3IK1wVA9p8SAYC5gRDBqz53QDasvag/dQboGMCy0zBA7e/CgoTyszX/VeA35QeH1YGc2Hwr2YchGn5mJNGVd8FdoEOIHEBo9VkeQc3cqFJgEkPhxSBHwoIMCVTAlx1vlggq4y+/7/fe72+tDuDdV2XARgD7isDtd95BpZWjKRUov4Acwa6BT5OEsEjICg1aBUAl8DpwA2kgQeCYbHsjL0zygfKbll9XC5xk3zYGgM1yA0IKERGgI2PJQJ20M13CAQfgWv1kEjBj+Yc2zlqAGdWPgBPtrwI2O16FXMrn8Ad+z04AaxVgTwDiasAtBNgnrK4E6HBgSApichCBBHkBCnQNbmb1iTPoSEXlDXCfTv6x0EAA2OUDtCPA70bMT6sAXjVAlf4sIhieC8BYXy0CYk5gIPKCA8CJGzoAI5QYJqoRzx8NAZ6KCLLgzra7igSWP/i79hzA6gCAAMQFrBMNSUCrFypUm+x78k/cQRffY45AqatOGDJy0CDHkh5dDERielFhWvrTIYHO+icy/jK+qe6sCkCAH70erLsXylXMWv5GFowQrLyACISU6HZ0W+RALX0Qz2ug4NgYUWScRNQ+q6IZ8GbaVMCdHS99jX/4dwIBCAmsoNd5AHAB1sRDArByAV1YgLkBnfRDF6AtPbP4LNY32lkOgMX/tPynSKFzC466Y2JP+mT+mk8BOiVAVP2MA9COgH4nQGcgHxyCAe5uMicqARTcJ+QBIlB5+6O+V4E7c9wMCSx/9HfkCEDyAMPDJiQZ2AABqtZUVwG7s+ZWMlCDO/F9iPFZso9l/IkDaMRgxPqe4g8JQa30yg14pdaM7TddgWHxXcUPVgLqvnqyWw6AqrlT0jPV33AekYJb4IlAdfX+6LwR0BVi8Yhg+WO//X5/e68AyLMAawlwCAEwF2BkpTfgqwlu5QU6G45KrdYNsNi9qwAQMgjBnyEDI77XYGcxfjXut1wAhlfSptsGoNHJPab6XkLwTAeAk1MIidp+mJlRJYCqPxCABwizr0aUDl3I/ogEMsDMjJEZp0oYjECWP/HbSA4ACEDWAbA8gJ6MjADWbYP6i5LqvyRROBBABHgjXEAV14k963s7d0koOkm/s+J+FiaERADqbjkAHKNNrsRCoE7lmYsQ0HjlPm+dgMzKRLmQkkgyBJhR/SPWPwPyTJuriWD5U78FHMB7eyJQ5QDaYiBhXL0mgGWumRNQAO/KbieTASMOL8bvVgUSq2/lAvAaOvDiwiEjs6/BThdZ6bUBJNvfuQN0Z+pzVzI09nXqrT3UMRMAACAASURBVJcKg+J6xKAnLao7Tvruc6ZcyBS6EDpUXUIEvgyAz2oTnQuqe+aYzT386d98v69rALZ1AEIAazVgz/4zBzC8aorlAdS2rkIgC4e8v2TxkOsGMLeA45I6vgZ7ygFg4g8JQhOdl+FPZv+ZnRey0CQhE4PtH1TfCBmkXQd+S+1ZXkCTiQZq0gG4sb6qMHSAKFYQHpsIMoDMtKla/syYy5/9Tb0DWGP/7R8QgOUA2NtnzEw3LhRS6hjlA9CK6/gfS4XU5rOk427p9bg02cfATtS9CwGcSsB6/taTf9Zvx0ItvQ2JgH7WgEYyMMA+5AwmHMBMDsAjAhrPTz5M9H4mggy4M65g+XO/YSeAXf1lLYAsBca/24D7MwKdakBIYOUBxKYyJ0BDAeIOTOW2QI75AgVkXNVH7b+VBFTgDisAQda/gd5LrCrlZpa/WXJrEVBk+cGxNWAkqwDMQWiFNq2/zNKgDOi6A2NFICULRAV8rrSN7HgEzmh/NH4G2MZlDi8qXf78Fz8QgNj/thjIcADtvw9HNcgQwGxIwPIGLHTQVj8BfszWmzkAlZsQwFrlPbcCYOUCjBwKKwl6pUBRWyFhukxY7LmO7414X8f61BVY4YLY9iDBhy6BTX6LPJCoPHtcAXelbQRUD+gZEojGZyCvjrv8hV/fOwArBGBLgnFpcGdJYUJ0gNknxLDNCwm8xKEV6xtqPwt4DWpm92kIQICN7bSNF2Xv/pLfUgNd5wxoCEAA34GbqL0VAmhSuMIBuIqv8wGJRUQWmCzAfNIQwV/8tff7O+9BEhBKgEMiUIUAXjLQinMbAAAcCIruFWMVgBPFX28iLhW2Yvzu+JCo06A21wAQm69XRVJwk+RpaiEQCxeQKEDlaWhgtEWQWEqvt7vhwoQDKAFfjR+5hytdgjf20X1HLH/kIpa//GtUCLATgE4CogOQz628IwzslKx0gosuG1bWnuUGotJhyzUYYUIjBSsnoJKVXZnPCAeYo3EBH1UDDIA38CniiBR/CA1I1r5VEQBUg/1XVt8jjG7iWZUD5WEz5UIK8sRagIhYquQQgfqI/a/aeBYKZMOD5a/86r0MCGsApAqQcQDbgTQBMNuqJ70GE/nuOgMSGjDFj7ZZhNABnxBTIxon459Vfa9yYpUEEfRU5RXounEUkJEgGJlEYNb9O2IQ16hsO07y9nk2ETjzJKG4JIKUSlgQKqyDzgzQM22ic/AcxPLXflXSAew30no8eDsJvBGWyhmJsKojQOAOi3R0yRFtPcvuqxo/tf7qeryYv2T/mZqT0IARgfzmG9Eg6erP8Jvr+4Tk4Sk6IwnWfgA/IxsCPhmfKWuk3ugcqENIgLwC+hl1j4Ac7c+CPDNOd4/++q/ccwCRA1iFHkqAtBrA3ICh/J46Yp7AjM+DHIK27t1aA0YIbKGPIisrw59NAOqSH/0NEKyMCBS4qwnAtNpnk4JGnN8pfKYKoIgiA2R2DEYglW1XE8FZQI6AHu1vv8nf+BUPBNDKgFYOgDkAsHdmQhAnkhP74kNDg72OwgMP0CRuN90GW+CTdCwWoVluQKv3EAYQ1cZjuOpv9JXJNyT49KIgliMwlByVu7kJUFwvPBjcQuaxYSuUOBAGZMjGIxEP1BEQn3z/3/oi4gA0CQD4uxAACMBLCKLNjFSPJd3Q7rtJOWu1oZNcHMgmE+8H5T3P3Xj7OlCzCgEeN+sEVDs8Rpu4Ol9ggd1ScuYWkAQIsDv1lrYqB+BZ/2FfsBqQAe3sbZG6Xwn2aGzr3Ja//cuJA8CnAXfr314SajgBkwBwAs6EAwmwWWFChThY0s8iI297B3DDPYRtCLi3Psb2AdRAHrKvqb9BCEyNtaKXS4OkoqAnomXjKUEo9e/GSjqAs0HvAS8C5WzfaNwKES1/95cZDmAlAbIacPudIRcgi4H0oqBuUirgU6WDSVtJsHnJw8gtZNyGWeJLEJNn61vZzYjzo/3dQ0Ea1DgmUXMWAqTAbil9UOaLynttQj+iAzibCCLQRfstUM+ShJiqqP/y937p7gDuex5gBz5bByD23woDMA9ACeCAG8jkCLTis+8ZUhjCAisZOKvwySw/OoWONFWMrmv4ZsWAqX+wrXMGbLkwnMvgIowEIWuHTsV1CTKz978WeViA88IKDzRnA/Ts8TyCcUng7/+SngC2twFZJLBPljIB4IQ1wgA9waPM+rCfJApN9Tae1beOGZ1LO06CEKj7UbF9A7CVB7AShIa9R3Uf1gOwhF9V6S1iEEQFDqFN3my14IJEYNYRTANNERd+PZMMIsXXp7H8g198v68VgHf2uP9dBX5xAtvbgaUUqEqCg/1HKweAlx9vsLeGIlqxchWojCyqY1RCgXK5jxGHofIsD9B+V92nSAgIxCEkgLEGBU8mAaO4PgoVmEJbOQQG1CzIs+08Msg6kAwRzJBOlgiWf/SLRgewksCq8l0YAKBveQAgBGb/t4vDhJQmAwf4a9dQeZPWnJbiHMfgOYeNlAKlx3BFOxs3L6B+LySS8EUg6rzwuEgQ3luBGugDqx/lCzyCGPbtCBBi05M9Io2OFB4hEXgmGLMgzZDEjIvYruUf/0I7BGgkAJWAbY46SUArGThMyAIZVADH2ppEkiCBir2n5xmpu5ME1I5pUH+LYEnFICKEDpiFEADPSSu0JhQX/MphTBFBIYnI3MRjgLviLs48H9OR/JNf4IcAK9bxPwoV9TerAXgj4T0BOJk9MhAQDZOfACUCNgIy0zbTJpPZpyGAQwTiKug7AYkr0L+N991Vf00gpGyHINbK3yZVMQQwVT2xEMh1BEZ/Nvk1EKsKmgXyGeOeTQQdEf/TL3wggNX2b/H//jqwLRGo1gC0HMCeD9AlQPw+WDqZJEZIoCdaNY6OgOmFAVq5u7ae3Y9AHam7sd8kApUsZHaekclAvrv86eoBcwkZkFvrA1hf1wU4Cu4Btu1T/c8G/hWgrxDEmSFDc0D//OdDCEAqADoPIMnA7a8wrv6LpSEFfJlkoQtAdfKShEmAWlUDN7xgOYYE6DPuBY+Lv0W0HRXdK/cN2X6l0jqcsICubbx2AVeFAK7Sy+zV1YDiasAjgH6MvqZth+vXH6sksfyLn/eKAFaw6yoA5gEE9FYScDsZZfsR8CwhSJNb2Tq5UVLsQO0lE5Pk4bqRiBDU/oEcHFVn9X1T4dFZ6TKhYfWZcltqbm6HsZm6D07QKuGRcqQGgEUKSF5N2QySYPutbZkw4SmJwCIIJIXIYSz/8uf2BEDXAWAosN/w7gUhAHwhge7GY2wGBKFtf5oMGKgcl1Cx/wKwKKQY2hWB3oHbqver7ab6J8t/2L9VbaR6sM8auk4gArlRNbBchQnSaBw5RyV7lRCAgSYCerS/otRZwqiMmSECc7x/9XNUDkCvAyB5AAwDtrlBQgG8KegCOsvolQgrgPKcQKTQSReBhOCquBP3a8LTToXF/vpY8ls2J6AdBFH/rNJfov4YDoL6UzVP5gDc8MBJBFbBnwHrWW08EEcqrvhw+5oNBZZ//bMLBCDqb7kAcAJtUQeyOuQDcGIPnzFeJQClSbJqngBULW3xIzKpkBYe3wGxkISn/u5zASwccLbh5NHhht43ELsFcGeFXwfmA1UAdBsZ9YxU/ej+zDkwJ+RtO5Mkmhh9yc+637cKwJ79lxyAlP/kKcC1IqBzAJgL0K4AQwC0m7hgyAsBrAVEaL0HJU6SQKeiyT6dWictOwsTsqW+9ttosAax/pA3AKJBEqEhQLX+T+J2PG9GEIxEPPC6ag/SNzhOtm/fZo3JABYpfLT/KBFU+leUvxHNR37mSAAC/lYBUDkA76EgIYWOAHASKnXHm4/hwaB8pIxIV8oFFpxlziNws/0diSgF91bwuQQmE7QQ+2fUvwO+pf7KkXRA9db6W6QB1+KCHu1qMgTQE70DoTOG24/Y5qMuIEMOFYBXQ4FM++WjP2MnAFUClGTg5gCEAMhy4M4F7JNou/eZ0qBWELD7qO6D0uNkZXmEwKqb4HXI4wzAa8ejLTYSjb5mfXz8jgCvlP86YrhC/ZH4lfpSFU4SgAfMo88TZFxAlRgyY1aI4Iy2zQF87KfbBLCVAAP199YCaBJAV9AlnAxX0NqwnIBSrHSSziAPa/VeJt/ACMp0AY6l1+CNvofqb6h6NikoJMMUHN2apayZNt3YxRwAPa6Tb2iTXj4cVP2MwkdkUQFz5njsGt1tX/rTHghArwHY7P++DBhdwDanYCWgzgPIfh2TtfUB+6QcJhcBedfGUXoGwAaOyXhdKy4rC1rxPAtlymqfjP0x5h6ArVSdARJdiQa6BWC8t3h8RhQ616AnY+cEigRQdREWUZ1NDBnFz4I5Y+OroMf2y5f9VE4ACH50AS4B7OD28gDtxyEVgW6yOIQwWGlg/Uz8bQLXcBoa/AM56Dq8FcMbCTyx/o3ISF3fsvaMWPRv7JLEPht08nC4TyTDb5UNI1VnwO3coaHQFPBKxa0QwAO/G1LAucwA+2oHkDkny2Vs27/8pygCANUXF9D+h2CdC1CA334rcQf7Z7yxsp8qiFpBOKhPQAiW6jIlN9UdzllAKQBjdtxT9eF8HJLQ5xNae6Lska1nSu+pfyMjb3GOlxwEYrHANwA6sO/abdBxyRiPAf4ZoGf6WOA9y0Es/+YnAwHs4JfsP4v/JSEoTgD/is1veYFZEsB+xAp7gDEX0yRU2asQaHX2wD8QjEEsCDKt0pZqM2LpSqaiiNpteCW7mQSgukc4UTWxsH0Z8EaKT/erRGIW/E/pAo6AOdt35+Pxvwf/t0gA8BKQFfzZMiDmAYakoJ4oUB2gE4UtHDLiYQSa9bnsDEhJj4HfdBYHF/V4Vn8gvh3sh9Rfk60ot7c9Uf+Xc80AkDnCNGng+RrnzCa/RS6Z8zXBJDv0ORnf9bHY96Pbov7LV/ykMQfQrQMgVQABvP67//60BKgXA7UTU9Z/mDgk+TeAndjrBtpCBcEF9Wz23on7j1p9TW74mzaH4jgC/Vtri20uDdakzvIDbTL0y1I9Gx+V8CJHgNeTBfIMEXhjz5LDU5HB8pU/ccwByBOAXQ6AxP9sQVBL5EJGF8uByPYDCehJE1UGAuB7JKD3MadA22iFx9DCiPPpeZAFOZWyH46Jk2cDPiZFRX1IvI7XrMdg2fsOvCRsYGMM25QadgC8KAeQIg5BblAajOL26v5Z4DPrb6m95wKWf/cTxhwAPgJskQAu/aUhAIB5+22J9aelQa0uOuFFQoRBCY2Soc4PNBDBMQVAGJ50amqVI8kYOH4F3FTZsyU9EvuLMs4q/NBP3SNT1Y2FPQyQcs0RYYT7JxYTZQgiAmoE/Ki/8E80DgO+RQYe8Nvx/v2P3wng9updALgAyEoEYrY/ejS4katyBegG2OfOEqpSX7s4K0QohgVUpSft+5VgR7BFsb/nEkxScByD/s31pB2IIOMSIETRE9YLF0wiOGMtwcUu4EoyyIAe79uyEsDwIhAsBSrrT6sAuyJ0i4KU6p9CAkpl9boBNuHT7iCw9vThJBJfe8erKrt2IZZjoWSIcTkLCTwVt6oC6nojwLKYvuoWIsUf1DsZRljn7m3PAPcMBY/GqIK8YU/IHTYs/+HHKQLYAd+tBCQkMIQA7L0AQAxo8bbjI1MXPiOIqMJNOgIEly4HmvsUIaUA7oQ0tD/LuBsAzTqC7XosUnAy/MwBZADtKTl1fjhB2aT19j9RCHAGOWTGyII/Gyos//HHAgEo5c8kAbv4X6m+lRDEmy73EtViSEA5pcFOIVTSMHIEAgTLVuvVceXVeFWwO3F+ByIW5zuxv1ZRRqL6d2TK64E1Y/9dIiDWfVB3veqPEcEThAARcDNgPKtNdC6Dw/lPP+Z+fxcWAOHbgM2FQKDsQ/wP+7TSo+qzsiAqk1apLmGoVUor4kTpcCCDALzZen1EQpbNp+QEjgNdiZWxN8t4pCKQUXeLOChZOFacEoFxTmzsYRIjEZwQAnjjRwCL7Hu0PxofLnVc1IM7gzxGE96vWgkAHwUWF8AWAuGDQOyhIAQ/KwPu+9t5KmVvJwXtMHSgE9BQfU0g7oMy2g4byb9ZMFtkwUCMhNDtJ2VDDVoNLBoSEBLpQBYB18kPpElkv9HM1XRzwFB85gzw2BaArX4uoRRAFYG7up+RQYYgKm5i+aof/RACiPK39wAAEbB3ArSq3v4Bl//qpcAa8Nt3QhAM7N0FE7DTSWc4goEUAAwm8Ky1CNYCG69syWr/BJBWLkArvWflL1H/iDwE2I6dH0hKJkeyYtCRFYCThSdZYLuEwo6hCGwGlE9FBsNx//OP2gkAwwBJBBoVgK4SsE8KyQWwuJ8RAoIdCQJvpMXqVnlQA3z4TpRdjsHA1IEo6hss7JFzQQDQYwaE0AHAUmMrSWgAmJKomuRH7D8DmOVWGMAjgHb7T8oBeORR2XcFOcyMyfps2776C/ocwPr7df8rkEMC23xS/0uQLgVm3IBOAHYni1ldneHVcSMJKdbJEYYOQU7BDR+M8VMZeQZUY1tHVNYxlQJnQgJNKNbk9tzGAFovx0CWDXurDkPF1+MVcgBZhzDbbgaoVWdQsftNaIHcNwLQIYCQgCh9SwaC2jfgQ/lPg92qAnQnokIB6gCUcrlVAqNsZqqco+xMtTM2/FTwVxyBofAsvGGgNe25UxqskgxV+ETIkCaCAgFEzkLmqdXuqZ1ARBam6gMAl6/5kSoEUPYfwa/fBNSeBQBi2MZW7wRox8skBgnYTUfgKLeA11O4KDk3gJ0pWzI00BOYxuhOeU9fhwXWqdg/Io7MfuJKKNhBfRrAJisAFJgH1wF4oPYAF4HxyP6oLwN6xhls/f7Lj7jf5dHf9hdeBNoRgJH5L4UB+2TSpBDmBADsCG5U9izYq+Sg25uKqqsJhnJ64JdrcC13Mfan14tAdDL76MhM0qmOFdh2fRxGJBZQoycKI7BkQZ5tFx0v2h+BPw30BrhXH7bweCOA/eWf+kUgFvjxKcChGqAAbuYADCLQ4N5O14j9I/DjftcGe1UDpn7Ogh2LhCrHfyzw098Hwews/aVkkMzkD8qd7JciggNJQItUjoC0CuAjxMLOMzz3r/3h4ADgLcDM+ktOwKwC4HJg9ZmV/RoXWaGBUv1TiYABO8ofWLHwRDLPBd8JCn8quLMWPeMkiPozK5/dNpBCkAPIgnwWiLP9QqAqBc8of6rN1/3wh4VA8gRg9AxARwI7iFgJUCcAKwlBFg50lQIdDoCbMC1rpYKQrBygW+kUMcjkR+CsxvHus/sReCPQRvsR0A74rPCBnXtK6ZVTsdzgYwK+ovaVthE5zCi/8MnydZ+vQgC1AIiFARveINHnJQMbNlHlAbDbiTj7NBmUiYCoNqsiDBNUT+YjoHaSh3Lz3BDBcivedkaSjvqa8X2ypBe+QEQBVl9vBHrmCCi4H7EKcJban00GFcJYvv6H9UlA+i4AXAuAZT/1WWf/LdXv8G6VAQkxlMHPMsJFJ3CJylugstTaU2FPdT3wZpQ9UZ4LiYvU/TswJ1xDRsWZ88v0a0oIFjtDNt7YEQCPEEc0dnX/AwGQ2P9oDkDCAvld9XdP9dEV4I3tbpaenMZ3V2lIn0yCSlv0wyTh1Nkz9p6ppxVGoFU2VV/UOqn+6NKiMbtzdQgmcgRv1P/hJlXdw/C7/dcfajsAifeFDESU27MB+wa5jzoUaOB3LD4SA4v9NVF4LgAnd3ehgeozAHugHianEx6wCR+FG2YeA294whVQYtjvWQRUMw9BlDIkG7b6j4VmVrusOp9s/y0ncJX6R+POAD4kiI0A4L8BQ+Uf3gfg2H/2MBBTfdP+C7vAzdaPAFfIwLSERHVoIoqUBjNKm3EDGVIwx8kAOFLuaL86hkkkxcU/jDgrSh8CUhG9B6iMzc+0iUB7xO6H4EWszLqBb/ghJARgTwKytwI7OYAhBHBcQDYckOtlTmFYABIA3XILbCEJ3QaE1ampsRItHTbsF+mqqpUryCzZzYA/QzJJN+ICPLFqLwPCI/F/aXy5N4YjiRT6akB7BGmd2/INP/ghBGjJPwL+1QnIfGf2X8CuQ4GGEZXoO9UFEOdwhAxYDiCtXE79ngKh2t7LFWTAHwAbSTEKEby2kaqznEHUJ6XmCUJJjaPUdFbFK4CvtI2IprJ/+caVAHQSkD0ObL0MxCgJbnNNqb7+XlX+KATYLlwdky4NZVaRxY/ZcMGLZwNHkCaXCPwZ1bbOBZXNyS0wkJruSKmll1w9CsrHdACzZOBdYwWwYj7CcAhcijf+8o0/KHYAkgzs/u4Trqm+/g7gKYUDRNG7F4jKhTlAbz+SbgNjdz+g0S5yA0wFO5AQAnHVzwOoZ/vPAn8yMeclKSMlPwOspm1nhO2oeRZEM+0qgH8q9d/O8ZtWAig4AMGQuRDIWQ48JAUBkO3eRcDWuQSi+pETQOBSdpxQ/kjJI7IYljkrVXaBlajpZxbqeGrOQEDzGqA8OoywfvdqHP5+IICznEKFSDJOYhjvm35g0QEkFwIh2Bm4w3AgcAJ6MrV5R+y9BpcmCFQl+oOz8MByE0qNu/EK4UDkJBihWHF7Bvz4m5jAJct+I8Wn+6+I1a8YE0k4+OwBtaLwlbYZwIfjrQQwrP4jK/82+6+2y8q/IQmolR2SiNvvqFUc3x/A9jOwESfAgB6BnxGJFR6E9tWbhJ499ey9FUbIhDT6ejadAjwKMbSVtkgxY7kvAOuZjwFn1fvq0CACeAhucGPycejzzT9gdABYERheCLqDUQhh+0qeC2iYNcBvWf4wMWgQhE7+CdHoC04TAlFy0zkY6+41udAJkyANar8JKVIHEBFEspYfOZLIxofkmSEOr82B+H9WvWcIoALaStuILNj+bdtKAF4JUKu+uQpQx/5AFKj6NBwQeiLOYCCxKEegCELb++GHcCoCA2taYHXU0IrtXTJhjsd5kKcDpziDBEEgQZkkg+MBWVigiYjA/T3gZofjGI4kC+azwTszXgTaqwlgHX/5ls97tRRYVL2tADRCgUH1yYKgDofE4nc4VqDG/EGbE0ZiziMIF/yGYlCHYJEKKzviJLaOEWTbQ5CQpN9AAhcoP5JWGaBA8lmyKYHZI+FgldwMeLNhgncNlX0RWczufyAAWQqcjP2tCgACV+Z+t0RYAUmIpAOxEdtHTmDbTybBsHaAnIMmiuHmatcBk9m8iexcEgrqVgP2c6cxvFL+LMii2HkYJ5Er8H6TaeL4ANj/CKSPofiIowcH8P23COBGnwHQhOBVALxHg1l4kCED0mbIEVjqTIhk+4GT26dJIXAF0yGBQR4U6MR5ZNsNTkIRS0mVsa8ir+o4LnF4ZKvPYXKV3xWK/1o4gG/9/ioJKC8E9dyAAXaM75sDANDp+N8LA7p3CyjF1Y5B3xxKEsZ6AVo5SIDYZHMvGRUlqqLseLCSbzunpBVGMsy6hTA0icAWXf9sIjC45irZyPzKuJUjIH4KxR8cwLd+v50A1PMAmOzTnwXTYvkld7Bth5uM+9uBo3yAodKR8uP4HUEQ5dFtGYEM25QCDwQQqVAEzAgcQdx/JvipC4jICX50Cpxk/wzoorCkAsrM8WbHM0WCEGXU9qr9y0oAWwiglH8LCYz1/w3wqvznqr5BDhqsUwuEqg5BkUwHdgOI2yGsx02tHIHcaGd/pMQIbArMRF7hCGAwFMqAxWwTEdys+sO9zJzfjBuoKPVVba8lgGISsFsApElivyE45wdXADdNhwUdlkm8nnYCCeWXY+l439tecgvG5OxuZqSMjnPoJnwWYJETYUoenWOkaBP9M2C2yDML8my72fg/Am2FLKKxZvZvfb7t+77KAWxOwEj8NXUHp7DNb3QBCvwSAnSCq0MAQhiitugOcCzcbsX71qrAri9OXEY21nMGHUu9GnG4oQVncMg2Z8FPSDEFNMcVHemf6ssIidw3a6wsyM9oVwXhUQLwznkQMVIKbQRAV/45RKDJoAHcIQMhiwjUQwjQscer3hYh0BWBxhhCNCzej/ZZx9FuIsolHLbMFUWfAXIUviAY2ecKOUVjMTIoXH8EmAwhRSA/Cuoj/c255pHot33uQw6A5QFku5cLQGAjMSDmLCcw4BImixUaCDCZkntuwGtPCcABCx6nHBJkVDg7qSuvwEoAcQDIBPi9MTIAKyt59rcKyGWWHCr9IvJ4kv2NAII8gIC1Wwqs1wUAoi0yEABrx82UP+sGziCFDsgkHLDyBN1N80gjqCLg+CkQJOPqdn4BUOhEniENVJtE/2x8TduRa/IAmT1WBMSzxomO8yj7P/65r1YCotIPn0m8j28BFpVvwGdkoCRf2/gOd1k3MNgImIEEyBZZYEKJugVrHYEoi3EsTSzu5HEIZCCFyuQPnMIl4If7kgVMtt0hUkOCMj5XgVex7VM2XU3IlEAQxyPDdP0//n3GlYAh+FWs370OXBbbqWSfblNxAlbbsuUPyMLLBeA9YLafTZruB8+AO2vps+32650Flqem4b4T1d881oyreWICqJLL1e2XjQDkjUDkmX+d5WffEVeWE0CBNJU/qfq6f0eQBdVv/Qw1tdyCBWzGsDJGqBIZgiCAzjqK0kQ6A1hnjOGBNUEwIUmd5AAqxyndB0PFw7nkOAY9R5ePf+9XSUBGBAJudAVt234Ttn37xi4ESGyTE0rnAIBtBqwfAD/+Zl68r8nGdA3RykEsy2TtfJYkKsfWk+wM4GavJwnA2fj/CDCPgqzSPwoLov1HSOUVAeBKwGgtgJH80+AfbL8OC9A66Od0gFy0UiuCa+Sjt0cKboYQRGmHsR0w4vmGE0GRltk+AapuIlTbG9dcDh8mxpkCauL6wt/eUcojfY8AUiv0Wd+tc3ogAA/8xsKfDuykTVP2/YO1GlCLNnUCiii0Cpu7LUfgjUf2WTG/JgXLORwFtbkE2VLQRNKPTgiHjNKASBw7PZZ2J0Vnc+Q4ugsk6gAAG0BJREFUVVKKQH/muZxKCp/4Xv3DQGLn0fI3sEerAPVTghAaaFyllgcDi1Asq43t6yzwI2IIKgHiOFKWjZyjZ3XZBMuAOJqYbTJVwwuDfIb/l8FR2cy5VX6Ts0HmZdunz90i7eClJZnjZdoMv1EjAMcFbLiYAT+x8TpX0DCeAHPXxAA5XTug7YiW7on9NPYPwgLtEEKiSNjcTg2y4YSehCeBv+xUZid98ne5khCmwHaQDGeOGfVZVgKwqgAiiBH4U2XAfTCco1qxNcAZxiOAm+J/kSvwEoYU4Anl325ath0hr5BYNPDYq9Sr4LzY+reJfBZZVa/vhPYRGGf2Z/p4bZZPfM++CmCFAF4YIETR/upnApw3AqUJAQ4ShQPD/ovA3wjdANDwwxvKZbVjN45uSwI427eqnIywpsbIKOT7iAAy4Ix+p5kxMn2kzSsCCKoA+AiwJoOOAJTtF8vPSAK3NSFLhAJdPwLuTKiwHc8jhsx+1YaGBSRxJdeadQgWETBVTJNG0mVEE3TbXww9yg6lmPzL/gapawNSitpXgIdcF40783tlzmUd94EAEiVAuc8m+HWOoCH61fxAy19R/mplAElHicqrryeD3wM1fVkpm1gBkOgxHEV0gZA4VnpiFlQ5MzHNNoXjpM+9APBozKuI59BvpgAwJgE/B0KA6CWgrP7vZP4bWcBJZJYEI1FYQuzlAtw8gTFg2jXs12I+diz7gQA9tu/2GaRkOQvrfYapiZgNR6znyMn1zQCkpG7GOZfG0PenQAAZIM6cS2bcq9osnxAC0C6AgH14+Ie9EIQQwoY5FRo0HAbbKY5In3Yf2QtHEGVWiGEAVhHow1cHPHgeJnAZqAIll3GrSUdKBkdyBmQF41WTsxv3LMK6mAAe5bdwSKt6/AcCMEIAmevrbz88A7Dv1CofVQQ66w9ftAJrMdSuAHD46ucIiEGDeRDcKCwgB43KgZYa47l4biIav0QyybjfOufhWGcRiQHK7nivKQFUATcQ+Ylgnhl7+cT3sEOARgDO038dATjZ/w74AKTM9q05AScjBY8YEHRVy4/Kr4mEKZXbRnaSa/IAvR3HISk3CZkkr3AMOPeM3c2SiTtWAfyzgDyz3+xYZ/6e6XPoCMBZ9tuAboB8cALKIbT5x54H2CeVBrkGOHUFHjFQNlBJ6wnVZ+AWgogA3Fg6cVymuJ1zME/kYQdT0CwgXTUpEFdmUodtCgQQjrVf2NXtMuNn2lTu18x4rxyACgO8sp+n+ts+A+Rs+a+0Z1jFfXS/ASLLGQxjJEAYlgpn1FwdN0UazloDD6wR4aQVH4GTPP+ZCUkn/MmhxtWgsu7H7O9x5fkun/hsFQKw5B+AGsGfjfc9UrDIYjukmmjatlv4taoAFduvyccFWYJIvOSdFvIo7s8Avps0ScBaE606VoVUdFvL9byO4Inc2PvhnEcC2CfL+mf7p+P//ar1dgTsEA7AmJ1gFrZ36k36tXEjV8CshFwT3tEsqBPt2rDQNqX68GNl2kfEUQGmpcQR+VSOkQJIQf2vUMorxkxdd1R+hbl6aLzmAMhCnuEZAKPmrxW+EYAFcGtpsLM9dATgUrSiMvLQbSruYArQCaKIAJxyCjgxnGN6hGLuyy55npicFuEcJZSjAD7aPwvOK46TGfPBAej4nz3959T8B8VXYMR5aK4HIACOLD8DLZvzlp2nZiAB1G1+J9pVbD8jrdR6Awts5PymQL+Pf6j6EBCCNVHN/7iV/lgq6XkWCcn1k2NmwX2UxLLHyQBeLkPGXD7x3cccQGbdP1P9UPmt5CAAqiMLOVvD8re2XkjggHXASALUWfAzl4BzKLT0wblk+kdt0vuNc6lMbBPkhtU9tMpRgfUogGaApfmi8lsdPd9S/44ASLyPQEelZwlATQqIPU/56ctB1MtEGI61slP1NybvU4LfELBXmxMZfzZGxnGkQY8HgB9rxkVM9XkK0imqfYUYqgRYAnHBEelxXzkAJwcg4EOFz9p+5hSasBPlZuGCMgIPIkwmiN50RjWg+22zDsFxHRnwR21cEKtzjADvTUx0OzMgjsY2VbEI/iq4ps+L3JiKslfPszJ2pS2exwMBZHMA+8Re709HAGxxELTtnACgWZNIa5ew/APY9c0xngno+qlBXHxfDP7tBlaOwSZjsn+GFLZJciAMOUQYRQI4dKxHBvWVJDAz9vKJz4rXAYjidiHA/sPRtQDWE4LGOwIt1e+2KxvgEsD7DPyotNPqXwQNO84ApIkxI3IJwXryMcPjnUAAVeCd1f6MaxsJgNX9WXjgKbzlCIwyX7vn3jJhpZCUAGBjRBCKTzjukoraOlfbp04iooTk04mFic4I6QiwvQkvp+XlL44cewYkZwF0uDZ1D2Ztu76VR8ZZPv5ZDxpOwwDr+X9P4ZV9b66B2HodRmgXnHEGrc8Tgz98B4GF4wJp0Bud7B+BqDu9fcxMn6hNaT+5llL/IsnNkMNMn9eZUDYC0M/5I2jXzxqowzaw9l1bZzsCl1p9I1zQJCHkhffeVH+HJBgA9HwysZYE4TA/Z/sZziECi+clPAXOKg62y5xLFHJMjZFU2ciVnA30GRJ4jD7Lxz/zVQ5AwFVa/rt3osAv5gIQ3A+25OFuenbefV6AlBLZeBb4U/hMNSLQC8gonPyzx7Xq7gapyObwfKJx4SfIOJmzjveYQM78VlW7PktU2eseCSCI9wegW5Y/SQwakDpksPYLM1juofVTQHFxE71NKGkJQmyGDTyt9qsFGeCYo8N5ZcfJtnMnsvo9smNm2mWBUHU50bFnjvvYY67H6wiAvvLLyQPgk3xWqKCFRZSdAbdti5KBilws8YrcAd70cgxfJYtAYQPI97uPEog62DbxCmNGE7UKJjx2duwz2kVjXLl/hiAihzEz5isCCFYByhzRCj0A37H92xjE1neuwtmP/V1nQBYKWfMbQ40MCKvtD5EMO6ErgBqMGQGBnWa6z37sdPujoUYUipy4f9a+R0A/c9zl277bXgXYRQABjsDUIK0Anym7DiW0m2CCaS0ZHsggafuzYO6GSwCQNkn0CwnojDESYUwFjDjcTL9osVHZTTwigCMgvu77txCAEkCy7s9IAcHI3IIGNoJwIAV0ppmwYD+4xgn9HoCpAuIQl0aDsF9nH0J6KDWo2v5DKk86zxy/QjCZtq9Tm+hcrtq/EUCn9M4LQIYwYL+x5mpABUgK8H0jgmH47IC/U38Sl1fBnwV+GryzuYILwd+GTl5ENPmyzNONkzx2xg7PklP2ujLtHqtNdJxov3YljQBEibW1t7Y34CVW/Wngt3vv9MXxB4sPd5w5CBY+6PESTvihCUzU7JzF68uCwzrnSnKudCx1MZmJUxo/itWTP+bMeWX7PEW7s46ZGSdq00IA+uYfou4DkEG9vX2W7Weqz8gBccjcAQNPRfnNuUjcCQPB6a7BZIMqBI32SfBVjhZNtm6sxPFL48HglX5XtM2OeWa7zFhWm+VbP6NPAgrYXOX3VH8fwFT9qEqg+rvq76izRxQZfEVlQXcOJ4nDBdgZY6TZKoZ6ZpLFo4iq8JZHj1Htf1X7K8bNjDnTZiCAyPLPxvs4LnUEiaW/HaifCPyReEXEkSGfM22/nO82OaKTTyP4QMOLQo/M5NdnfXWf6viZ9pk263Vm2m0hwOoAUK3NxUCBsrvEkFH9YI1AN3+zFYHki0M6UBog8bCDYcth0SUHOgW3pwxyAPiJ9wvMjp6Z7Gzsx+pXPU62/RntGgFYyt/IQVnS9au3DwHL6vc6RIjWASDIBntvOMvsSkAPwBZuuu0HQBuNUwUFPd+LwZ+diFc4kPSxyQ/52H2rx6u0z7bV7ZZvkRyAEddr694BP3IFmXyAE/NHlt8iAv2fjXju1wJ/Cvhq4AzOzDZO58y4mXxClUxObX/4IvqzyU547xqOjnGkf7VvpX2p7bd8eCIJKIpLXAFTfq322jl0feCOee00qC2HYIHfUt408GFgb26n5v0JawVmiOVUgHuDpX6E+GwqEzseLRcnXz3OzDVV+3jtl5UAEKAIOhO40WO+mZifOA5KBEG7DuCJhUADIcDkZPPUJIQDil21/dP4KXYsNs9g46HNgYGrkz1/UucRwHrMo+c527/abwwBdgLoSIAou1bjSNU98jD/81Ct/t7/IyAuRPocAH9F9be2pEM0x+l+tTEag03u11H55Zy2yTZzURUUH2xbBVDmcEfGfOy+yzfrEMBaCrzfTAbsiBwyYcGg/oSEAOu9sKi2oe2fUP3WJQnacN4XbH84lp6VB9xJZoKn25RPPD3yaQ2PAC5zEkfHP9I/03cjAAbgAegHFv9YBMEsPyqsPgcNbNaWgb+bh4QsNLHgjWV9Q4IxZoZFIubxghmWcRWZSVrgj/xwb8Df/VYZMEY/7hVjPBAAgIIqvKHGkfJ3Y0UEsl99+L4AaQcoxLmm593Z4Gfz2pvrw76kg5giBXIiV+EwHDdsEE336/efAaiZszzzuEfHWr7508k7ARXIEMjMGZhKnnkpKGnDxhu2ESWfAX8K0Jn/ZwBmgjn3E7Y/i5uIWDITM3uszFgdYV01cPVEgvZHwXP0dK46fmXc5Zs+nZcBN8BFqn10v7H8V5NMZ7kTVYHBoicBTMkgqaqhC3AaRHiJ9m8TccJZeBM4dUw2wIHrjABVmdjkJ2nDV8eJzuus/VeelzX2RgCDwnuLghxV74CbedQ3Uy5MvBQkUn53P7odreIJUFnzvdueGKdq+b3xLwF2NqE/zRxnweiDNc6VpLD+Uo0AGnjBWg92f6dVur2yNFhA59h4nEfb5+T6fw2MCPxU9ZV8mG3UXKNzn1yjnqIRZtz9RXIpinaIplkiCgd+08D9Bc4ihuUbMQRQkzXrDBAv4UNBcllR+IDK/Ejgb5MZZnVEIJ7V9J4M9EAdEUI7ZqZhVrkzZJawFslTegPvR/gFMiSxEYBW2PX7oPIROWTe+JsIHzoygS/6fDTwjiq/Bv8s8BmJAOfR2x6BxnMW1dDBIyxrTkbnt/VzGqX6PwIgjhxCX0MGXEeO9xh912t4IIAo5nfAj2o0kAaqeDLb341hHNcDf/QEoAvsI8lCA4nW5D/iAE5558ABxR/O/SDCD3a/DCuZ83q/E8HyDZ/mVAF2pCEoKcizdj5DJEIaVfAnlgJXwT/lApxS3wzoM2DLTNSK8mfHE+UvtS/A9apxM6fwlMeW81vJ5WrnsREAA/W2LQHsVMyfGKez/gr8Q1ignEXm8V8PzFXXYIHJUmY2mWbIwPq/EvWEzkzeTJuQNMgg2XEzIJwJb6rjHgp7zjrYI43D3MryX8EBWHZ+VvUtEmGAbseAGUSPWwT/2apvglntOAv0bRwDWRnAXdYmM/BkEvKpgZm8tEeC7nWH6QhgRvVdkColt9rKcT1ioC4gsP0V8LttjUnMwFkBvjXJhu2EFGcBEk3saL8cN5uHmD3PaMpnzzMax9v/GMc4cn5n9N0IANXXBWnmPQCi0Enwb8AO2mbAXwFw1fJXiKQBxLg7FYJAR8aGiyboZfvVwNFxMhN1ZoyZPplzie5hZYzXve3y9RICEBAOZJAEdQnQxpiuG3DWBWA//RnJhu5TdyskFTIDKwBPtU2qfwQGb3/Ut/utEo0TTUxczPSd6ZMF5pVjZ88hanfkHDcCiAC7HSAqFQJthi4icAlU8YMyImPtAcAOmLBtCHzCHikwR6GEvtMnVxQY6ZFD2vMt8TDTjFN5yj5Xgisa29t/BNSV4y5f/6nj04ADABNZfI8kqJor5XcVPwF+D7RybimSgF/PHDNQ5YhAPCC2vkl3EYF6VvlpP7VxZpJW+lTasntbAYLVduYcKse9evzoXJav+9RX6wBkMnUKfgH4U+VFDcTkcmANCAR/SBIF8M+CPOUUCDnijZwB9UyfDlSJmZpo0s3HTPtMm7McRMkNRcgK9s9e18HDDt03AugArx7qMfftQ0XKP+MmvD4U4HguhDi8PpV9mfUGTJFToJdrMGaGNWHO2u46iYCQjgAwC4RsuyxRZoA0c8xo3CvGjI7p3dvla4kD2Dqom06JIOsOEs8A4A9jOZCzwV9yBKpxBtSZNt01JY5h3cwzicA7p84VZGZech1AFhjZdjPneYTIop+iet7ReGed60YAFuBc9T8R/IPiF2N+Rh6RWtM+xEmIw/EmlEckacA6KnsGuL0JaO5LJv2ykztqF+2fBXV23LNApcc5cnyPCM4Yd/kv6ACyoM62q7wSTD+BaDiQlAuYLBNSIBeAGRGBSQbkTlZAf0bb4dySbqQ62TOTNtPGDVkIarJjnkkCR45Z/V1nHMPa5xUBwEQ/TfnhF3DHJC8TYa7gKPhLqg8Hi4Bd3W9ZbDZhzgB3ZYx2bs7szUzsqM3R/Y/pBqJzPZM0HgP4eD0bAaTi/WxeoBDvD6SQIAzG/K1bslJgEUF3o48+XUhi32EiFev8WYKYAjzOPBCDSFkicHj7o75Zlc+MQy4vurS2vzp+9ryvtveZ81i+5lPGMiBT3zRJ7J3Tig9UHvVxHYC6SxmQm22csVwC2q8lcgTbGGRWHQF4tq83KbYxjNkegWAW6NG4mUk84wYyx50Zt3K+FgFUzu2o+9gIIALeVeBHuxmdQxb8VeAP48IAEZCn9zvHsCZQFuDZdvQ4CeWPJudTE0F0fjNOoDLmEQKoHmfmWjRhLF8dOQA1KVygFpKDrwP4B7IwgDkNdOYIDJBlgXt2O7wPenJEE3IG7DN9qhM9Ou8rx5slgMo5zzoT5hY2AjBBfTL48cfZhs6+OhzOvANtArBpR5AA5mEiIHc5GjPrCLLEcIXyW5O3uj07sTNgybTJgjU7Vna8KtEebe/1X/6z5QAmwT+AnL1g9CD4hTzcsMAiDba9mPCLQEv3G2RlTfoMoDNtvEnZ+quBZlR6Buwzx7lCvTMAz7SZIYDsuFlyZCrvnddGAIMDCMDfgbxCFIkKgUcg2q6m1X3/VWj7yTUD7Ec1iSHhLrJEcAT0dLIVKxHRRKwSQQSAq/dH15PdX2030z76LRj4oz7LV2kHQJRqIAgB1GOD31DRChF0bR3lM8GcKO91fYvuwmJr73y8yeQSRlL5zwL1rOJHk/jo/oxyR8e4GtDZ41fPoyeAQhKvVBk4Q/kD8FdIYLvhCTLxQozIAWzDBwCLQB3tj87BnQwTyl8hgkrbzKSNAHD1/gxJZNtkrhfVPLo2rfyV9hsBlMH8RMpfBjn8MpbyZ8asEEEbT/1GFZWOgB/tD13EBcpfBfwVbiCa+FfvrwA7OpfKWLNksZ7D8p8+lFwI9AS2H1U0A1Rp47YlwLTaTwF/7xSB9Oj+I+pfeX15SCYGyWYm5etGAhlQPmabqxwFjrsRgAaO+f0k5ccTcI+dBGuaHJLjReByCSNQ16PAj/qHgIUBKqrN2h7tH6ncFQQRgSoCeLQ/Gj+65gxxasufPSZrt/zHrAN4jcCfBjyG4RPPCZQdgAOuCLgeqUSEFIIeZt0VQD46pjeBryCBCMRX788CNjqPCplYx9wIIHQAB8GfVvwT3gNAgTQBflflme0l7qJCIDMgzwCvtQmcSZpECi82rTiECBTVsWbHi/pl9kdtzgT20bGW/xA5gNcc/K4bOAh8D8DdD3/kPygplhVLoL9Q+TPnESlUFdTV9rPOIgLw0f1HQRv9rjpE8I63EYDpAF5D8LuAP2j5o7GpSkMn/UNXvlfaZtxCa3Oh8lcAWWk7C9yzjpEFmAes2X3ZY2dIKNNm+feWA3hC8FeASNuS9QxZNbeOTfur38i6edkxI2BnVFc7kyPWPnO8yvhntI0m9WOSwBGQRy7g6P4skWwEMDiASfDjzTFdxX5m3f4CYCNyyCzwicZIkQUBv6fiFYWvtDVB9cjKnyWLqrqfBehZsM4CcbZfFrjR+BFRynGWf6cdwCT4GahSJBCAPwJrtx++6GOnQK3icVO5T3p+oAL0qG13fYScvImVAW/p+CoIzYxfPb8qkUSAuIIgZseMzjWzP9NmPb+NABpYXgPwlwAPE02vZjwT8BHJsMn7ZG6AzLoMAM9qU7H5Z6j7GWNkVLd6nCwAFVe2r5HCn7V/+crVAVSeAUALbyjhrPJ7LsIC9NaHKN4lDsBQVtMpOI7CIyg2ebxjzKr/DOgzfSok8NhtI2CeCfQjID3SN7pG3L985cvEOgAE/ZFXfSceCio7AMO1uIShriflFhySqQL2DMKgx0yofwbAnnupALYCpsx5PUaY8H4ILSoAjxzG8hUvi88C7Ee3VB5PjrZJuA02BgVp4EBSwM7E/cn1BBVV90A2tQ86RQCOCCuz/ygRZAF/lETOBLSnypXz9Igssy8igIp7WP7tTgAhcCfVuyOBE8DfLq4A/shVuERhAGsKpBeFBNH/gmRNqogoov2PRQJHj/MYJDBDDkeAPHs8fcxGAJaiVwHMwLZtS4Df7Kst+8HKgQX44fj7hizYz24XKbH8rmjzItAe3R+dU9WmZ53AB5UEZoE8228ggH+TdQAFADMgpQhGAZ0SAlHkSOGj/VZ4MRNCZPvMtuv6JQgqA9gqKWTBmAV3tl32uGcpvgWy6vZZpT8L5CgQlAA85a2qtwZ6RflDB5AEfwT4aL+21Fb7LIhn+kfAzfzHIhVgR22j8zmq/BVQZc61SgKV41fH9n6bWXI4q9/y5SoJiAMfBb9Xm7ccwXB8cQVE7QayIW8groI0s5KwOmYEHm9Cm/suUP+MEp/V5oiaV8B6VdsZEphR9Jk+FXLYCMAE0oTtb2OpCZoBq+kAjLFMsgDP4x33TOsfugohMnJuEUEM56lmRaSIV+/PnP8RwGfHrxzjyrZnksPlBPBlRhlwxrpnwW8CnWXJC0RymBCS5b4zwV5Wf+hwBNhH+lqW9rHdwVF1P9r/dQZ6ljiWlQC0SjIbPLRRilYFv0cC7Yc9WOrLAFWf94y9n+ljnZurdie8YnzquMS9PAUJHAVshqCs63oMsFeuzzvPaB8eZ/lS7QCU4jJVNckgUGurH1XuiVJfilSYFTdUtUIgR0nA67/tU7OjouBll2GEKVnQZ4EWXUPFps8es3KM15EEskoPt3T7KP02AojUO0UCk+CnoCWAzII7Au2w3yG8o6COzoUBioKCnKPrFBjJqRlQcQLVY2WJIjNuBaCvIwlUVX0G0NVjdATwMXEAAYBdEnhC8Ecgc/efGPNH5xFNdhOQRdt/ptpHCh3tj675CFE8JTFUjv2UriFz7GUlgOp/DNKRwUHwdxPfUeMjDoCCq5BfOOoEZvpr2x+BLavolXEyAM6obnTMzHEqoMuc09HxKv2rbTPAVYZO/ydUbXfkKP4/BnecprBuissAAAAASUVORK5CYII=";
  93997. return TextureTools;
  93998. }());
  93999. BABYLON.TextureTools = TextureTools;
  94000. })(BABYLON || (BABYLON = {}));
  94001. //# sourceMappingURL=babylon.textureTools.js.map
  94002. var BABYLON;
  94003. (function (BABYLON) {
  94004. var FramingBehavior = /** @class */ (function () {
  94005. function FramingBehavior() {
  94006. this._mode = FramingBehavior.FitFrustumSidesMode;
  94007. this._radiusScale = 1.0;
  94008. this._positionScale = 0.5;
  94009. this._defaultElevation = 0.3;
  94010. this._elevationReturnTime = 1500;
  94011. this._elevationReturnWaitTime = 1000;
  94012. this._zoomStopsAnimation = false;
  94013. this._framingTime = 1500;
  94014. this._isPointerDown = false;
  94015. this._lastInteractionTime = -Infinity;
  94016. // Framing control
  94017. this._animatables = new Array();
  94018. this._betaIsAnimating = false;
  94019. }
  94020. Object.defineProperty(FramingBehavior.prototype, "name", {
  94021. get: function () {
  94022. return "Framing";
  94023. },
  94024. enumerable: true,
  94025. configurable: true
  94026. });
  94027. Object.defineProperty(FramingBehavior.prototype, "mode", {
  94028. /**
  94029. * Gets current mode used by the behavior.
  94030. */
  94031. get: function () {
  94032. return this._mode;
  94033. },
  94034. /**
  94035. * Sets the current mode used by the behavior
  94036. */
  94037. set: function (mode) {
  94038. this._mode = mode;
  94039. },
  94040. enumerable: true,
  94041. configurable: true
  94042. });
  94043. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  94044. /**
  94045. * Gets the scale applied to the radius
  94046. */
  94047. get: function () {
  94048. return this._radiusScale;
  94049. },
  94050. /**
  94051. * Sets the scale applied to the radius (1 by default)
  94052. */
  94053. set: function (radius) {
  94054. this._radiusScale = radius;
  94055. },
  94056. enumerable: true,
  94057. configurable: true
  94058. });
  94059. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  94060. /**
  94061. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94062. */
  94063. get: function () {
  94064. return this._positionScale;
  94065. },
  94066. /**
  94067. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94068. */
  94069. set: function (scale) {
  94070. this._positionScale = scale;
  94071. },
  94072. enumerable: true,
  94073. configurable: true
  94074. });
  94075. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  94076. /**
  94077. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94078. * behaviour is triggered, in radians.
  94079. */
  94080. get: function () {
  94081. return this._defaultElevation;
  94082. },
  94083. /**
  94084. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94085. * behaviour is triggered, in radians.
  94086. */
  94087. set: function (elevation) {
  94088. this._defaultElevation = elevation;
  94089. },
  94090. enumerable: true,
  94091. configurable: true
  94092. });
  94093. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  94094. /**
  94095. * Gets the time (in milliseconds) taken to return to the default beta position.
  94096. * Negative value indicates camera should not return to default.
  94097. */
  94098. get: function () {
  94099. return this._elevationReturnTime;
  94100. },
  94101. /**
  94102. * Sets the time (in milliseconds) taken to return to the default beta position.
  94103. * Negative value indicates camera should not return to default.
  94104. */
  94105. set: function (speed) {
  94106. this._elevationReturnTime = speed;
  94107. },
  94108. enumerable: true,
  94109. configurable: true
  94110. });
  94111. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  94112. /**
  94113. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94114. */
  94115. get: function () {
  94116. return this._elevationReturnWaitTime;
  94117. },
  94118. /**
  94119. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94120. */
  94121. set: function (time) {
  94122. this._elevationReturnWaitTime = time;
  94123. },
  94124. enumerable: true,
  94125. configurable: true
  94126. });
  94127. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  94128. /**
  94129. * Gets the flag that indicates if user zooming should stop animation.
  94130. */
  94131. get: function () {
  94132. return this._zoomStopsAnimation;
  94133. },
  94134. /**
  94135. * Sets the flag that indicates if user zooming should stop animation.
  94136. */
  94137. set: function (flag) {
  94138. this._zoomStopsAnimation = flag;
  94139. },
  94140. enumerable: true,
  94141. configurable: true
  94142. });
  94143. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  94144. /**
  94145. * Gets the transition time when framing the mesh, in milliseconds
  94146. */
  94147. get: function () {
  94148. return this._framingTime;
  94149. },
  94150. /**
  94151. * Sets the transition time when framing the mesh, in milliseconds
  94152. */
  94153. set: function (time) {
  94154. this._framingTime = time;
  94155. },
  94156. enumerable: true,
  94157. configurable: true
  94158. });
  94159. FramingBehavior.prototype.init = function () {
  94160. // Do notihng
  94161. };
  94162. FramingBehavior.prototype.attach = function (camera) {
  94163. var _this = this;
  94164. this._attachedCamera = camera;
  94165. var scene = this._attachedCamera.getScene();
  94166. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  94167. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94168. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94169. _this._isPointerDown = true;
  94170. return;
  94171. }
  94172. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94173. _this._isPointerDown = false;
  94174. }
  94175. });
  94176. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94177. if (mesh) {
  94178. _this.zoomOnMesh(mesh);
  94179. }
  94180. });
  94181. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94182. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94183. _this._applyUserInteraction();
  94184. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  94185. // back to the default position after a given timeout
  94186. _this._maintainCameraAboveGround();
  94187. });
  94188. };
  94189. FramingBehavior.prototype.detach = function () {
  94190. if (!this._attachedCamera) {
  94191. return;
  94192. }
  94193. var scene = this._attachedCamera.getScene();
  94194. if (this._onPrePointerObservableObserver) {
  94195. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94196. }
  94197. if (this._onAfterCheckInputsObserver) {
  94198. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94199. }
  94200. if (this._onMeshTargetChangedObserver) {
  94201. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94202. }
  94203. this._attachedCamera = null;
  94204. };
  94205. /**
  94206. * Targets the given mesh and updates zoom level accordingly.
  94207. * @param mesh The mesh to target.
  94208. * @param radius Optional. If a cached radius position already exists, overrides default.
  94209. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94210. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94211. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94212. */
  94213. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94214. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94215. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94216. mesh.computeWorldMatrix(true);
  94217. var boundingBox = mesh.getBoundingInfo().boundingBox;
  94218. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  94219. };
  94220. /**
  94221. * Targets the given mesh with its children and updates zoom level accordingly.
  94222. * @param mesh The mesh to target.
  94223. * @param radius Optional. If a cached radius position already exists, overrides default.
  94224. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94225. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94226. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94227. */
  94228. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94229. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94230. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94231. mesh.computeWorldMatrix(true);
  94232. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  94233. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  94234. };
  94235. /**
  94236. * Targets the given meshes with their children and updates zoom level accordingly.
  94237. * @param meshes The mesh to target.
  94238. * @param radius Optional. If a cached radius position already exists, overrides default.
  94239. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94240. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94241. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94242. */
  94243. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  94244. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94245. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94246. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  94247. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  94248. for (var i = 0; i < meshes.length; i++) {
  94249. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  94250. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  94251. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  94252. }
  94253. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  94254. };
  94255. /**
  94256. * Targets the given mesh and updates zoom level accordingly.
  94257. * @param mesh The mesh to target.
  94258. * @param radius Optional. If a cached radius position already exists, overrides default.
  94259. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94260. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94261. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94262. */
  94263. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  94264. var _this = this;
  94265. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94266. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94267. var zoomTarget;
  94268. if (!this._attachedCamera) {
  94269. return;
  94270. }
  94271. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  94272. var bottom = minimumWorld.y;
  94273. var top = maximumWorld.y;
  94274. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  94275. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  94276. if (focusOnOriginXZ) {
  94277. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  94278. }
  94279. else {
  94280. var centerWorld = minimumWorld.add(radiusWorld);
  94281. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  94282. }
  94283. if (!this._vectorTransition) {
  94284. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  94285. }
  94286. this._betaIsAnimating = true;
  94287. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  94288. if (animatable) {
  94289. this._animatables.push(animatable);
  94290. }
  94291. // sets the radius and lower radius bounds
  94292. // Small delta ensures camera is not always at lower zoom limit.
  94293. var radius = 0;
  94294. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  94295. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94296. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  94297. radius = position;
  94298. }
  94299. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94300. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94301. if (this._attachedCamera.lowerRadiusLimit === null) {
  94302. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  94303. }
  94304. }
  94305. // Set sensibilities
  94306. var extend = maximumWorld.subtract(minimumWorld).length();
  94307. this._attachedCamera.panningSensibility = 5000 / extend;
  94308. this._attachedCamera.wheelPrecision = 100 / radius;
  94309. // transition to new radius
  94310. if (!this._radiusTransition) {
  94311. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94312. }
  94313. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  94314. _this.stopAllAnimations();
  94315. if (onAnimationEnd) {
  94316. onAnimationEnd();
  94317. }
  94318. if (_this._attachedCamera) {
  94319. _this._attachedCamera.storeState();
  94320. }
  94321. });
  94322. if (animatable) {
  94323. this._animatables.push(animatable);
  94324. }
  94325. };
  94326. /**
  94327. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  94328. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  94329. * frustum width.
  94330. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  94331. * to fully enclose the mesh in the viewing frustum.
  94332. */
  94333. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  94334. var size = maximumWorld.subtract(minimumWorld);
  94335. var boxVectorGlobalDiagonal = size.length();
  94336. var frustumSlope = this._getFrustumSlope();
  94337. // Formula for setting distance
  94338. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  94339. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  94340. // Horizon distance
  94341. var radius = radiusWithoutFraming * this._radiusScale;
  94342. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  94343. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  94344. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  94345. var camera = this._attachedCamera;
  94346. if (!camera) {
  94347. return 0;
  94348. }
  94349. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94350. // Don't exceed the requested limit
  94351. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  94352. }
  94353. // Don't exceed the upper radius limit
  94354. if (camera.upperRadiusLimit) {
  94355. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  94356. }
  94357. return distance;
  94358. };
  94359. /**
  94360. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  94361. * is automatically returned to its default position (expected to be above ground plane).
  94362. */
  94363. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  94364. var _this = this;
  94365. if (this._elevationReturnTime < 0) {
  94366. return;
  94367. }
  94368. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  94369. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  94370. var limitBeta = Math.PI * 0.5;
  94371. // Bring the camera back up if below the ground plane
  94372. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  94373. this._betaIsAnimating = true;
  94374. //Transition to new position
  94375. this.stopAllAnimations();
  94376. if (!this._betaTransition) {
  94377. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94378. }
  94379. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  94380. _this._clearAnimationLocks();
  94381. _this.stopAllAnimations();
  94382. });
  94383. if (animatabe) {
  94384. this._animatables.push(animatabe);
  94385. }
  94386. }
  94387. };
  94388. /**
  94389. * Returns the frustum slope based on the canvas ratio and camera FOV
  94390. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  94391. */
  94392. FramingBehavior.prototype._getFrustumSlope = function () {
  94393. // Calculate the viewport ratio
  94394. // Aspect Ratio is Height/Width.
  94395. var camera = this._attachedCamera;
  94396. if (!camera) {
  94397. return BABYLON.Vector2.Zero();
  94398. }
  94399. var engine = camera.getScene().getEngine();
  94400. var aspectRatio = engine.getAspectRatio(camera);
  94401. // Camera FOV is the vertical field of view (top-bottom) in radians.
  94402. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  94403. var frustumSlopeY = Math.tan(camera.fov / 2);
  94404. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  94405. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  94406. // along the forward vector.
  94407. var frustumSlopeX = frustumSlopeY * aspectRatio;
  94408. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  94409. };
  94410. /**
  94411. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  94412. */
  94413. FramingBehavior.prototype._clearAnimationLocks = function () {
  94414. this._betaIsAnimating = false;
  94415. };
  94416. /**
  94417. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94418. */
  94419. FramingBehavior.prototype._applyUserInteraction = function () {
  94420. if (this.isUserIsMoving) {
  94421. this._lastInteractionTime = BABYLON.Tools.Now;
  94422. this.stopAllAnimations();
  94423. this._clearAnimationLocks();
  94424. }
  94425. };
  94426. /**
  94427. * Stops and removes all animations that have been applied to the camera
  94428. */
  94429. FramingBehavior.prototype.stopAllAnimations = function () {
  94430. if (this._attachedCamera) {
  94431. this._attachedCamera.animations = [];
  94432. }
  94433. while (this._animatables.length) {
  94434. if (this._animatables[0]) {
  94435. this._animatables[0].onAnimationEnd = null;
  94436. this._animatables[0].stop();
  94437. }
  94438. this._animatables.shift();
  94439. }
  94440. };
  94441. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  94442. /**
  94443. * Gets a value indicating if the user is moving the camera
  94444. */
  94445. get: function () {
  94446. if (!this._attachedCamera) {
  94447. return false;
  94448. }
  94449. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94450. this._attachedCamera.inertialBetaOffset !== 0 ||
  94451. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94452. this._attachedCamera.inertialPanningX !== 0 ||
  94453. this._attachedCamera.inertialPanningY !== 0 ||
  94454. this._isPointerDown;
  94455. },
  94456. enumerable: true,
  94457. configurable: true
  94458. });
  94459. /**
  94460. * The easing function used by animations
  94461. */
  94462. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  94463. /**
  94464. * The easing mode used by animations
  94465. */
  94466. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  94467. // Statics
  94468. /**
  94469. * The camera can move all the way towards the mesh.
  94470. */
  94471. FramingBehavior.IgnoreBoundsSizeMode = 0;
  94472. /**
  94473. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  94474. */
  94475. FramingBehavior.FitFrustumSidesMode = 1;
  94476. return FramingBehavior;
  94477. }());
  94478. BABYLON.FramingBehavior = FramingBehavior;
  94479. })(BABYLON || (BABYLON = {}));
  94480. //# sourceMappingURL=babylon.framingBehavior.js.map
  94481. var BABYLON;
  94482. (function (BABYLON) {
  94483. /**
  94484. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  94485. */
  94486. var BouncingBehavior = /** @class */ (function () {
  94487. function BouncingBehavior() {
  94488. /**
  94489. * The duration of the animation, in milliseconds
  94490. */
  94491. this.transitionDuration = 450;
  94492. /**
  94493. * Length of the distance animated by the transition when lower radius is reached
  94494. */
  94495. this.lowerRadiusTransitionRange = 2;
  94496. /**
  94497. * Length of the distance animated by the transition when upper radius is reached
  94498. */
  94499. this.upperRadiusTransitionRange = -2;
  94500. this._autoTransitionRange = false;
  94501. // Animations
  94502. this._radiusIsAnimating = false;
  94503. this._radiusBounceTransition = null;
  94504. this._animatables = new Array();
  94505. }
  94506. Object.defineProperty(BouncingBehavior.prototype, "name", {
  94507. get: function () {
  94508. return "Bouncing";
  94509. },
  94510. enumerable: true,
  94511. configurable: true
  94512. });
  94513. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  94514. /**
  94515. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94516. */
  94517. get: function () {
  94518. return this._autoTransitionRange;
  94519. },
  94520. /**
  94521. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94522. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  94523. */
  94524. set: function (value) {
  94525. var _this = this;
  94526. if (this._autoTransitionRange === value) {
  94527. return;
  94528. }
  94529. this._autoTransitionRange = value;
  94530. var camera = this._attachedCamera;
  94531. if (!camera) {
  94532. return;
  94533. }
  94534. if (value) {
  94535. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94536. if (!mesh) {
  94537. return;
  94538. }
  94539. mesh.computeWorldMatrix(true);
  94540. var diagonal = mesh.getBoundingInfo().diagonalLength;
  94541. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  94542. _this.upperRadiusTransitionRange = diagonal * 0.05;
  94543. });
  94544. }
  94545. else if (this._onMeshTargetChangedObserver) {
  94546. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94547. }
  94548. },
  94549. enumerable: true,
  94550. configurable: true
  94551. });
  94552. BouncingBehavior.prototype.init = function () {
  94553. // Do notihng
  94554. };
  94555. BouncingBehavior.prototype.attach = function (camera) {
  94556. var _this = this;
  94557. this._attachedCamera = camera;
  94558. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94559. if (!_this._attachedCamera) {
  94560. return;
  94561. }
  94562. // Add the bounce animation to the lower radius limit
  94563. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  94564. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  94565. }
  94566. // Add the bounce animation to the upper radius limit
  94567. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  94568. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  94569. }
  94570. });
  94571. };
  94572. BouncingBehavior.prototype.detach = function () {
  94573. if (!this._attachedCamera) {
  94574. return;
  94575. }
  94576. if (this._onAfterCheckInputsObserver) {
  94577. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94578. }
  94579. if (this._onMeshTargetChangedObserver) {
  94580. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94581. }
  94582. this._attachedCamera = null;
  94583. };
  94584. /**
  94585. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  94586. * @param radiusLimit The limit to check against.
  94587. * @return Bool to indicate if at limit.
  94588. */
  94589. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  94590. if (!this._attachedCamera) {
  94591. return false;
  94592. }
  94593. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  94594. return true;
  94595. }
  94596. return false;
  94597. };
  94598. /**
  94599. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  94600. * @param radiusDelta The delta by which to animate to. Can be negative.
  94601. */
  94602. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  94603. var _this = this;
  94604. if (!this._attachedCamera) {
  94605. return;
  94606. }
  94607. if (!this._radiusBounceTransition) {
  94608. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  94609. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  94610. }
  94611. // Prevent zoom until bounce has completed
  94612. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  94613. this._attachedCamera.wheelPrecision = Infinity;
  94614. this._attachedCamera.inertialRadiusOffset = 0;
  94615. // Animate to the radius limit
  94616. this.stopAllAnimations();
  94617. this._radiusIsAnimating = true;
  94618. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  94619. if (animatable) {
  94620. this._animatables.push(animatable);
  94621. }
  94622. };
  94623. /**
  94624. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  94625. */
  94626. BouncingBehavior.prototype._clearAnimationLocks = function () {
  94627. this._radiusIsAnimating = false;
  94628. if (this._attachedCamera) {
  94629. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  94630. }
  94631. };
  94632. /**
  94633. * Stops and removes all animations that have been applied to the camera
  94634. */
  94635. BouncingBehavior.prototype.stopAllAnimations = function () {
  94636. if (this._attachedCamera) {
  94637. this._attachedCamera.animations = [];
  94638. }
  94639. while (this._animatables.length) {
  94640. this._animatables[0].onAnimationEnd = null;
  94641. this._animatables[0].stop();
  94642. this._animatables.shift();
  94643. }
  94644. };
  94645. /**
  94646. * The easing function used by animations
  94647. */
  94648. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  94649. /**
  94650. * The easing mode used by animations
  94651. */
  94652. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  94653. return BouncingBehavior;
  94654. }());
  94655. BABYLON.BouncingBehavior = BouncingBehavior;
  94656. })(BABYLON || (BABYLON = {}));
  94657. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  94658. var BABYLON;
  94659. (function (BABYLON) {
  94660. var AutoRotationBehavior = /** @class */ (function () {
  94661. function AutoRotationBehavior() {
  94662. this._zoomStopsAnimation = false;
  94663. this._idleRotationSpeed = 0.05;
  94664. this._idleRotationWaitTime = 2000;
  94665. this._idleRotationSpinupTime = 2000;
  94666. this._isPointerDown = false;
  94667. this._lastFrameTime = null;
  94668. this._lastInteractionTime = -Infinity;
  94669. this._cameraRotationSpeed = 0;
  94670. this._lastFrameRadius = 0;
  94671. }
  94672. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  94673. get: function () {
  94674. return "AutoRotation";
  94675. },
  94676. enumerable: true,
  94677. configurable: true
  94678. });
  94679. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  94680. /**
  94681. * Gets the flag that indicates if user zooming should stop animation.
  94682. */
  94683. get: function () {
  94684. return this._zoomStopsAnimation;
  94685. },
  94686. /**
  94687. * Sets the flag that indicates if user zooming should stop animation.
  94688. */
  94689. set: function (flag) {
  94690. this._zoomStopsAnimation = flag;
  94691. },
  94692. enumerable: true,
  94693. configurable: true
  94694. });
  94695. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  94696. /**
  94697. * Gets the default speed at which the camera rotates around the model.
  94698. */
  94699. get: function () {
  94700. return this._idleRotationSpeed;
  94701. },
  94702. /**
  94703. * Sets the default speed at which the camera rotates around the model.
  94704. */
  94705. set: function (speed) {
  94706. this._idleRotationSpeed = speed;
  94707. },
  94708. enumerable: true,
  94709. configurable: true
  94710. });
  94711. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  94712. /**
  94713. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  94714. */
  94715. get: function () {
  94716. return this._idleRotationWaitTime;
  94717. },
  94718. /**
  94719. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  94720. */
  94721. set: function (time) {
  94722. this._idleRotationWaitTime = time;
  94723. },
  94724. enumerable: true,
  94725. configurable: true
  94726. });
  94727. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  94728. /**
  94729. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94730. */
  94731. get: function () {
  94732. return this._idleRotationSpinupTime;
  94733. },
  94734. /**
  94735. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94736. */
  94737. set: function (time) {
  94738. this._idleRotationSpinupTime = time;
  94739. },
  94740. enumerable: true,
  94741. configurable: true
  94742. });
  94743. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  94744. /**
  94745. * Gets a value indicating if the camera is currently rotating because of this behavior
  94746. */
  94747. get: function () {
  94748. return Math.abs(this._cameraRotationSpeed) > 0;
  94749. },
  94750. enumerable: true,
  94751. configurable: true
  94752. });
  94753. AutoRotationBehavior.prototype.init = function () {
  94754. // Do notihng
  94755. };
  94756. AutoRotationBehavior.prototype.attach = function (camera) {
  94757. var _this = this;
  94758. this._attachedCamera = camera;
  94759. var scene = this._attachedCamera.getScene();
  94760. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94761. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94762. _this._isPointerDown = true;
  94763. return;
  94764. }
  94765. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94766. _this._isPointerDown = false;
  94767. }
  94768. });
  94769. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94770. var now = BABYLON.Tools.Now;
  94771. var dt = 0;
  94772. if (_this._lastFrameTime != null) {
  94773. dt = now - _this._lastFrameTime;
  94774. }
  94775. _this._lastFrameTime = now;
  94776. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94777. _this._applyUserInteraction();
  94778. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  94779. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  94780. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  94781. // Step camera rotation by rotation speed
  94782. if (_this._attachedCamera) {
  94783. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  94784. }
  94785. });
  94786. };
  94787. AutoRotationBehavior.prototype.detach = function () {
  94788. if (!this._attachedCamera) {
  94789. return;
  94790. }
  94791. var scene = this._attachedCamera.getScene();
  94792. if (this._onPrePointerObservableObserver) {
  94793. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94794. }
  94795. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94796. this._attachedCamera = null;
  94797. };
  94798. /**
  94799. * Returns true if user is scrolling.
  94800. * @return true if user is scrolling.
  94801. */
  94802. AutoRotationBehavior.prototype._userIsZooming = function () {
  94803. if (!this._attachedCamera) {
  94804. return false;
  94805. }
  94806. return this._attachedCamera.inertialRadiusOffset !== 0;
  94807. };
  94808. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  94809. if (!this._attachedCamera) {
  94810. return false;
  94811. }
  94812. var zoomHasHitLimit = false;
  94813. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  94814. zoomHasHitLimit = true;
  94815. }
  94816. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  94817. this._lastFrameRadius = this._attachedCamera.radius;
  94818. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  94819. };
  94820. /**
  94821. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94822. */
  94823. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  94824. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  94825. this._lastInteractionTime = BABYLON.Tools.Now;
  94826. }
  94827. };
  94828. // Tools
  94829. AutoRotationBehavior.prototype._userIsMoving = function () {
  94830. if (!this._attachedCamera) {
  94831. return false;
  94832. }
  94833. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94834. this._attachedCamera.inertialBetaOffset !== 0 ||
  94835. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94836. this._attachedCamera.inertialPanningX !== 0 ||
  94837. this._attachedCamera.inertialPanningY !== 0 ||
  94838. this._isPointerDown;
  94839. };
  94840. return AutoRotationBehavior;
  94841. }());
  94842. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  94843. })(BABYLON || (BABYLON = {}));
  94844. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  94845. var BABYLON;
  94846. (function (BABYLON) {
  94847. var NullEngineOptions = /** @class */ (function () {
  94848. function NullEngineOptions() {
  94849. this.renderWidth = 512;
  94850. this.renderHeight = 256;
  94851. this.textureSize = 512;
  94852. this.deterministicLockstep = false;
  94853. this.lockstepMaxSteps = 4;
  94854. }
  94855. return NullEngineOptions;
  94856. }());
  94857. BABYLON.NullEngineOptions = NullEngineOptions;
  94858. /**
  94859. * The null engine class provides support for headless version of babylon.js.
  94860. * This can be used in server side scenario or for testing purposes
  94861. */
  94862. var NullEngine = /** @class */ (function (_super) {
  94863. __extends(NullEngine, _super);
  94864. function NullEngine(options) {
  94865. if (options === void 0) { options = new NullEngineOptions(); }
  94866. var _this = _super.call(this, null) || this;
  94867. if (options.deterministicLockstep === undefined) {
  94868. options.deterministicLockstep = false;
  94869. }
  94870. if (options.lockstepMaxSteps === undefined) {
  94871. options.lockstepMaxSteps = 4;
  94872. }
  94873. _this._options = options;
  94874. // Init caps
  94875. // We consider we are on a webgl1 capable device
  94876. _this._caps = new BABYLON.EngineCapabilities();
  94877. _this._caps.maxTexturesImageUnits = 16;
  94878. _this._caps.maxVertexTextureImageUnits = 16;
  94879. _this._caps.maxTextureSize = 512;
  94880. _this._caps.maxCubemapTextureSize = 512;
  94881. _this._caps.maxRenderTextureSize = 512;
  94882. _this._caps.maxVertexAttribs = 16;
  94883. _this._caps.maxVaryingVectors = 16;
  94884. _this._caps.maxFragmentUniformVectors = 16;
  94885. _this._caps.maxVertexUniformVectors = 16;
  94886. // Extensions
  94887. _this._caps.standardDerivatives = false;
  94888. _this._caps.astc = null;
  94889. _this._caps.s3tc = null;
  94890. _this._caps.pvrtc = null;
  94891. _this._caps.etc1 = null;
  94892. _this._caps.etc2 = null;
  94893. _this._caps.textureAnisotropicFilterExtension = null;
  94894. _this._caps.maxAnisotropy = 0;
  94895. _this._caps.uintIndices = false;
  94896. _this._caps.fragmentDepthSupported = false;
  94897. _this._caps.highPrecisionShaderSupported = true;
  94898. _this._caps.colorBufferFloat = false;
  94899. _this._caps.textureFloat = false;
  94900. _this._caps.textureFloatLinearFiltering = false;
  94901. _this._caps.textureFloatRender = false;
  94902. _this._caps.textureHalfFloat = false;
  94903. _this._caps.textureHalfFloatLinearFiltering = false;
  94904. _this._caps.textureHalfFloatRender = false;
  94905. _this._caps.textureLOD = false;
  94906. _this._caps.drawBuffersExtension = false;
  94907. _this._caps.depthTextureExtension = false;
  94908. _this._caps.vertexArrayObject = false;
  94909. _this._caps.instancedArrays = false;
  94910. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  94911. // Wrappers
  94912. if (typeof URL === "undefined") {
  94913. URL = {
  94914. createObjectURL: function () { },
  94915. revokeObjectURL: function () { }
  94916. };
  94917. }
  94918. if (typeof Blob === "undefined") {
  94919. Blob = function () { };
  94920. }
  94921. return _this;
  94922. }
  94923. NullEngine.prototype.isDeterministicLockStep = function () {
  94924. return this._options.deterministicLockstep;
  94925. };
  94926. NullEngine.prototype.getLockstepMaxSteps = function () {
  94927. return this._options.lockstepMaxSteps;
  94928. };
  94929. NullEngine.prototype.getHardwareScalingLevel = function () {
  94930. return 1.0;
  94931. };
  94932. NullEngine.prototype.createVertexBuffer = function (vertices) {
  94933. return {
  94934. capacity: 0,
  94935. references: 1,
  94936. is32Bits: false
  94937. };
  94938. };
  94939. NullEngine.prototype.createIndexBuffer = function (indices) {
  94940. return {
  94941. capacity: 0,
  94942. references: 1,
  94943. is32Bits: false
  94944. };
  94945. };
  94946. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  94947. if (stencil === void 0) { stencil = false; }
  94948. };
  94949. NullEngine.prototype.getRenderWidth = function (useScreen) {
  94950. if (useScreen === void 0) { useScreen = false; }
  94951. if (!useScreen && this._currentRenderTarget) {
  94952. return this._currentRenderTarget.width;
  94953. }
  94954. return this._options.renderWidth;
  94955. };
  94956. NullEngine.prototype.getRenderHeight = function (useScreen) {
  94957. if (useScreen === void 0) { useScreen = false; }
  94958. if (!useScreen && this._currentRenderTarget) {
  94959. return this._currentRenderTarget.height;
  94960. }
  94961. return this._options.renderHeight;
  94962. };
  94963. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  94964. this._cachedViewport = viewport;
  94965. };
  94966. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  94967. return {
  94968. transformFeedback: null,
  94969. __SPECTOR_rebuildProgram: null
  94970. };
  94971. };
  94972. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  94973. return [];
  94974. };
  94975. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  94976. return [];
  94977. };
  94978. NullEngine.prototype.bindSamplers = function (effect) {
  94979. this._currentEffect = null;
  94980. };
  94981. NullEngine.prototype.enableEffect = function (effect) {
  94982. this._currentEffect = effect;
  94983. if (effect.onBind) {
  94984. effect.onBind(effect);
  94985. }
  94986. effect.onBindObservable.notifyObservers(effect);
  94987. };
  94988. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  94989. if (zOffset === void 0) { zOffset = 0; }
  94990. if (reverseSide === void 0) { reverseSide = false; }
  94991. };
  94992. NullEngine.prototype.setIntArray = function (uniform, array) {
  94993. };
  94994. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  94995. };
  94996. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  94997. };
  94998. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  94999. };
  95000. NullEngine.prototype.setFloatArray = function (uniform, array) {
  95001. };
  95002. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  95003. };
  95004. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  95005. };
  95006. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  95007. };
  95008. NullEngine.prototype.setArray = function (uniform, array) {
  95009. };
  95010. NullEngine.prototype.setArray2 = function (uniform, array) {
  95011. };
  95012. NullEngine.prototype.setArray3 = function (uniform, array) {
  95013. };
  95014. NullEngine.prototype.setArray4 = function (uniform, array) {
  95015. };
  95016. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  95017. };
  95018. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  95019. };
  95020. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  95021. };
  95022. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  95023. };
  95024. NullEngine.prototype.setFloat = function (uniform, value) {
  95025. };
  95026. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  95027. };
  95028. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  95029. };
  95030. NullEngine.prototype.setBool = function (uniform, bool) {
  95031. };
  95032. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  95033. };
  95034. NullEngine.prototype.setColor3 = function (uniform, color3) {
  95035. };
  95036. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  95037. };
  95038. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  95039. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  95040. if (this._alphaMode === mode) {
  95041. return;
  95042. }
  95043. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  95044. if (!noDepthWriteChange) {
  95045. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  95046. }
  95047. this._alphaMode = mode;
  95048. };
  95049. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  95050. };
  95051. NullEngine.prototype.wipeCaches = function (bruteForce) {
  95052. if (this.preventCacheWipeBetweenFrames) {
  95053. return;
  95054. }
  95055. this.resetTextureCache();
  95056. this._currentEffect = null;
  95057. if (bruteForce) {
  95058. this._currentProgram = null;
  95059. this._stencilState.reset();
  95060. this._depthCullingState.reset();
  95061. this._alphaState.reset();
  95062. }
  95063. this._cachedVertexBuffers = null;
  95064. this._cachedIndexBuffer = null;
  95065. this._cachedEffectForVertexBuffers = null;
  95066. };
  95067. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  95068. };
  95069. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  95070. };
  95071. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  95072. };
  95073. NullEngine.prototype._createTexture = function () {
  95074. return {};
  95075. };
  95076. NullEngine.prototype._releaseTexture = function (texture) {
  95077. };
  95078. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  95079. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95080. if (onLoad === void 0) { onLoad = null; }
  95081. if (onError === void 0) { onError = null; }
  95082. if (buffer === void 0) { buffer = null; }
  95083. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  95084. var url = String(urlArg);
  95085. texture.url = url;
  95086. texture.generateMipMaps = !noMipmap;
  95087. texture.samplingMode = samplingMode;
  95088. texture.invertY = invertY;
  95089. texture.baseWidth = this._options.textureSize;
  95090. texture.baseHeight = this._options.textureSize;
  95091. texture.width = this._options.textureSize;
  95092. texture.height = this._options.textureSize;
  95093. if (format) {
  95094. texture.format = format;
  95095. }
  95096. texture.isReady = true;
  95097. if (onLoad) {
  95098. onLoad();
  95099. }
  95100. return texture;
  95101. };
  95102. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  95103. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  95104. if (options !== undefined && typeof options === "object") {
  95105. fullOptions.generateMipMaps = options.generateMipMaps;
  95106. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  95107. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  95108. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  95109. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  95110. }
  95111. else {
  95112. fullOptions.generateMipMaps = options;
  95113. fullOptions.generateDepthBuffer = true;
  95114. fullOptions.generateStencilBuffer = false;
  95115. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95116. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  95117. }
  95118. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  95119. var width = size.width || size;
  95120. var height = size.height || size;
  95121. texture._depthStencilBuffer = {};
  95122. texture._framebuffer = {};
  95123. texture.baseWidth = width;
  95124. texture.baseHeight = height;
  95125. texture.width = width;
  95126. texture.height = height;
  95127. texture.isReady = true;
  95128. texture.samples = 1;
  95129. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  95130. texture.samplingMode = fullOptions.samplingMode;
  95131. texture.type = fullOptions.type;
  95132. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  95133. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  95134. return texture;
  95135. };
  95136. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  95137. texture.samplingMode = samplingMode;
  95138. };
  95139. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  95140. if (this._currentRenderTarget) {
  95141. this.unBindFramebuffer(this._currentRenderTarget);
  95142. }
  95143. this._currentRenderTarget = texture;
  95144. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  95145. if (this._cachedViewport && !forceFullscreenViewport) {
  95146. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  95147. }
  95148. };
  95149. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  95150. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  95151. this._currentRenderTarget = null;
  95152. if (onBeforeUnbind) {
  95153. if (texture._MSAAFramebuffer) {
  95154. this._currentFramebuffer = texture._framebuffer;
  95155. }
  95156. onBeforeUnbind();
  95157. }
  95158. this._currentFramebuffer = null;
  95159. };
  95160. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  95161. var vbo = {
  95162. capacity: 1,
  95163. references: 1,
  95164. is32Bits: false
  95165. };
  95166. return vbo;
  95167. };
  95168. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  95169. if (offset === void 0) { offset = 0; }
  95170. };
  95171. /**
  95172. * Updates a dynamic vertex buffer.
  95173. * @param vertexBuffer the vertex buffer to update
  95174. * @param data the data used to update the vertex buffer
  95175. * @param byteOffset the byte offset of the data (optional)
  95176. * @param byteLength the byte length of the data (optional)
  95177. */
  95178. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  95179. };
  95180. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  95181. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  95182. this._boundTexturesCache[this._activeChannel] = texture;
  95183. }
  95184. };
  95185. NullEngine.prototype._bindTexture = function (channel, texture) {
  95186. if (channel < 0) {
  95187. return;
  95188. }
  95189. this._bindTextureDirectly(0, texture);
  95190. };
  95191. NullEngine.prototype._releaseBuffer = function (buffer) {
  95192. buffer.references--;
  95193. if (buffer.references === 0) {
  95194. return true;
  95195. }
  95196. return false;
  95197. };
  95198. return NullEngine;
  95199. }(BABYLON.Engine));
  95200. BABYLON.NullEngine = NullEngine;
  95201. })(BABYLON || (BABYLON = {}));
  95202. //# sourceMappingURL=babylon.nullEngine.js.map
  95203. var BABYLON;
  95204. (function (BABYLON) {
  95205. /**
  95206. * This class can be used to get instrumentation data from a Babylon engine
  95207. */
  95208. var EngineInstrumentation = /** @class */ (function () {
  95209. function EngineInstrumentation(engine) {
  95210. this.engine = engine;
  95211. this._captureGPUFrameTime = false;
  95212. this._gpuFrameTime = new BABYLON.PerfCounter();
  95213. this._captureShaderCompilationTime = false;
  95214. this._shaderCompilationTime = new BABYLON.PerfCounter();
  95215. // Observers
  95216. this._onBeginFrameObserver = null;
  95217. this._onEndFrameObserver = null;
  95218. this._onBeforeShaderCompilationObserver = null;
  95219. this._onAfterShaderCompilationObserver = null;
  95220. }
  95221. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  95222. // Properties
  95223. /**
  95224. * Gets the perf counter used for GPU frame time
  95225. */
  95226. get: function () {
  95227. return this._gpuFrameTime;
  95228. },
  95229. enumerable: true,
  95230. configurable: true
  95231. });
  95232. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  95233. /**
  95234. * Gets the GPU frame time capture status
  95235. */
  95236. get: function () {
  95237. return this._captureGPUFrameTime;
  95238. },
  95239. /**
  95240. * Enable or disable the GPU frame time capture
  95241. */
  95242. set: function (value) {
  95243. var _this = this;
  95244. if (value === this._captureGPUFrameTime) {
  95245. return;
  95246. }
  95247. this._captureGPUFrameTime = value;
  95248. if (value) {
  95249. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  95250. if (!_this._gpuFrameTimeToken) {
  95251. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  95252. }
  95253. });
  95254. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  95255. if (!_this._gpuFrameTimeToken) {
  95256. return;
  95257. }
  95258. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  95259. if (time > -1) {
  95260. _this._gpuFrameTimeToken = null;
  95261. _this._gpuFrameTime.fetchNewFrame();
  95262. _this._gpuFrameTime.addCount(time, true);
  95263. }
  95264. });
  95265. }
  95266. else {
  95267. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95268. this._onBeginFrameObserver = null;
  95269. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95270. this._onEndFrameObserver = null;
  95271. }
  95272. },
  95273. enumerable: true,
  95274. configurable: true
  95275. });
  95276. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  95277. /**
  95278. * Gets the perf counter used for shader compilation time
  95279. */
  95280. get: function () {
  95281. return this._shaderCompilationTime;
  95282. },
  95283. enumerable: true,
  95284. configurable: true
  95285. });
  95286. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  95287. /**
  95288. * Gets the shader compilation time capture status
  95289. */
  95290. get: function () {
  95291. return this._captureShaderCompilationTime;
  95292. },
  95293. /**
  95294. * Enable or disable the shader compilation time capture
  95295. */
  95296. set: function (value) {
  95297. var _this = this;
  95298. if (value === this._captureShaderCompilationTime) {
  95299. return;
  95300. }
  95301. this._captureShaderCompilationTime = value;
  95302. if (value) {
  95303. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  95304. _this._shaderCompilationTime.fetchNewFrame();
  95305. _this._shaderCompilationTime.beginMonitoring();
  95306. });
  95307. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  95308. _this._shaderCompilationTime.endMonitoring();
  95309. });
  95310. }
  95311. else {
  95312. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95313. this._onBeforeShaderCompilationObserver = null;
  95314. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95315. this._onAfterShaderCompilationObserver = null;
  95316. }
  95317. },
  95318. enumerable: true,
  95319. configurable: true
  95320. });
  95321. EngineInstrumentation.prototype.dispose = function () {
  95322. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95323. this._onBeginFrameObserver = null;
  95324. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95325. this._onEndFrameObserver = null;
  95326. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95327. this._onBeforeShaderCompilationObserver = null;
  95328. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95329. this._onAfterShaderCompilationObserver = null;
  95330. this.engine = null;
  95331. };
  95332. return EngineInstrumentation;
  95333. }());
  95334. BABYLON.EngineInstrumentation = EngineInstrumentation;
  95335. })(BABYLON || (BABYLON = {}));
  95336. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  95337. var BABYLON;
  95338. (function (BABYLON) {
  95339. /**
  95340. * This class can be used to get instrumentation data from a Babylon engine
  95341. */
  95342. var SceneInstrumentation = /** @class */ (function () {
  95343. function SceneInstrumentation(scene) {
  95344. var _this = this;
  95345. this.scene = scene;
  95346. this._captureActiveMeshesEvaluationTime = false;
  95347. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  95348. this._captureRenderTargetsRenderTime = false;
  95349. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  95350. this._captureFrameTime = false;
  95351. this._frameTime = new BABYLON.PerfCounter();
  95352. this._captureRenderTime = false;
  95353. this._renderTime = new BABYLON.PerfCounter();
  95354. this._captureInterFrameTime = false;
  95355. this._interFrameTime = new BABYLON.PerfCounter();
  95356. this._captureParticlesRenderTime = false;
  95357. this._particlesRenderTime = new BABYLON.PerfCounter();
  95358. this._captureSpritesRenderTime = false;
  95359. this._spritesRenderTime = new BABYLON.PerfCounter();
  95360. this._capturePhysicsTime = false;
  95361. this._physicsTime = new BABYLON.PerfCounter();
  95362. this._captureAnimationsTime = false;
  95363. this._animationsTime = new BABYLON.PerfCounter();
  95364. // Observers
  95365. this._onBeforeActiveMeshesEvaluationObserver = null;
  95366. this._onAfterActiveMeshesEvaluationObserver = null;
  95367. this._onBeforeRenderTargetsRenderObserver = null;
  95368. this._onAfterRenderTargetsRenderObserver = null;
  95369. this._onAfterRenderObserver = null;
  95370. this._onBeforeDrawPhaseObserver = null;
  95371. this._onAfterDrawPhaseObserver = null;
  95372. this._onBeforeAnimationsObserver = null;
  95373. this._onBeforeParticlesRenderingObserver = null;
  95374. this._onAfterParticlesRenderingObserver = null;
  95375. this._onBeforeSpritesRenderingObserver = null;
  95376. this._onAfterSpritesRenderingObserver = null;
  95377. this._onBeforePhysicsObserver = null;
  95378. this._onAfterPhysicsObserver = null;
  95379. this._onAfterAnimationsObserver = null;
  95380. // Before render
  95381. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  95382. if (_this._captureActiveMeshesEvaluationTime) {
  95383. _this._activeMeshesEvaluationTime.fetchNewFrame();
  95384. }
  95385. if (_this._captureRenderTargetsRenderTime) {
  95386. _this._renderTargetsRenderTime.fetchNewFrame();
  95387. }
  95388. if (_this._captureFrameTime) {
  95389. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  95390. _this._frameTime.beginMonitoring();
  95391. }
  95392. if (_this._captureInterFrameTime) {
  95393. _this._interFrameTime.endMonitoring();
  95394. }
  95395. if (_this._captureParticlesRenderTime) {
  95396. _this._particlesRenderTime.fetchNewFrame();
  95397. }
  95398. if (_this._captureSpritesRenderTime) {
  95399. _this._spritesRenderTime.fetchNewFrame();
  95400. }
  95401. if (_this._captureAnimationsTime) {
  95402. _this._animationsTime.beginMonitoring();
  95403. }
  95404. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  95405. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  95406. });
  95407. // After render
  95408. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  95409. if (_this._captureFrameTime) {
  95410. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  95411. _this._frameTime.endMonitoring();
  95412. }
  95413. if (_this._captureRenderTime) {
  95414. _this._renderTime.endMonitoring(false);
  95415. }
  95416. if (_this._captureInterFrameTime) {
  95417. _this._interFrameTime.beginMonitoring();
  95418. }
  95419. });
  95420. }
  95421. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  95422. // Properties
  95423. /**
  95424. * Gets the perf counter used for active meshes evaluation time
  95425. */
  95426. get: function () {
  95427. return this._activeMeshesEvaluationTime;
  95428. },
  95429. enumerable: true,
  95430. configurable: true
  95431. });
  95432. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  95433. /**
  95434. * Gets the active meshes evaluation time capture status
  95435. */
  95436. get: function () {
  95437. return this._captureActiveMeshesEvaluationTime;
  95438. },
  95439. /**
  95440. * Enable or disable the active meshes evaluation time capture
  95441. */
  95442. set: function (value) {
  95443. var _this = this;
  95444. if (value === this._captureActiveMeshesEvaluationTime) {
  95445. return;
  95446. }
  95447. this._captureActiveMeshesEvaluationTime = value;
  95448. if (value) {
  95449. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  95450. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  95451. _this._activeMeshesEvaluationTime.beginMonitoring();
  95452. });
  95453. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  95454. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  95455. _this._activeMeshesEvaluationTime.endMonitoring();
  95456. });
  95457. }
  95458. else {
  95459. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95460. this._onBeforeActiveMeshesEvaluationObserver = null;
  95461. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95462. this._onAfterActiveMeshesEvaluationObserver = null;
  95463. }
  95464. },
  95465. enumerable: true,
  95466. configurable: true
  95467. });
  95468. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  95469. /**
  95470. * Gets the perf counter used for render targets render time
  95471. */
  95472. get: function () {
  95473. return this._renderTargetsRenderTime;
  95474. },
  95475. enumerable: true,
  95476. configurable: true
  95477. });
  95478. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  95479. /**
  95480. * Gets the render targets render time capture status
  95481. */
  95482. get: function () {
  95483. return this._captureRenderTargetsRenderTime;
  95484. },
  95485. /**
  95486. * Enable or disable the render targets render time capture
  95487. */
  95488. set: function (value) {
  95489. var _this = this;
  95490. if (value === this._captureRenderTargetsRenderTime) {
  95491. return;
  95492. }
  95493. this._captureRenderTargetsRenderTime = value;
  95494. if (value) {
  95495. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  95496. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  95497. _this._renderTargetsRenderTime.beginMonitoring();
  95498. });
  95499. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  95500. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  95501. _this._renderTargetsRenderTime.endMonitoring(false);
  95502. });
  95503. }
  95504. else {
  95505. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95506. this._onBeforeRenderTargetsRenderObserver = null;
  95507. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95508. this._onAfterRenderTargetsRenderObserver = null;
  95509. }
  95510. },
  95511. enumerable: true,
  95512. configurable: true
  95513. });
  95514. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  95515. /**
  95516. * Gets the perf counter used for particles render time
  95517. */
  95518. get: function () {
  95519. return this._particlesRenderTime;
  95520. },
  95521. enumerable: true,
  95522. configurable: true
  95523. });
  95524. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  95525. /**
  95526. * Gets the particles render time capture status
  95527. */
  95528. get: function () {
  95529. return this._captureParticlesRenderTime;
  95530. },
  95531. /**
  95532. * Enable or disable the particles render time capture
  95533. */
  95534. set: function (value) {
  95535. var _this = this;
  95536. if (value === this._captureParticlesRenderTime) {
  95537. return;
  95538. }
  95539. this._captureParticlesRenderTime = value;
  95540. if (value) {
  95541. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  95542. BABYLON.Tools.StartPerformanceCounter("Particles");
  95543. _this._particlesRenderTime.beginMonitoring();
  95544. });
  95545. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  95546. BABYLON.Tools.EndPerformanceCounter("Particles");
  95547. _this._particlesRenderTime.endMonitoring(false);
  95548. });
  95549. }
  95550. else {
  95551. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95552. this._onBeforeParticlesRenderingObserver = null;
  95553. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95554. this._onAfterParticlesRenderingObserver = null;
  95555. }
  95556. },
  95557. enumerable: true,
  95558. configurable: true
  95559. });
  95560. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  95561. /**
  95562. * Gets the perf counter used for sprites render time
  95563. */
  95564. get: function () {
  95565. return this._spritesRenderTime;
  95566. },
  95567. enumerable: true,
  95568. configurable: true
  95569. });
  95570. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  95571. /**
  95572. * Gets the sprites render time capture status
  95573. */
  95574. get: function () {
  95575. return this._captureSpritesRenderTime;
  95576. },
  95577. /**
  95578. * Enable or disable the sprites render time capture
  95579. */
  95580. set: function (value) {
  95581. var _this = this;
  95582. if (value === this._captureSpritesRenderTime) {
  95583. return;
  95584. }
  95585. this._captureSpritesRenderTime = value;
  95586. if (value) {
  95587. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  95588. BABYLON.Tools.StartPerformanceCounter("Sprites");
  95589. _this._spritesRenderTime.beginMonitoring();
  95590. });
  95591. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  95592. BABYLON.Tools.EndPerformanceCounter("Sprites");
  95593. _this._spritesRenderTime.endMonitoring(false);
  95594. });
  95595. }
  95596. else {
  95597. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95598. this._onBeforeSpritesRenderingObserver = null;
  95599. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95600. this._onAfterSpritesRenderingObserver = null;
  95601. }
  95602. },
  95603. enumerable: true,
  95604. configurable: true
  95605. });
  95606. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  95607. /**
  95608. * Gets the perf counter used for physics time
  95609. */
  95610. get: function () {
  95611. return this._physicsTime;
  95612. },
  95613. enumerable: true,
  95614. configurable: true
  95615. });
  95616. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  95617. /**
  95618. * Gets the physics time capture status
  95619. */
  95620. get: function () {
  95621. return this._capturePhysicsTime;
  95622. },
  95623. /**
  95624. * Enable or disable the physics time capture
  95625. */
  95626. set: function (value) {
  95627. var _this = this;
  95628. if (value === this._capturePhysicsTime) {
  95629. return;
  95630. }
  95631. this._capturePhysicsTime = value;
  95632. if (value) {
  95633. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  95634. BABYLON.Tools.StartPerformanceCounter("Physics");
  95635. _this._physicsTime.beginMonitoring();
  95636. });
  95637. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  95638. BABYLON.Tools.EndPerformanceCounter("Physics");
  95639. _this._physicsTime.endMonitoring();
  95640. });
  95641. }
  95642. else {
  95643. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95644. this._onBeforePhysicsObserver = null;
  95645. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95646. this._onAfterPhysicsObserver = null;
  95647. }
  95648. },
  95649. enumerable: true,
  95650. configurable: true
  95651. });
  95652. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  95653. /**
  95654. * Gets the perf counter used for animations time
  95655. */
  95656. get: function () {
  95657. return this._animationsTime;
  95658. },
  95659. enumerable: true,
  95660. configurable: true
  95661. });
  95662. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  95663. /**
  95664. * Gets the animations time capture status
  95665. */
  95666. get: function () {
  95667. return this._captureAnimationsTime;
  95668. },
  95669. /**
  95670. * Enable or disable the animations time capture
  95671. */
  95672. set: function (value) {
  95673. var _this = this;
  95674. if (value === this._captureAnimationsTime) {
  95675. return;
  95676. }
  95677. this._captureAnimationsTime = value;
  95678. if (value) {
  95679. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  95680. _this._animationsTime.endMonitoring();
  95681. });
  95682. }
  95683. else {
  95684. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95685. this._onAfterAnimationsObserver = null;
  95686. }
  95687. },
  95688. enumerable: true,
  95689. configurable: true
  95690. });
  95691. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  95692. /**
  95693. * Gets the perf counter used for frame time capture
  95694. */
  95695. get: function () {
  95696. return this._frameTime;
  95697. },
  95698. enumerable: true,
  95699. configurable: true
  95700. });
  95701. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  95702. /**
  95703. * Gets the frame time capture status
  95704. */
  95705. get: function () {
  95706. return this._captureFrameTime;
  95707. },
  95708. /**
  95709. * Enable or disable the frame time capture
  95710. */
  95711. set: function (value) {
  95712. this._captureFrameTime = value;
  95713. },
  95714. enumerable: true,
  95715. configurable: true
  95716. });
  95717. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  95718. /**
  95719. * Gets the perf counter used for inter-frames time capture
  95720. */
  95721. get: function () {
  95722. return this._interFrameTime;
  95723. },
  95724. enumerable: true,
  95725. configurable: true
  95726. });
  95727. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  95728. /**
  95729. * Gets the inter-frames time capture status
  95730. */
  95731. get: function () {
  95732. return this._captureInterFrameTime;
  95733. },
  95734. /**
  95735. * Enable or disable the inter-frames time capture
  95736. */
  95737. set: function (value) {
  95738. this._captureInterFrameTime = value;
  95739. },
  95740. enumerable: true,
  95741. configurable: true
  95742. });
  95743. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  95744. /**
  95745. * Gets the perf counter used for render time capture
  95746. */
  95747. get: function () {
  95748. return this._renderTime;
  95749. },
  95750. enumerable: true,
  95751. configurable: true
  95752. });
  95753. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  95754. /**
  95755. * Gets the render time capture status
  95756. */
  95757. get: function () {
  95758. return this._captureRenderTime;
  95759. },
  95760. /**
  95761. * Enable or disable the render time capture
  95762. */
  95763. set: function (value) {
  95764. var _this = this;
  95765. if (value === this._captureRenderTime) {
  95766. return;
  95767. }
  95768. this._captureRenderTime = value;
  95769. if (value) {
  95770. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  95771. _this._renderTime.beginMonitoring();
  95772. BABYLON.Tools.StartPerformanceCounter("Main render");
  95773. });
  95774. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  95775. _this._renderTime.endMonitoring(false);
  95776. BABYLON.Tools.EndPerformanceCounter("Main render");
  95777. });
  95778. }
  95779. else {
  95780. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95781. this._onBeforeDrawPhaseObserver = null;
  95782. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95783. this._onAfterDrawPhaseObserver = null;
  95784. }
  95785. },
  95786. enumerable: true,
  95787. configurable: true
  95788. });
  95789. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  95790. /**
  95791. * Gets the perf counter used for draw calls
  95792. */
  95793. get: function () {
  95794. return this.scene.getEngine()._drawCalls;
  95795. },
  95796. enumerable: true,
  95797. configurable: true
  95798. });
  95799. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  95800. /**
  95801. * Gets the perf counter used for texture collisions
  95802. */
  95803. get: function () {
  95804. return this.scene.getEngine()._textureCollisions;
  95805. },
  95806. enumerable: true,
  95807. configurable: true
  95808. });
  95809. SceneInstrumentation.prototype.dispose = function () {
  95810. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  95811. this._onAfterRenderObserver = null;
  95812. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95813. this._onBeforeActiveMeshesEvaluationObserver = null;
  95814. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95815. this._onAfterActiveMeshesEvaluationObserver = null;
  95816. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95817. this._onBeforeRenderTargetsRenderObserver = null;
  95818. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95819. this._onAfterRenderTargetsRenderObserver = null;
  95820. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  95821. this._onBeforeAnimationsObserver = null;
  95822. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95823. this._onBeforeParticlesRenderingObserver = null;
  95824. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95825. this._onAfterParticlesRenderingObserver = null;
  95826. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95827. this._onBeforeSpritesRenderingObserver = null;
  95828. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95829. this._onAfterSpritesRenderingObserver = null;
  95830. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95831. this._onBeforeDrawPhaseObserver = null;
  95832. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95833. this._onAfterDrawPhaseObserver = null;
  95834. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95835. this._onBeforePhysicsObserver = null;
  95836. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95837. this._onAfterPhysicsObserver = null;
  95838. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95839. this._onAfterAnimationsObserver = null;
  95840. this.scene = null;
  95841. };
  95842. return SceneInstrumentation;
  95843. }());
  95844. BABYLON.SceneInstrumentation = SceneInstrumentation;
  95845. })(BABYLON || (BABYLON = {}));
  95846. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  95847. var BABYLON;
  95848. (function (BABYLON) {
  95849. /**
  95850. * @hidden
  95851. **/
  95852. var _TimeToken = /** @class */ (function () {
  95853. function _TimeToken() {
  95854. this._timeElapsedQueryEnded = false;
  95855. }
  95856. return _TimeToken;
  95857. }());
  95858. BABYLON._TimeToken = _TimeToken;
  95859. })(BABYLON || (BABYLON = {}));
  95860. //# sourceMappingURL=babylon.timeToken.js.map
  95861. var BABYLON;
  95862. (function (BABYLON) {
  95863. /**
  95864. * Background material defines definition.
  95865. * @hidden Mainly internal Use
  95866. */
  95867. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  95868. __extends(BackgroundMaterialDefines, _super);
  95869. /**
  95870. * Constructor of the defines.
  95871. */
  95872. function BackgroundMaterialDefines() {
  95873. var _this = _super.call(this) || this;
  95874. /**
  95875. * True if the diffuse texture is in use.
  95876. */
  95877. _this.DIFFUSE = false;
  95878. /**
  95879. * The direct UV channel to use.
  95880. */
  95881. _this.DIFFUSEDIRECTUV = 0;
  95882. /**
  95883. * True if the diffuse texture is in gamma space.
  95884. */
  95885. _this.GAMMADIFFUSE = false;
  95886. /**
  95887. * True if the diffuse texture has opacity in the alpha channel.
  95888. */
  95889. _this.DIFFUSEHASALPHA = false;
  95890. /**
  95891. * True if you want the material to fade to transparent at grazing angle.
  95892. */
  95893. _this.OPACITYFRESNEL = false;
  95894. /**
  95895. * True if an extra blur needs to be added in the reflection.
  95896. */
  95897. _this.REFLECTIONBLUR = false;
  95898. /**
  95899. * True if you want the material to fade to reflection at grazing angle.
  95900. */
  95901. _this.REFLECTIONFRESNEL = false;
  95902. /**
  95903. * True if you want the material to falloff as far as you move away from the scene center.
  95904. */
  95905. _this.REFLECTIONFALLOFF = false;
  95906. /**
  95907. * False if the current Webgl implementation does not support the texture lod extension.
  95908. */
  95909. _this.TEXTURELODSUPPORT = false;
  95910. /**
  95911. * True to ensure the data are premultiplied.
  95912. */
  95913. _this.PREMULTIPLYALPHA = false;
  95914. /**
  95915. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  95916. */
  95917. _this.USERGBCOLOR = false;
  95918. /**
  95919. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  95920. * stays aligned with the desired configuration.
  95921. */
  95922. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  95923. /**
  95924. * True to add noise in order to reduce the banding effect.
  95925. */
  95926. _this.NOISE = false;
  95927. /**
  95928. * is the reflection texture in BGR color scheme?
  95929. * Mainly used to solve a bug in ios10 video tag
  95930. */
  95931. _this.REFLECTIONBGR = false;
  95932. _this.IMAGEPROCESSING = false;
  95933. _this.VIGNETTE = false;
  95934. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  95935. _this.VIGNETTEBLENDMODEOPAQUE = false;
  95936. _this.TONEMAPPING = false;
  95937. _this.CONTRAST = false;
  95938. _this.COLORCURVES = false;
  95939. _this.COLORGRADING = false;
  95940. _this.COLORGRADING3D = false;
  95941. _this.SAMPLER3DGREENDEPTH = false;
  95942. _this.SAMPLER3DBGRMAP = false;
  95943. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  95944. _this.EXPOSURE = false;
  95945. // Reflection.
  95946. _this.REFLECTION = false;
  95947. _this.REFLECTIONMAP_3D = false;
  95948. _this.REFLECTIONMAP_SPHERICAL = false;
  95949. _this.REFLECTIONMAP_PLANAR = false;
  95950. _this.REFLECTIONMAP_CUBIC = false;
  95951. _this.REFLECTIONMAP_PROJECTION = false;
  95952. _this.REFLECTIONMAP_SKYBOX = false;
  95953. _this.REFLECTIONMAP_EXPLICIT = false;
  95954. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  95955. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  95956. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  95957. _this.INVERTCUBICMAP = false;
  95958. _this.REFLECTIONMAP_OPPOSITEZ = false;
  95959. _this.LODINREFLECTIONALPHA = false;
  95960. _this.GAMMAREFLECTION = false;
  95961. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  95962. // Default BJS.
  95963. _this.MAINUV1 = false;
  95964. _this.MAINUV2 = false;
  95965. _this.UV1 = false;
  95966. _this.UV2 = false;
  95967. _this.CLIPPLANE = false;
  95968. _this.POINTSIZE = false;
  95969. _this.FOG = false;
  95970. _this.NORMAL = false;
  95971. _this.NUM_BONE_INFLUENCERS = 0;
  95972. _this.BonesPerMesh = 0;
  95973. _this.INSTANCES = false;
  95974. _this.SHADOWFLOAT = false;
  95975. _this.rebuild();
  95976. return _this;
  95977. }
  95978. return BackgroundMaterialDefines;
  95979. }(BABYLON.MaterialDefines));
  95980. /**
  95981. * Background material used to create an efficient environement around your scene.
  95982. */
  95983. var BackgroundMaterial = /** @class */ (function (_super) {
  95984. __extends(BackgroundMaterial, _super);
  95985. /**
  95986. * Instantiates a Background Material in the given scene
  95987. * @param name The friendly name of the material
  95988. * @param scene The scene to add the material to
  95989. */
  95990. function BackgroundMaterial(name, scene) {
  95991. var _this = _super.call(this, name, scene) || this;
  95992. /**
  95993. * Key light Color (multiply against the environement texture)
  95994. */
  95995. _this.primaryColor = BABYLON.Color3.White();
  95996. _this._primaryColorShadowLevel = 0;
  95997. _this._primaryColorHighlightLevel = 0;
  95998. /**
  95999. * Reflection Texture used in the material.
  96000. * Should be author in a specific way for the best result (refer to the documentation).
  96001. */
  96002. _this.reflectionTexture = null;
  96003. /**
  96004. * Reflection Texture level of blur.
  96005. *
  96006. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  96007. * texture twice.
  96008. */
  96009. _this.reflectionBlur = 0;
  96010. /**
  96011. * Diffuse Texture used in the material.
  96012. * Should be author in a specific way for the best result (refer to the documentation).
  96013. */
  96014. _this.diffuseTexture = null;
  96015. _this._shadowLights = null;
  96016. /**
  96017. * Specify the list of lights casting shadow on the material.
  96018. * All scene shadow lights will be included if null.
  96019. */
  96020. _this.shadowLights = null;
  96021. /**
  96022. * Helps adjusting the shadow to a softer level if required.
  96023. * 0 means black shadows and 1 means no shadows.
  96024. */
  96025. _this.shadowLevel = 0;
  96026. /**
  96027. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  96028. * It is usually zero but might be interesting to modify according to your setup.
  96029. */
  96030. _this.sceneCenter = BABYLON.Vector3.Zero();
  96031. /**
  96032. * This helps specifying that the material is falling off to the sky box at grazing angle.
  96033. * This helps ensuring a nice transition when the camera goes under the ground.
  96034. */
  96035. _this.opacityFresnel = true;
  96036. /**
  96037. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  96038. * This helps adding a mirror texture on the ground.
  96039. */
  96040. _this.reflectionFresnel = false;
  96041. /**
  96042. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  96043. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  96044. */
  96045. _this.reflectionFalloffDistance = 0.0;
  96046. /**
  96047. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  96048. */
  96049. _this.reflectionAmount = 1.0;
  96050. /**
  96051. * This specifies the weight of the reflection at grazing angle.
  96052. */
  96053. _this.reflectionReflectance0 = 0.05;
  96054. /**
  96055. * This specifies the weight of the reflection at a perpendicular point of view.
  96056. */
  96057. _this.reflectionReflectance90 = 0.5;
  96058. /**
  96059. * Helps to directly use the maps channels instead of their level.
  96060. */
  96061. _this.useRGBColor = true;
  96062. /**
  96063. * This helps reducing the banding effect that could occur on the background.
  96064. */
  96065. _this.enableNoise = false;
  96066. _this._fovMultiplier = 1.0;
  96067. /**
  96068. * Enable the FOV adjustment feature controlled by fovMultiplier.
  96069. */
  96070. _this.useEquirectangularFOV = false;
  96071. _this._maxSimultaneousLights = 4;
  96072. /**
  96073. * Number of Simultaneous lights allowed on the material.
  96074. */
  96075. _this.maxSimultaneousLights = 4;
  96076. /**
  96077. * Keep track of the image processing observer to allow dispose and replace.
  96078. */
  96079. _this._imageProcessingObserver = null;
  96080. /**
  96081. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  96082. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  96083. */
  96084. _this.switchToBGR = false;
  96085. // Temp values kept as cache in the material.
  96086. _this._renderTargets = new BABYLON.SmartArray(16);
  96087. _this._reflectionControls = BABYLON.Vector4.Zero();
  96088. _this._white = BABYLON.Color3.White();
  96089. _this._primaryShadowColor = BABYLON.Color3.Black();
  96090. _this._primaryHighlightColor = BABYLON.Color3.Black();
  96091. // Setup the default processing configuration to the scene.
  96092. _this._attachImageProcessingConfiguration(null);
  96093. _this.getRenderTargetTextures = function () {
  96094. _this._renderTargets.reset();
  96095. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  96096. _this._renderTargets.push(_this._diffuseTexture);
  96097. }
  96098. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  96099. _this._renderTargets.push(_this._reflectionTexture);
  96100. }
  96101. return _this._renderTargets;
  96102. };
  96103. return _this;
  96104. }
  96105. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  96106. /**
  96107. * Experimental Internal Use Only.
  96108. *
  96109. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  96110. * This acts as a helper to set the primary color to a more "human friendly" value.
  96111. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  96112. * output color as close as possible from the chosen value.
  96113. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  96114. * part of lighting setup.)
  96115. */
  96116. get: function () {
  96117. return this.__perceptualColor;
  96118. },
  96119. set: function (value) {
  96120. this.__perceptualColor = value;
  96121. this._computePrimaryColorFromPerceptualColor();
  96122. this._markAllSubMeshesAsLightsDirty();
  96123. },
  96124. enumerable: true,
  96125. configurable: true
  96126. });
  96127. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  96128. /**
  96129. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  96130. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  96131. */
  96132. get: function () {
  96133. return this._primaryColorShadowLevel;
  96134. },
  96135. set: function (value) {
  96136. this._primaryColorShadowLevel = value;
  96137. this._computePrimaryColors();
  96138. this._markAllSubMeshesAsLightsDirty();
  96139. },
  96140. enumerable: true,
  96141. configurable: true
  96142. });
  96143. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  96144. /**
  96145. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  96146. * The primary color is used at the level chosen to define what the white area would look.
  96147. */
  96148. get: function () {
  96149. return this._primaryColorHighlightLevel;
  96150. },
  96151. set: function (value) {
  96152. this._primaryColorHighlightLevel = value;
  96153. this._computePrimaryColors();
  96154. this._markAllSubMeshesAsLightsDirty();
  96155. },
  96156. enumerable: true,
  96157. configurable: true
  96158. });
  96159. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  96160. /**
  96161. * Sets the reflection reflectance fresnel values according to the default standard
  96162. * empirically know to work well :-)
  96163. */
  96164. set: function (value) {
  96165. var reflectionWeight = value;
  96166. if (reflectionWeight < 0.5) {
  96167. reflectionWeight = reflectionWeight * 2.0;
  96168. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  96169. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  96170. }
  96171. else {
  96172. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  96173. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  96174. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  96175. }
  96176. },
  96177. enumerable: true,
  96178. configurable: true
  96179. });
  96180. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  96181. /**
  96182. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  96183. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  96184. * Recommended to be keep at 1.0 except for special cases.
  96185. */
  96186. get: function () {
  96187. return this._fovMultiplier;
  96188. },
  96189. set: function (value) {
  96190. if (isNaN(value)) {
  96191. value = 1.0;
  96192. }
  96193. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  96194. },
  96195. enumerable: true,
  96196. configurable: true
  96197. });
  96198. /**
  96199. * Attaches a new image processing configuration to the PBR Material.
  96200. * @param configuration (if null the scene configuration will be use)
  96201. */
  96202. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  96203. var _this = this;
  96204. if (configuration === this._imageProcessingConfiguration) {
  96205. return;
  96206. }
  96207. // Detaches observer.
  96208. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96209. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96210. }
  96211. // Pick the scene configuration if needed.
  96212. if (!configuration) {
  96213. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  96214. }
  96215. else {
  96216. this._imageProcessingConfiguration = configuration;
  96217. }
  96218. // Attaches observer.
  96219. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  96220. _this._computePrimaryColorFromPerceptualColor();
  96221. _this._markAllSubMeshesAsImageProcessingDirty();
  96222. });
  96223. };
  96224. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  96225. /**
  96226. * Gets the image processing configuration used either in this material.
  96227. */
  96228. get: function () {
  96229. return this._imageProcessingConfiguration;
  96230. },
  96231. /**
  96232. * Sets the Default image processing configuration used either in the this material.
  96233. *
  96234. * If sets to null, the scene one is in use.
  96235. */
  96236. set: function (value) {
  96237. this._attachImageProcessingConfiguration(value);
  96238. // Ensure the effect will be rebuilt.
  96239. this._markAllSubMeshesAsTexturesDirty();
  96240. },
  96241. enumerable: true,
  96242. configurable: true
  96243. });
  96244. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  96245. /**
  96246. * Gets wether the color curves effect is enabled.
  96247. */
  96248. get: function () {
  96249. return this.imageProcessingConfiguration.colorCurvesEnabled;
  96250. },
  96251. /**
  96252. * Sets wether the color curves effect is enabled.
  96253. */
  96254. set: function (value) {
  96255. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  96256. },
  96257. enumerable: true,
  96258. configurable: true
  96259. });
  96260. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  96261. /**
  96262. * Gets wether the color grading effect is enabled.
  96263. */
  96264. get: function () {
  96265. return this.imageProcessingConfiguration.colorGradingEnabled;
  96266. },
  96267. /**
  96268. * Gets wether the color grading effect is enabled.
  96269. */
  96270. set: function (value) {
  96271. this.imageProcessingConfiguration.colorGradingEnabled = value;
  96272. },
  96273. enumerable: true,
  96274. configurable: true
  96275. });
  96276. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  96277. /**
  96278. * Gets wether tonemapping is enabled or not.
  96279. */
  96280. get: function () {
  96281. return this._imageProcessingConfiguration.toneMappingEnabled;
  96282. },
  96283. /**
  96284. * Sets wether tonemapping is enabled or not
  96285. */
  96286. set: function (value) {
  96287. this._imageProcessingConfiguration.toneMappingEnabled = value;
  96288. },
  96289. enumerable: true,
  96290. configurable: true
  96291. });
  96292. ;
  96293. ;
  96294. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  96295. /**
  96296. * The camera exposure used on this material.
  96297. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96298. * This corresponds to a photographic exposure.
  96299. */
  96300. get: function () {
  96301. return this._imageProcessingConfiguration.exposure;
  96302. },
  96303. /**
  96304. * The camera exposure used on this material.
  96305. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96306. * This corresponds to a photographic exposure.
  96307. */
  96308. set: function (value) {
  96309. this._imageProcessingConfiguration.exposure = value;
  96310. },
  96311. enumerable: true,
  96312. configurable: true
  96313. });
  96314. ;
  96315. ;
  96316. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  96317. /**
  96318. * Gets The camera contrast used on this material.
  96319. */
  96320. get: function () {
  96321. return this._imageProcessingConfiguration.contrast;
  96322. },
  96323. /**
  96324. * Sets The camera contrast used on this material.
  96325. */
  96326. set: function (value) {
  96327. this._imageProcessingConfiguration.contrast = value;
  96328. },
  96329. enumerable: true,
  96330. configurable: true
  96331. });
  96332. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  96333. /**
  96334. * Gets the Color Grading 2D Lookup Texture.
  96335. */
  96336. get: function () {
  96337. return this._imageProcessingConfiguration.colorGradingTexture;
  96338. },
  96339. /**
  96340. * Sets the Color Grading 2D Lookup Texture.
  96341. */
  96342. set: function (value) {
  96343. this.imageProcessingConfiguration.colorGradingTexture = value;
  96344. },
  96345. enumerable: true,
  96346. configurable: true
  96347. });
  96348. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  96349. /**
  96350. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96351. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96352. * 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;
  96353. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96354. */
  96355. get: function () {
  96356. return this.imageProcessingConfiguration.colorCurves;
  96357. },
  96358. /**
  96359. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96360. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96361. * 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;
  96362. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96363. */
  96364. set: function (value) {
  96365. this.imageProcessingConfiguration.colorCurves = value;
  96366. },
  96367. enumerable: true,
  96368. configurable: true
  96369. });
  96370. /**
  96371. * The entire material has been created in order to prevent overdraw.
  96372. * @returns false
  96373. */
  96374. BackgroundMaterial.prototype.needAlphaTesting = function () {
  96375. return true;
  96376. };
  96377. /**
  96378. * The entire material has been created in order to prevent overdraw.
  96379. * @returns true if blending is enable
  96380. */
  96381. BackgroundMaterial.prototype.needAlphaBlending = function () {
  96382. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  96383. };
  96384. /**
  96385. * Checks wether the material is ready to be rendered for a given mesh.
  96386. * @param mesh The mesh to render
  96387. * @param subMesh The submesh to check against
  96388. * @param useInstances Specify wether or not the material is used with instances
  96389. * @returns true if all the dependencies are ready (Textures, Effects...)
  96390. */
  96391. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  96392. var _this = this;
  96393. if (useInstances === void 0) { useInstances = false; }
  96394. if (subMesh.effect && this.isFrozen) {
  96395. if (this._wasPreviouslyReady) {
  96396. return true;
  96397. }
  96398. }
  96399. if (!subMesh._materialDefines) {
  96400. subMesh._materialDefines = new BackgroundMaterialDefines();
  96401. }
  96402. var scene = this.getScene();
  96403. var defines = subMesh._materialDefines;
  96404. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  96405. if (defines._renderId === scene.getRenderId()) {
  96406. return true;
  96407. }
  96408. }
  96409. var engine = scene.getEngine();
  96410. // Lights
  96411. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  96412. defines._needNormals = true;
  96413. // Textures
  96414. if (defines._areTexturesDirty) {
  96415. defines._needUVs = false;
  96416. if (scene.texturesEnabled) {
  96417. if (scene.getEngine().getCaps().textureLOD) {
  96418. defines.TEXTURELODSUPPORT = true;
  96419. }
  96420. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96421. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  96422. return false;
  96423. }
  96424. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  96425. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  96426. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  96427. defines.OPACITYFRESNEL = this._opacityFresnel;
  96428. }
  96429. else {
  96430. defines.DIFFUSE = false;
  96431. defines.DIFFUSEHASALPHA = false;
  96432. defines.GAMMADIFFUSE = false;
  96433. defines.OPACITYFRESNEL = false;
  96434. }
  96435. var reflectionTexture = this._reflectionTexture;
  96436. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96437. if (!reflectionTexture.isReadyOrNotBlocking()) {
  96438. return false;
  96439. }
  96440. defines.REFLECTION = true;
  96441. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  96442. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  96443. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  96444. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  96445. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  96446. defines.REFLECTIONBGR = this.switchToBGR;
  96447. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  96448. defines.INVERTCUBICMAP = true;
  96449. }
  96450. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  96451. switch (reflectionTexture.coordinatesMode) {
  96452. case BABYLON.Texture.EXPLICIT_MODE:
  96453. defines.REFLECTIONMAP_EXPLICIT = true;
  96454. break;
  96455. case BABYLON.Texture.PLANAR_MODE:
  96456. defines.REFLECTIONMAP_PLANAR = true;
  96457. break;
  96458. case BABYLON.Texture.PROJECTION_MODE:
  96459. defines.REFLECTIONMAP_PROJECTION = true;
  96460. break;
  96461. case BABYLON.Texture.SKYBOX_MODE:
  96462. defines.REFLECTIONMAP_SKYBOX = true;
  96463. break;
  96464. case BABYLON.Texture.SPHERICAL_MODE:
  96465. defines.REFLECTIONMAP_SPHERICAL = true;
  96466. break;
  96467. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  96468. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  96469. break;
  96470. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  96471. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  96472. break;
  96473. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  96474. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  96475. break;
  96476. case BABYLON.Texture.CUBIC_MODE:
  96477. case BABYLON.Texture.INVCUBIC_MODE:
  96478. default:
  96479. defines.REFLECTIONMAP_CUBIC = true;
  96480. break;
  96481. }
  96482. if (this.reflectionFresnel) {
  96483. defines.REFLECTIONFRESNEL = true;
  96484. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  96485. this._reflectionControls.x = this.reflectionAmount;
  96486. this._reflectionControls.y = this.reflectionReflectance0;
  96487. this._reflectionControls.z = this.reflectionReflectance90;
  96488. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  96489. }
  96490. else {
  96491. defines.REFLECTIONFRESNEL = false;
  96492. defines.REFLECTIONFALLOFF = false;
  96493. }
  96494. }
  96495. else {
  96496. defines.REFLECTION = false;
  96497. defines.REFLECTIONFRESNEL = false;
  96498. defines.REFLECTIONFALLOFF = false;
  96499. defines.REFLECTIONBLUR = false;
  96500. defines.REFLECTIONMAP_3D = false;
  96501. defines.REFLECTIONMAP_SPHERICAL = false;
  96502. defines.REFLECTIONMAP_PLANAR = false;
  96503. defines.REFLECTIONMAP_CUBIC = false;
  96504. defines.REFLECTIONMAP_PROJECTION = false;
  96505. defines.REFLECTIONMAP_SKYBOX = false;
  96506. defines.REFLECTIONMAP_EXPLICIT = false;
  96507. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  96508. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  96509. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  96510. defines.INVERTCUBICMAP = false;
  96511. defines.REFLECTIONMAP_OPPOSITEZ = false;
  96512. defines.LODINREFLECTIONALPHA = false;
  96513. defines.GAMMAREFLECTION = false;
  96514. }
  96515. }
  96516. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  96517. defines.USERGBCOLOR = this._useRGBColor;
  96518. defines.NOISE = this._enableNoise;
  96519. }
  96520. if (defines._areLightsDirty) {
  96521. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  96522. }
  96523. if (defines._areImageProcessingDirty) {
  96524. if (!this._imageProcessingConfiguration.isReady()) {
  96525. return false;
  96526. }
  96527. this._imageProcessingConfiguration.prepareDefines(defines);
  96528. }
  96529. // Misc.
  96530. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  96531. // Values that need to be evaluated on every frame
  96532. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  96533. // Attribs
  96534. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  96535. if (mesh) {
  96536. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  96537. mesh.createNormals(true);
  96538. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  96539. }
  96540. }
  96541. }
  96542. // Get correct effect
  96543. if (defines.isDirty) {
  96544. defines.markAsProcessed();
  96545. scene.resetCachedMaterial();
  96546. // Fallbacks
  96547. var fallbacks = new BABYLON.EffectFallbacks();
  96548. if (defines.FOG) {
  96549. fallbacks.addFallback(0, "FOG");
  96550. }
  96551. if (defines.POINTSIZE) {
  96552. fallbacks.addFallback(1, "POINTSIZE");
  96553. }
  96554. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  96555. if (defines.NUM_BONE_INFLUENCERS > 0) {
  96556. fallbacks.addCPUSkinningFallback(0, mesh);
  96557. }
  96558. //Attributes
  96559. var attribs = [BABYLON.VertexBuffer.PositionKind];
  96560. if (defines.NORMAL) {
  96561. attribs.push(BABYLON.VertexBuffer.NormalKind);
  96562. }
  96563. if (defines.UV1) {
  96564. attribs.push(BABYLON.VertexBuffer.UVKind);
  96565. }
  96566. if (defines.UV2) {
  96567. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96568. }
  96569. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  96570. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  96571. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  96572. "vFogInfos", "vFogColor", "pointSize",
  96573. "vClipPlane", "mBones",
  96574. "vPrimaryColor", "vPrimaryColorShadow",
  96575. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  96576. "shadowLevel", "alpha",
  96577. "vBackgroundCenter", "vReflectionControl",
  96578. "vDiffuseInfos", "diffuseMatrix",
  96579. ];
  96580. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  96581. var uniformBuffers = ["Material", "Scene"];
  96582. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  96583. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  96584. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  96585. uniformsNames: uniforms,
  96586. uniformBuffersNames: uniformBuffers,
  96587. samplers: samplers,
  96588. defines: defines,
  96589. maxSimultaneousLights: this._maxSimultaneousLights
  96590. });
  96591. var onCompiled = function (effect) {
  96592. if (_this.onCompiled) {
  96593. _this.onCompiled(effect);
  96594. }
  96595. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  96596. };
  96597. var join = defines.toString();
  96598. subMesh.setEffect(scene.getEngine().createEffect("background", {
  96599. attributes: attribs,
  96600. uniformsNames: uniforms,
  96601. uniformBuffersNames: uniformBuffers,
  96602. samplers: samplers,
  96603. defines: join,
  96604. fallbacks: fallbacks,
  96605. onCompiled: onCompiled,
  96606. onError: this.onError,
  96607. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  96608. }, engine), defines);
  96609. this.buildUniformLayout();
  96610. }
  96611. if (!subMesh.effect || !subMesh.effect.isReady()) {
  96612. return false;
  96613. }
  96614. defines._renderId = scene.getRenderId();
  96615. this._wasPreviouslyReady = true;
  96616. return true;
  96617. };
  96618. /**
  96619. * Compute the primary color according to the chosen perceptual color.
  96620. */
  96621. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  96622. if (!this.__perceptualColor) {
  96623. return;
  96624. }
  96625. this._primaryColor.copyFrom(this.__perceptualColor);
  96626. // Revert gamma space.
  96627. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  96628. // Revert image processing configuration.
  96629. if (this._imageProcessingConfiguration) {
  96630. // Revert Exposure.
  96631. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  96632. }
  96633. this._computePrimaryColors();
  96634. };
  96635. /**
  96636. * Compute the highlights and shadow colors according to their chosen levels.
  96637. */
  96638. BackgroundMaterial.prototype._computePrimaryColors = function () {
  96639. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  96640. return;
  96641. }
  96642. // Find the highlight color based on the configuration.
  96643. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  96644. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  96645. // Find the shadow color based on the configuration.
  96646. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  96647. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  96648. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  96649. };
  96650. /**
  96651. * Build the uniform buffer used in the material.
  96652. */
  96653. BackgroundMaterial.prototype.buildUniformLayout = function () {
  96654. // Order is important !
  96655. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  96656. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  96657. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  96658. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  96659. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  96660. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  96661. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  96662. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  96663. this._uniformBuffer.addUniform("pointSize", 1);
  96664. this._uniformBuffer.addUniform("shadowLevel", 1);
  96665. this._uniformBuffer.addUniform("alpha", 1);
  96666. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  96667. this._uniformBuffer.addUniform("vReflectionControl", 4);
  96668. this._uniformBuffer.create();
  96669. };
  96670. /**
  96671. * Unbind the material.
  96672. */
  96673. BackgroundMaterial.prototype.unbind = function () {
  96674. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  96675. this._uniformBuffer.setTexture("diffuseSampler", null);
  96676. }
  96677. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  96678. this._uniformBuffer.setTexture("reflectionSampler", null);
  96679. }
  96680. _super.prototype.unbind.call(this);
  96681. };
  96682. /**
  96683. * Bind only the world matrix to the material.
  96684. * @param world The world matrix to bind.
  96685. */
  96686. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  96687. this._activeEffect.setMatrix("world", world);
  96688. };
  96689. /**
  96690. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  96691. * @param world The world matrix to bind.
  96692. * @param subMesh The submesh to bind for.
  96693. */
  96694. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  96695. var scene = this.getScene();
  96696. var defines = subMesh._materialDefines;
  96697. if (!defines) {
  96698. return;
  96699. }
  96700. var effect = subMesh.effect;
  96701. if (!effect) {
  96702. return;
  96703. }
  96704. this._activeEffect = effect;
  96705. // Matrices
  96706. this.bindOnlyWorldMatrix(world);
  96707. // Bones
  96708. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  96709. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  96710. if (mustRebind) {
  96711. this._uniformBuffer.bindToEffect(effect, "Material");
  96712. this.bindViewProjection(effect);
  96713. var reflectionTexture = this._reflectionTexture;
  96714. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  96715. // Texture uniforms
  96716. if (scene.texturesEnabled) {
  96717. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96718. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  96719. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  96720. }
  96721. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96722. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  96723. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  96724. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  96725. }
  96726. }
  96727. if (this.shadowLevel > 0) {
  96728. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  96729. }
  96730. this._uniformBuffer.updateFloat("alpha", this.alpha);
  96731. // Point size
  96732. if (this.pointsCloud) {
  96733. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  96734. }
  96735. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  96736. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  96737. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  96738. }
  96739. else {
  96740. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  96741. }
  96742. }
  96743. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  96744. // Textures
  96745. if (scene.texturesEnabled) {
  96746. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96747. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  96748. }
  96749. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96750. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  96751. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96752. }
  96753. else if (!defines.REFLECTIONBLUR) {
  96754. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96755. }
  96756. else {
  96757. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  96758. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  96759. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  96760. }
  96761. if (defines.REFLECTIONFRESNEL) {
  96762. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  96763. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  96764. }
  96765. }
  96766. }
  96767. // Clip plane
  96768. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  96769. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  96770. }
  96771. if (mustRebind || !this.isFrozen) {
  96772. if (scene.lightsEnabled) {
  96773. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  96774. }
  96775. // View
  96776. this.bindView(effect);
  96777. // Fog
  96778. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  96779. // image processing
  96780. this._imageProcessingConfiguration.bind(this._activeEffect);
  96781. }
  96782. this._uniformBuffer.update();
  96783. this._afterBind(mesh);
  96784. };
  96785. /**
  96786. * Dispose the material.
  96787. * @param forceDisposeEffect Force disposal of the associated effect.
  96788. * @param forceDisposeTextures Force disposal of the associated textures.
  96789. */
  96790. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  96791. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  96792. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  96793. if (forceDisposeTextures) {
  96794. if (this.diffuseTexture) {
  96795. this.diffuseTexture.dispose();
  96796. }
  96797. if (this.reflectionTexture) {
  96798. this.reflectionTexture.dispose();
  96799. }
  96800. }
  96801. this._renderTargets.dispose();
  96802. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96803. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96804. }
  96805. _super.prototype.dispose.call(this, forceDisposeEffect);
  96806. };
  96807. /**
  96808. * Clones the material.
  96809. * @param name The cloned name.
  96810. * @returns The cloned material.
  96811. */
  96812. BackgroundMaterial.prototype.clone = function (name) {
  96813. var _this = this;
  96814. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  96815. };
  96816. /**
  96817. * Serializes the current material to its JSON representation.
  96818. * @returns The JSON representation.
  96819. */
  96820. BackgroundMaterial.prototype.serialize = function () {
  96821. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  96822. serializationObject.customType = "BABYLON.BackgroundMaterial";
  96823. return serializationObject;
  96824. };
  96825. /**
  96826. * Gets the class name of the material
  96827. * @returns "BackgroundMaterial"
  96828. */
  96829. BackgroundMaterial.prototype.getClassName = function () {
  96830. return "BackgroundMaterial";
  96831. };
  96832. /**
  96833. * Parse a JSON input to create back a background material.
  96834. * @param source The JSON data to parse
  96835. * @param scene The scene to create the parsed material in
  96836. * @param rootUrl The root url of the assets the material depends upon
  96837. * @returns the instantiated BackgroundMaterial.
  96838. */
  96839. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  96840. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  96841. };
  96842. /**
  96843. * Standard reflectance value at parallel view angle.
  96844. */
  96845. BackgroundMaterial.StandardReflectance0 = 0.05;
  96846. /**
  96847. * Standard reflectance value at grazing angle.
  96848. */
  96849. BackgroundMaterial.StandardReflectance90 = 0.5;
  96850. __decorate([
  96851. BABYLON.serializeAsColor3()
  96852. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  96853. __decorate([
  96854. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  96855. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  96856. __decorate([
  96857. BABYLON.serializeAsColor3()
  96858. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  96859. __decorate([
  96860. BABYLON.serialize()
  96861. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  96862. __decorate([
  96863. BABYLON.serialize()
  96864. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  96865. __decorate([
  96866. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  96867. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  96868. __decorate([
  96869. BABYLON.serializeAsTexture()
  96870. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  96871. __decorate([
  96872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96873. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  96874. __decorate([
  96875. BABYLON.serialize()
  96876. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  96877. __decorate([
  96878. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96879. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  96880. __decorate([
  96881. BABYLON.serializeAsTexture()
  96882. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  96883. __decorate([
  96884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96885. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  96886. __decorate([
  96887. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96888. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  96889. __decorate([
  96890. BABYLON.serialize()
  96891. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  96892. __decorate([
  96893. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96894. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  96895. __decorate([
  96896. BABYLON.serializeAsVector3()
  96897. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  96898. __decorate([
  96899. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96900. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  96901. __decorate([
  96902. BABYLON.serialize()
  96903. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  96904. __decorate([
  96905. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96906. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  96907. __decorate([
  96908. BABYLON.serialize()
  96909. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  96910. __decorate([
  96911. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96912. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  96913. __decorate([
  96914. BABYLON.serialize()
  96915. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  96916. __decorate([
  96917. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96918. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  96919. __decorate([
  96920. BABYLON.serialize()
  96921. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  96922. __decorate([
  96923. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96924. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  96925. __decorate([
  96926. BABYLON.serialize()
  96927. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  96928. __decorate([
  96929. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96930. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  96931. __decorate([
  96932. BABYLON.serialize()
  96933. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  96934. __decorate([
  96935. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96936. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  96937. __decorate([
  96938. BABYLON.serialize()
  96939. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  96940. __decorate([
  96941. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96942. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  96943. __decorate([
  96944. BABYLON.serialize()
  96945. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  96946. __decorate([
  96947. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96948. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  96949. __decorate([
  96950. BABYLON.serialize()
  96951. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  96952. __decorate([
  96953. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96954. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  96955. __decorate([
  96956. BABYLON.serializeAsImageProcessingConfiguration()
  96957. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  96958. return BackgroundMaterial;
  96959. }(BABYLON.PushMaterial));
  96960. BABYLON.BackgroundMaterial = BackgroundMaterial;
  96961. })(BABYLON || (BABYLON = {}));
  96962. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  96963. var __assign = (this && this.__assign) || Object.assign || function(t) {
  96964. for (var s, i = 1, n = arguments.length; i < n; i++) {
  96965. s = arguments[i];
  96966. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  96967. t[p] = s[p];
  96968. }
  96969. return t;
  96970. };
  96971. var BABYLON;
  96972. (function (BABYLON) {
  96973. /**
  96974. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  96975. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  96976. * It also helps with the default setup of your imageProcessing configuration.
  96977. */
  96978. var EnvironmentHelper = /** @class */ (function () {
  96979. /**
  96980. * constructor
  96981. * @param options
  96982. * @param scene The scene to add the material to
  96983. */
  96984. function EnvironmentHelper(options, scene) {
  96985. var _this = this;
  96986. this._errorHandler = function (message, exception) {
  96987. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  96988. };
  96989. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  96990. this._scene = scene;
  96991. this.onErrorObservable = new BABYLON.Observable();
  96992. this._setupBackground();
  96993. this._setupImageProcessing();
  96994. }
  96995. /**
  96996. * Creates the default options for the helper.
  96997. */
  96998. EnvironmentHelper._getDefaultOptions = function () {
  96999. return {
  97000. createGround: true,
  97001. groundSize: 15,
  97002. groundTexture: this._groundTextureCDNUrl,
  97003. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97004. groundOpacity: 0.9,
  97005. enableGroundShadow: true,
  97006. groundShadowLevel: 0.5,
  97007. enableGroundMirror: false,
  97008. groundMirrorSizeRatio: 0.3,
  97009. groundMirrorBlurKernel: 64,
  97010. groundMirrorAmount: 1,
  97011. groundMirrorFresnelWeight: 1,
  97012. groundMirrorFallOffDistance: 0,
  97013. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  97014. groundYBias: 0.00001,
  97015. createSkybox: true,
  97016. skyboxSize: 20,
  97017. skyboxTexture: this._skyboxTextureCDNUrl,
  97018. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97019. backgroundYRotation: 0,
  97020. sizeAuto: true,
  97021. rootPosition: BABYLON.Vector3.Zero(),
  97022. setupImageProcessing: true,
  97023. environmentTexture: this._environmentTextureCDNUrl,
  97024. cameraExposure: 0.8,
  97025. cameraContrast: 1.2,
  97026. toneMappingEnabled: true,
  97027. };
  97028. };
  97029. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  97030. /**
  97031. * Gets the root mesh created by the helper.
  97032. */
  97033. get: function () {
  97034. return this._rootMesh;
  97035. },
  97036. enumerable: true,
  97037. configurable: true
  97038. });
  97039. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  97040. /**
  97041. * Gets the skybox created by the helper.
  97042. */
  97043. get: function () {
  97044. return this._skybox;
  97045. },
  97046. enumerable: true,
  97047. configurable: true
  97048. });
  97049. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  97050. /**
  97051. * Gets the skybox texture created by the helper.
  97052. */
  97053. get: function () {
  97054. return this._skyboxTexture;
  97055. },
  97056. enumerable: true,
  97057. configurable: true
  97058. });
  97059. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  97060. /**
  97061. * Gets the skybox material created by the helper.
  97062. */
  97063. get: function () {
  97064. return this._skyboxMaterial;
  97065. },
  97066. enumerable: true,
  97067. configurable: true
  97068. });
  97069. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  97070. /**
  97071. * Gets the ground mesh created by the helper.
  97072. */
  97073. get: function () {
  97074. return this._ground;
  97075. },
  97076. enumerable: true,
  97077. configurable: true
  97078. });
  97079. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  97080. /**
  97081. * Gets the ground texture created by the helper.
  97082. */
  97083. get: function () {
  97084. return this._groundTexture;
  97085. },
  97086. enumerable: true,
  97087. configurable: true
  97088. });
  97089. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  97090. /**
  97091. * Gets the ground mirror created by the helper.
  97092. */
  97093. get: function () {
  97094. return this._groundMirror;
  97095. },
  97096. enumerable: true,
  97097. configurable: true
  97098. });
  97099. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  97100. /**
  97101. * Gets the ground mirror render list to helps pushing the meshes
  97102. * you wish in the ground reflection.
  97103. */
  97104. get: function () {
  97105. if (this._groundMirror) {
  97106. return this._groundMirror.renderList;
  97107. }
  97108. return null;
  97109. },
  97110. enumerable: true,
  97111. configurable: true
  97112. });
  97113. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  97114. /**
  97115. * Gets the ground material created by the helper.
  97116. */
  97117. get: function () {
  97118. return this._groundMaterial;
  97119. },
  97120. enumerable: true,
  97121. configurable: true
  97122. });
  97123. /**
  97124. * Updates the background according to the new options
  97125. * @param options
  97126. */
  97127. EnvironmentHelper.prototype.updateOptions = function (options) {
  97128. var newOptions = __assign({}, this._options, options);
  97129. if (this._ground && !newOptions.createGround) {
  97130. this._ground.dispose();
  97131. this._ground = null;
  97132. }
  97133. if (this._groundMaterial && !newOptions.createGround) {
  97134. this._groundMaterial.dispose();
  97135. this._groundMaterial = null;
  97136. }
  97137. if (this._groundTexture) {
  97138. if (this._options.groundTexture != newOptions.groundTexture) {
  97139. this._groundTexture.dispose();
  97140. this._groundTexture = null;
  97141. }
  97142. }
  97143. if (this._skybox && !newOptions.createSkybox) {
  97144. this._skybox.dispose();
  97145. this._skybox = null;
  97146. }
  97147. if (this._skyboxMaterial && !newOptions.createSkybox) {
  97148. this._skyboxMaterial.dispose();
  97149. this._skyboxMaterial = null;
  97150. }
  97151. if (this._skyboxTexture) {
  97152. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  97153. this._skyboxTexture.dispose();
  97154. this._skyboxTexture = null;
  97155. }
  97156. }
  97157. if (this._groundMirror && !newOptions.enableGroundMirror) {
  97158. this._groundMirror.dispose();
  97159. this._groundMirror = null;
  97160. }
  97161. if (this._scene.environmentTexture) {
  97162. if (this._options.environmentTexture != newOptions.environmentTexture) {
  97163. this._scene.environmentTexture.dispose();
  97164. }
  97165. }
  97166. this._options = newOptions;
  97167. this._setupBackground();
  97168. this._setupImageProcessing();
  97169. };
  97170. /**
  97171. * Sets the primary color of all the available elements.
  97172. * @param color the main color to affect to the ground and the background
  97173. */
  97174. EnvironmentHelper.prototype.setMainColor = function (color) {
  97175. if (this.groundMaterial) {
  97176. this.groundMaterial.primaryColor = color;
  97177. }
  97178. if (this.skyboxMaterial) {
  97179. this.skyboxMaterial.primaryColor = color;
  97180. }
  97181. if (this.groundMirror) {
  97182. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  97183. }
  97184. };
  97185. /**
  97186. * Setup the image processing according to the specified options.
  97187. */
  97188. EnvironmentHelper.prototype._setupImageProcessing = function () {
  97189. if (this._options.setupImageProcessing) {
  97190. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  97191. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  97192. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  97193. this._setupEnvironmentTexture();
  97194. }
  97195. };
  97196. /**
  97197. * Setup the environment texture according to the specified options.
  97198. */
  97199. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  97200. if (this._scene.environmentTexture) {
  97201. return;
  97202. }
  97203. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  97204. this._scene.environmentTexture = this._options.environmentTexture;
  97205. return;
  97206. }
  97207. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  97208. this._scene.environmentTexture = environmentTexture;
  97209. };
  97210. /**
  97211. * Setup the background according to the specified options.
  97212. */
  97213. EnvironmentHelper.prototype._setupBackground = function () {
  97214. if (!this._rootMesh) {
  97215. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  97216. }
  97217. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  97218. var sceneSize = this._getSceneSize();
  97219. if (this._options.createGround) {
  97220. this._setupGround(sceneSize);
  97221. this._setupGroundMaterial();
  97222. this._setupGroundDiffuseTexture();
  97223. if (this._options.enableGroundMirror) {
  97224. this._setupGroundMirrorTexture(sceneSize);
  97225. }
  97226. this._setupMirrorInGroundMaterial();
  97227. }
  97228. if (this._options.createSkybox) {
  97229. this._setupSkybox(sceneSize);
  97230. this._setupSkyboxMaterial();
  97231. this._setupSkyboxReflectionTexture();
  97232. }
  97233. this._rootMesh.position.x = sceneSize.rootPosition.x;
  97234. this._rootMesh.position.z = sceneSize.rootPosition.z;
  97235. this._rootMesh.position.y = sceneSize.rootPosition.y;
  97236. };
  97237. /**
  97238. * Get the scene sizes according to the setup.
  97239. */
  97240. EnvironmentHelper.prototype._getSceneSize = function () {
  97241. var _this = this;
  97242. var groundSize = this._options.groundSize;
  97243. var skyboxSize = this._options.skyboxSize;
  97244. var rootPosition = this._options.rootPosition;
  97245. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  97246. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97247. }
  97248. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  97249. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  97250. });
  97251. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  97252. if (this._options.sizeAuto) {
  97253. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  97254. this._scene.activeCamera.upperRadiusLimit) {
  97255. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  97256. skyboxSize = groundSize;
  97257. }
  97258. var sceneDiagonalLenght = sceneDiagonal.length();
  97259. if (sceneDiagonalLenght > groundSize) {
  97260. groundSize = sceneDiagonalLenght * 2;
  97261. skyboxSize = groundSize;
  97262. }
  97263. // 10 % bigger.
  97264. groundSize *= 1.1;
  97265. skyboxSize *= 1.5;
  97266. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  97267. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  97268. }
  97269. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97270. };
  97271. /**
  97272. * Setup the ground according to the specified options.
  97273. */
  97274. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  97275. var _this = this;
  97276. if (!this._ground) {
  97277. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  97278. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  97279. this._ground.parent = this._rootMesh;
  97280. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  97281. }
  97282. this._ground.receiveShadows = this._options.enableGroundShadow;
  97283. };
  97284. /**
  97285. * Setup the ground material according to the specified options.
  97286. */
  97287. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  97288. if (!this._groundMaterial) {
  97289. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  97290. }
  97291. this._groundMaterial.alpha = this._options.groundOpacity;
  97292. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  97293. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  97294. this._groundMaterial.primaryColor = this._options.groundColor;
  97295. this._groundMaterial.useRGBColor = false;
  97296. this._groundMaterial.enableNoise = true;
  97297. if (this._ground) {
  97298. this._ground.material = this._groundMaterial;
  97299. }
  97300. };
  97301. /**
  97302. * Setup the ground diffuse texture according to the specified options.
  97303. */
  97304. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  97305. if (!this._groundMaterial) {
  97306. return;
  97307. }
  97308. if (this._groundTexture) {
  97309. return;
  97310. }
  97311. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  97312. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  97313. return;
  97314. }
  97315. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97316. diffuseTexture.gammaSpace = false;
  97317. diffuseTexture.hasAlpha = true;
  97318. this._groundMaterial.diffuseTexture = diffuseTexture;
  97319. };
  97320. /**
  97321. * Setup the ground mirror texture according to the specified options.
  97322. */
  97323. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  97324. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97325. if (!this._groundMirror) {
  97326. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  97327. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  97328. this._groundMirror.anisotropicFilteringLevel = 1;
  97329. this._groundMirror.wrapU = wrapping;
  97330. this._groundMirror.wrapV = wrapping;
  97331. this._groundMirror.gammaSpace = false;
  97332. if (this._groundMirror.renderList) {
  97333. for (var i = 0; i < this._scene.meshes.length; i++) {
  97334. var mesh = this._scene.meshes[i];
  97335. if (mesh !== this._ground &&
  97336. mesh !== this._skybox &&
  97337. mesh !== this._rootMesh) {
  97338. this._groundMirror.renderList.push(mesh);
  97339. }
  97340. }
  97341. }
  97342. }
  97343. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  97344. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  97345. };
  97346. /**
  97347. * Setup the ground to receive the mirror texture.
  97348. */
  97349. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  97350. if (this._groundMaterial) {
  97351. this._groundMaterial.reflectionTexture = this._groundMirror;
  97352. this._groundMaterial.reflectionFresnel = true;
  97353. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  97354. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  97355. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  97356. }
  97357. };
  97358. /**
  97359. * Setup the skybox according to the specified options.
  97360. */
  97361. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  97362. var _this = this;
  97363. if (!this._skybox) {
  97364. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  97365. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  97366. }
  97367. this._skybox.parent = this._rootMesh;
  97368. };
  97369. /**
  97370. * Setup the skybox material according to the specified options.
  97371. */
  97372. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  97373. if (!this._skybox) {
  97374. return;
  97375. }
  97376. if (!this._skyboxMaterial) {
  97377. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  97378. }
  97379. this._skyboxMaterial.useRGBColor = false;
  97380. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  97381. this._skyboxMaterial.enableNoise = true;
  97382. this._skybox.material = this._skyboxMaterial;
  97383. };
  97384. /**
  97385. * Setup the skybox reflection texture according to the specified options.
  97386. */
  97387. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  97388. if (!this._skyboxMaterial) {
  97389. return;
  97390. }
  97391. if (this._skyboxTexture) {
  97392. return;
  97393. }
  97394. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  97395. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  97396. return;
  97397. }
  97398. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97399. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  97400. this._skyboxTexture.gammaSpace = false;
  97401. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  97402. };
  97403. /**
  97404. * Dispose all the elements created by the Helper.
  97405. */
  97406. EnvironmentHelper.prototype.dispose = function () {
  97407. if (this._groundMaterial) {
  97408. this._groundMaterial.dispose(true, true);
  97409. }
  97410. if (this._skyboxMaterial) {
  97411. this._skyboxMaterial.dispose(true, true);
  97412. }
  97413. this._rootMesh.dispose(false);
  97414. };
  97415. /**
  97416. * Default ground texture URL.
  97417. */
  97418. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  97419. /**
  97420. * Default skybox texture URL.
  97421. */
  97422. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  97423. /**
  97424. * Default environment texture URL.
  97425. */
  97426. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  97427. return EnvironmentHelper;
  97428. }());
  97429. BABYLON.EnvironmentHelper = EnvironmentHelper;
  97430. })(BABYLON || (BABYLON = {}));
  97431. //# sourceMappingURL=babylon.environmentHelper.js.map
  97432. var BABYLON;
  97433. (function (BABYLON) {
  97434. /**
  97435. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  97436. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  97437. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  97438. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  97439. */
  97440. var VideoDome = /** @class */ (function (_super) {
  97441. __extends(VideoDome, _super);
  97442. /**
  97443. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  97444. * @param name Element's name, child elements will append suffixes for their own names.
  97445. * @param urlsOrVideo
  97446. * @param options An object containing optional or exposed sub element properties:
  97447. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  97448. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  97449. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  97450. * @param options **loop=true** Automatically loop video on end.
  97451. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  97452. */
  97453. function VideoDome(name, urlsOrVideo, options, scene) {
  97454. var _this = _super.call(this, name, scene) || this;
  97455. // set defaults and manage values
  97456. name = name || "videoDome";
  97457. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  97458. options.clickToPlay = Boolean(options.clickToPlay);
  97459. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  97460. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  97461. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  97462. // create
  97463. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  97464. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  97465. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  97466. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  97467. flat: false,
  97468. radius: options.size,
  97469. subdivisions: options.resolution,
  97470. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  97471. }, scene);
  97472. // configure material
  97473. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  97474. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  97475. material.reflectionTexture = _this._videoTexture;
  97476. material.useEquirectangularFOV = true;
  97477. material.fovMultiplier = 1.0;
  97478. // configure mesh
  97479. _this._mesh.material = material;
  97480. _this._mesh.parent = _this;
  97481. // optional configuration
  97482. if (options.clickToPlay) {
  97483. scene.onPointerUp = function () {
  97484. _this._videoTexture.video.play();
  97485. };
  97486. }
  97487. return _this;
  97488. }
  97489. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  97490. /**
  97491. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  97492. * Also see the options.resolution property.
  97493. */
  97494. get: function () {
  97495. return this._material.fovMultiplier;
  97496. },
  97497. set: function (value) {
  97498. this._material.fovMultiplier = value;
  97499. },
  97500. enumerable: true,
  97501. configurable: true
  97502. });
  97503. /**
  97504. * Releases resources associated with this node.
  97505. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  97506. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  97507. */
  97508. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  97509. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  97510. this._videoTexture.dispose();
  97511. this._mesh.dispose();
  97512. this._material.dispose();
  97513. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  97514. };
  97515. return VideoDome;
  97516. }(BABYLON.Node));
  97517. BABYLON.VideoDome = VideoDome;
  97518. })(BABYLON || (BABYLON = {}));
  97519. //# sourceMappingURL=babylon.videoDome.js.map
  97520. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\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}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  97521. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  97522. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  97523. globalObject["BABYLON"] = BABYLON;
  97524. //backwards compatibility
  97525. if(typeof earcut !== 'undefined') {
  97526. globalObject["Earcut"] = {
  97527. earcut: earcut
  97528. };
  97529. }
  97530. return BABYLON;
  97531. });
  97532. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(23)))
  97533. /***/ }),
  97534. /* 1 */
  97535. /***/ (function(module, exports, __webpack_require__) {
  97536. (function (global, factory) {
  97537. true ? module.exports = factory() :
  97538. typeof define === 'function' && define.amd ? define(factory) :
  97539. (global.deepmerge = factory());
  97540. }(this, (function () { 'use strict';
  97541. var isMergeableObject = function isMergeableObject(value) {
  97542. return isNonNullObject(value)
  97543. && !isSpecial(value)
  97544. };
  97545. function isNonNullObject(value) {
  97546. return !!value && typeof value === 'object'
  97547. }
  97548. function isSpecial(value) {
  97549. var stringValue = Object.prototype.toString.call(value);
  97550. return stringValue === '[object RegExp]'
  97551. || stringValue === '[object Date]'
  97552. || isReactElement(value)
  97553. }
  97554. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  97555. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  97556. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  97557. function isReactElement(value) {
  97558. return value.$$typeof === REACT_ELEMENT_TYPE
  97559. }
  97560. function emptyTarget(val) {
  97561. return Array.isArray(val) ? [] : {}
  97562. }
  97563. function cloneUnlessOtherwiseSpecified(value, optionsArgument) {
  97564. var clone = !optionsArgument || optionsArgument.clone !== false;
  97565. return (clone && isMergeableObject(value))
  97566. ? deepmerge(emptyTarget(value), value, optionsArgument)
  97567. : value
  97568. }
  97569. function defaultArrayMerge(target, source, optionsArgument) {
  97570. return target.concat(source).map(function(element) {
  97571. return cloneUnlessOtherwiseSpecified(element, optionsArgument)
  97572. })
  97573. }
  97574. function mergeObject(target, source, optionsArgument) {
  97575. var destination = {};
  97576. if (isMergeableObject(target)) {
  97577. Object.keys(target).forEach(function(key) {
  97578. destination[key] = cloneUnlessOtherwiseSpecified(target[key], optionsArgument);
  97579. });
  97580. }
  97581. Object.keys(source).forEach(function(key) {
  97582. if (!isMergeableObject(source[key]) || !target[key]) {
  97583. destination[key] = cloneUnlessOtherwiseSpecified(source[key], optionsArgument);
  97584. } else {
  97585. destination[key] = deepmerge(target[key], source[key], optionsArgument);
  97586. }
  97587. });
  97588. return destination
  97589. }
  97590. function deepmerge(target, source, optionsArgument) {
  97591. var sourceIsArray = Array.isArray(source);
  97592. var targetIsArray = Array.isArray(target);
  97593. var options = optionsArgument || { arrayMerge: defaultArrayMerge };
  97594. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  97595. if (!sourceAndTargetTypesMatch) {
  97596. return cloneUnlessOtherwiseSpecified(source, optionsArgument)
  97597. } else if (sourceIsArray) {
  97598. var arrayMerge = options.arrayMerge || defaultArrayMerge;
  97599. return arrayMerge(target, source, optionsArgument)
  97600. } else {
  97601. return mergeObject(target, source, optionsArgument)
  97602. }
  97603. }
  97604. deepmerge.all = function deepmergeAll(array, optionsArgument) {
  97605. if (!Array.isArray(array)) {
  97606. throw new Error('first argument should be an array')
  97607. }
  97608. return array.reduce(function(prev, next) {
  97609. return deepmerge(prev, next, optionsArgument)
  97610. }, {})
  97611. };
  97612. var deepmerge_1 = deepmerge;
  97613. return deepmerge_1;
  97614. })));
  97615. /***/ }),
  97616. /* 2 */
  97617. /***/ (function(module, exports, __webpack_require__) {
  97618. "use strict";
  97619. Object.defineProperty(exports, "__esModule", { value: true });
  97620. /**
  97621. * Is the provided string a URL?
  97622. *
  97623. * @param urlToCheck the url to inspect
  97624. */
  97625. function isUrl(urlToCheck) {
  97626. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  97627. return true;
  97628. }
  97629. return false;
  97630. }
  97631. exports.isUrl = isUrl;
  97632. /**
  97633. * Convert a string from kebab-case to camelCase
  97634. * @param s string to convert
  97635. */
  97636. function kebabToCamel(s) {
  97637. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  97638. }
  97639. exports.kebabToCamel = kebabToCamel;
  97640. //https://gist.github.com/youssman/745578062609e8acac9f
  97641. /**
  97642. * Convert a string from camelCase to kebab-case
  97643. * @param str string to convert
  97644. */
  97645. function camelToKebab(str) {
  97646. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  97647. }
  97648. exports.camelToKebab = camelToKebab;
  97649. /**
  97650. * This will extend an object with configuration values.
  97651. * What it practically does it take the keys from the configuration and set them on the object.
  97652. * I the configuration is a tree, it will traverse into the tree.
  97653. * @param object the object to extend
  97654. * @param config the configuration object that will extend the object
  97655. */
  97656. function extendClassWithConfig(object, config) {
  97657. if (!config)
  97658. return;
  97659. Object.keys(config).forEach(function (key) {
  97660. if (key in object && typeof object[key] !== 'function') {
  97661. // if (typeof object[key] === 'function') return;
  97662. // if it is an object, iterate internally until reaching basic types
  97663. if (typeof object[key] === 'object') {
  97664. extendClassWithConfig(object[key], config[key]);
  97665. }
  97666. else {
  97667. if (config[key] !== undefined) {
  97668. object[key] = config[key];
  97669. }
  97670. }
  97671. }
  97672. });
  97673. }
  97674. exports.extendClassWithConfig = extendClassWithConfig;
  97675. /***/ }),
  97676. /* 3 */
  97677. /***/ (function(module, exports, __webpack_require__) {
  97678. "use strict";
  97679. Object.defineProperty(exports, "__esModule", { value: true });
  97680. var babylonjs_1 = __webpack_require__(0);
  97681. var helper_1 = __webpack_require__(2);
  97682. /**
  97683. * This is a simple HTML mapper.
  97684. * This mapper parses a single HTML element and returns the configuration from its attributes.
  97685. * it parses numbers and boolean values to the corresponding variable types.
  97686. * The following HTML element:
  97687. * <div test="1" random-flag="true" a.string.object="test"> will result in the following configuration:
  97688. *
  97689. * {
  97690. * test: 1, //a number!
  97691. * randomFlag: boolean, //camelCase and boolean
  97692. * a: {
  97693. * string: {
  97694. * object: "test" //dot-separated object levels
  97695. * }
  97696. * }
  97697. * }
  97698. */
  97699. var HTMLMapper = /** @class */ (function () {
  97700. function HTMLMapper() {
  97701. }
  97702. /**
  97703. * Map a specific element and get configuration from it
  97704. * @param element the HTML element to analyze.
  97705. */
  97706. HTMLMapper.prototype.map = function (element) {
  97707. var config = {};
  97708. var _loop_1 = function (attrIdx) {
  97709. var attr = element.attributes.item(attrIdx);
  97710. if (!attr) {
  97711. return "continue";
  97712. }
  97713. // map "object.property" to the right configuration place.
  97714. var split = attr.nodeName.split('.');
  97715. split.reduce(function (currentConfig, key, idx) {
  97716. //convert html-style to json-style
  97717. var camelKey = helper_1.kebabToCamel(key);
  97718. if (idx === split.length - 1) {
  97719. var val = attr.nodeValue; // firefox warns nodeValue is deprecated, but I found no sign of it anywhere.
  97720. if (val === "true") {
  97721. val = true;
  97722. }
  97723. else if (val === "false") {
  97724. val = false;
  97725. }
  97726. else {
  97727. var isnum = !isNaN(parseFloat(val)) && isFinite(val); ///^\d+$/.test(val);
  97728. if (isnum) {
  97729. var number = parseFloat(val);
  97730. if (!isNaN(number)) {
  97731. val = number;
  97732. }
  97733. }
  97734. }
  97735. currentConfig[camelKey] = val;
  97736. }
  97737. else {
  97738. currentConfig[camelKey] = currentConfig[camelKey] || {};
  97739. }
  97740. return currentConfig[camelKey];
  97741. }, config);
  97742. };
  97743. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  97744. _loop_1(attrIdx);
  97745. }
  97746. return config;
  97747. };
  97748. return HTMLMapper;
  97749. }());
  97750. /**
  97751. * A simple string-to-JSON mapper.
  97752. * This is the main mapper, used to analyze downloaded JSON-Configuration or JSON payload
  97753. */
  97754. var JSONMapper = /** @class */ (function () {
  97755. function JSONMapper() {
  97756. }
  97757. JSONMapper.prototype.map = function (rawSource) {
  97758. return JSON.parse(rawSource);
  97759. };
  97760. return JSONMapper;
  97761. }());
  97762. /**
  97763. * The DOM Mapper will traverse an entire DOM Tree and will load the configuration from the
  97764. * DOM elements and attributes.
  97765. */
  97766. var DOMMapper = /** @class */ (function () {
  97767. function DOMMapper() {
  97768. }
  97769. /**
  97770. * The mapping function that will convert HTML data to a viewer configuration object
  97771. * @param baseElement the baseElement from which to start traversing
  97772. * @returns a ViewerCOnfiguration object from the provided HTML Element
  97773. */
  97774. DOMMapper.prototype.map = function (baseElement) {
  97775. var htmlMapper = new HTMLMapper();
  97776. var config = htmlMapper.map(baseElement);
  97777. var traverseChildren = function (element, partConfig) {
  97778. var children = element.children;
  97779. if (children.length) {
  97780. for (var i = 0; i < children.length; ++i) {
  97781. var item = children.item(i);
  97782. // use the HTML Mapper to read configuration from a single element
  97783. var configMapped = htmlMapper.map(item);
  97784. var key = helper_1.kebabToCamel(item.nodeName.toLowerCase());
  97785. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  97786. partConfig[key] = [];
  97787. }
  97788. else {
  97789. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  97790. partConfig.push(configMapped);
  97791. }
  97792. else if (partConfig[key]) {
  97793. //exists already! probably an array
  97794. element.setAttribute('array', 'true');
  97795. var oldItem = partConfig[key];
  97796. partConfig = [oldItem, configMapped];
  97797. }
  97798. else {
  97799. partConfig[key] = configMapped;
  97800. }
  97801. }
  97802. traverseChildren(item, partConfig[key] || configMapped);
  97803. }
  97804. }
  97805. return partConfig;
  97806. };
  97807. traverseChildren(baseElement, config);
  97808. return config;
  97809. };
  97810. return DOMMapper;
  97811. }());
  97812. /**
  97813. * The MapperManager manages the different implemented mappers.
  97814. * It allows the user to register new mappers as well and use them to parse their own configuration data
  97815. */
  97816. var MapperManager = /** @class */ (function () {
  97817. function MapperManager() {
  97818. this._mappers = {
  97819. "html": new HTMLMapper(),
  97820. "json": new JSONMapper(),
  97821. "dom": new DOMMapper()
  97822. };
  97823. }
  97824. /**
  97825. * Get a specific configuration mapper.
  97826. *
  97827. * @param type the name of the mapper to load
  97828. */
  97829. MapperManager.prototype.getMapper = function (type) {
  97830. if (!this._mappers[type]) {
  97831. babylonjs_1.Tools.Error("No mapper defined for " + type);
  97832. }
  97833. return this._mappers[type] || this._mappers[MapperManager.DefaultMapper];
  97834. };
  97835. /**
  97836. * Use this functio to register your own configuration mapper.
  97837. * After a mapper is registered, it can be used to parse the specific type fo configuration to the standard ViewerConfiguration.
  97838. * @param type the name of the mapper. This will be used to define the configuration type and/or to get the mapper
  97839. * @param mapper The implemented mapper
  97840. */
  97841. MapperManager.prototype.registerMapper = function (type, mapper) {
  97842. this._mappers[type] = mapper;
  97843. };
  97844. /**
  97845. * Dispose the mapper manager and all of its mappers.
  97846. */
  97847. MapperManager.prototype.dispose = function () {
  97848. this._mappers = {};
  97849. };
  97850. /**
  97851. * The default mapper is the JSON mapper.
  97852. */
  97853. MapperManager.DefaultMapper = 'json';
  97854. return MapperManager;
  97855. }());
  97856. exports.MapperManager = MapperManager;
  97857. /**
  97858. * mapperManager is a singleton of the type MapperManager.
  97859. * The mapperManager can be disposed directly with calling mapperManager.dispose()
  97860. * or indirectly with using BabylonViewer.disposeAll()
  97861. */
  97862. exports.mapperManager = new MapperManager();
  97863. /***/ }),
  97864. /* 4 */
  97865. /***/ (function(module, exports, __webpack_require__) {
  97866. "use strict";
  97867. Object.defineProperty(exports, "__esModule", { value: true });
  97868. var babylonjs_1 = __webpack_require__(0);
  97869. /**
  97870. * Receives Telemetry events and raises events to the API
  97871. */
  97872. var TelemetryManager = /** @class */ (function () {
  97873. function TelemetryManager() {
  97874. this.onEventBroadcastedObservable = new babylonjs_1.Observable();
  97875. this._event = this._eventEnabled;
  97876. }
  97877. Object.defineProperty(TelemetryManager.prototype, "broadcast", {
  97878. /**
  97879. * Receives a telemetry event
  97880. * @param event The name of the Telemetry event
  97881. * @param details An additional value, or an object containing a list of property/value pairs
  97882. */
  97883. get: function () {
  97884. return this._event;
  97885. },
  97886. enumerable: true,
  97887. configurable: true
  97888. });
  97889. /**
  97890. * Log a Telemetry event for errors raised on the WebGL context.
  97891. * @param engine The Babylon engine with the WebGL context.
  97892. */
  97893. TelemetryManager.prototype.flushWebGLErrors = function (viewer) {
  97894. var engine = viewer.engine;
  97895. if (!engine) {
  97896. return;
  97897. }
  97898. var logErrors = true;
  97899. while (logErrors) {
  97900. var gl = engine._gl;
  97901. if (gl && gl.getError) {
  97902. var error = gl.getError();
  97903. if (error === gl.NO_ERROR) {
  97904. logErrors = false;
  97905. }
  97906. else {
  97907. this.broadcast("WebGL Error", viewer, { error: error });
  97908. }
  97909. }
  97910. else {
  97911. logErrors = false;
  97912. }
  97913. }
  97914. };
  97915. Object.defineProperty(TelemetryManager.prototype, "enable", {
  97916. /**
  97917. * Enable or disable telemetry events
  97918. * @param enabled Boolan, true if events are enabled
  97919. */
  97920. set: function (enabled) {
  97921. if (enabled) {
  97922. this._event = this._eventEnabled;
  97923. }
  97924. else {
  97925. this._event = this._eventDisabled;
  97926. }
  97927. },
  97928. enumerable: true,
  97929. configurable: true
  97930. });
  97931. /**
  97932. * Called on event when disabled, typically do nothing here
  97933. */
  97934. TelemetryManager.prototype._eventDisabled = function () {
  97935. // nothing to do
  97936. };
  97937. /**
  97938. * Called on event when enabled
  97939. * @param event - The name of the Telemetry event
  97940. * @param details An additional value, or an object containing a list of property/value pairs
  97941. */
  97942. TelemetryManager.prototype._eventEnabled = function (event, viewer, details) {
  97943. var telemetryData = {
  97944. viewer: viewer,
  97945. event: event,
  97946. session: this.session,
  97947. date: new Date(),
  97948. now: window.performance ? window.performance.now() : Date.now(),
  97949. detail: null
  97950. };
  97951. if (typeof details === "object") {
  97952. for (var attr in details) {
  97953. if (details.hasOwnProperty(attr)) {
  97954. telemetryData[attr] = details[attr];
  97955. }
  97956. }
  97957. }
  97958. else if (details) {
  97959. telemetryData.detail = details;
  97960. }
  97961. this.onEventBroadcastedObservable.notifyObservers(telemetryData);
  97962. };
  97963. Object.defineProperty(TelemetryManager.prototype, "session", {
  97964. /**
  97965. * Returns the current session ID or creates one if it doesn't exixt
  97966. * @return The current session ID
  97967. */
  97968. get: function () {
  97969. if (!this._currentSessionId) {
  97970. //String + Timestamp + Random Integer
  97971. this._currentSessionId = "SESSION_" + Date.now() + Math.floor(Math.random() * 0x10000);
  97972. }
  97973. return this._currentSessionId;
  97974. },
  97975. enumerable: true,
  97976. configurable: true
  97977. });
  97978. TelemetryManager.prototype.dispose = function () {
  97979. this.onEventBroadcastedObservable.clear();
  97980. delete this.onEventBroadcastedObservable;
  97981. };
  97982. return TelemetryManager;
  97983. }());
  97984. exports.TelemetryManager = TelemetryManager;
  97985. exports.telemetryManager = new TelemetryManager();
  97986. /***/ }),
  97987. /* 5 */
  97988. /***/ (function(module, exports, __webpack_require__) {
  97989. "use strict";
  97990. Object.defineProperty(exports, "__esModule", { value: true });
  97991. /// <reference path="../../dist/babylon.glTF2Interface.d.ts"/>
  97992. var mappers_1 = __webpack_require__(3);
  97993. exports.mapperManager = mappers_1.mapperManager;
  97994. var globals_1 = __webpack_require__(6);
  97995. exports.viewerGlobals = globals_1.viewerGlobals;
  97996. var viewerManager_1 = __webpack_require__(7);
  97997. exports.viewerManager = viewerManager_1.viewerManager;
  97998. var defaultViewer_1 = __webpack_require__(8);
  97999. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  98000. var viewer_1 = __webpack_require__(9);
  98001. exports.AbstractViewer = viewer_1.AbstractViewer;
  98002. var telemetryManager_1 = __webpack_require__(4);
  98003. exports.telemetryManager = telemetryManager_1.telemetryManager;
  98004. var modelLoader_1 = __webpack_require__(18);
  98005. exports.ModelLoader = modelLoader_1.ModelLoader;
  98006. var viewerModel_1 = __webpack_require__(20);
  98007. exports.ViewerModel = viewerModel_1.ViewerModel;
  98008. exports.ModelState = viewerModel_1.ModelState;
  98009. var modelAnimation_1 = __webpack_require__(21);
  98010. exports.AnimationPlayMode = modelAnimation_1.AnimationPlayMode;
  98011. exports.AnimationState = modelAnimation_1.AnimationState;
  98012. /**
  98013. * BabylonJS Viewer
  98014. *
  98015. * An HTML-Based viewer for 3D models, based on BabylonJS and its extensions.
  98016. */
  98017. var BABYLON = __webpack_require__(0);
  98018. exports.BABYLON = BABYLON;
  98019. // load needed modules.
  98020. __webpack_require__(19);
  98021. __webpack_require__(48);
  98022. var initializer_1 = __webpack_require__(49);
  98023. exports.InitTags = initializer_1.InitTags;
  98024. // promise polyfill, if needed!
  98025. BABYLON.PromisePolyfill.Apply();
  98026. initializer_1.initListeners();
  98027. //deprectaed, here for backwards compatibility
  98028. var disableInit = globals_1.viewerGlobals.disableInit;
  98029. exports.disableInit = disableInit;
  98030. /**
  98031. * Dispose all viewers currently registered
  98032. */
  98033. function disposeAll() {
  98034. viewerManager_1.viewerManager.dispose();
  98035. mappers_1.mapperManager.dispose();
  98036. telemetryManager_1.telemetryManager.dispose();
  98037. }
  98038. exports.disposeAll = disposeAll;
  98039. var Version = BABYLON.Engine.Version;
  98040. exports.Version = Version;
  98041. /***/ }),
  98042. /* 6 */
  98043. /***/ (function(module, exports, __webpack_require__) {
  98044. "use strict";
  98045. Object.defineProperty(exports, "__esModule", { value: true });
  98046. var ViewerGlobals = /** @class */ (function () {
  98047. function ViewerGlobals() {
  98048. this.disableInit = false;
  98049. this.disableWebGL2Support = false;
  98050. }
  98051. return ViewerGlobals;
  98052. }());
  98053. exports.ViewerGlobals = ViewerGlobals;
  98054. exports.viewerGlobals = new ViewerGlobals();
  98055. /***/ }),
  98056. /* 7 */
  98057. /***/ (function(module, exports, __webpack_require__) {
  98058. "use strict";
  98059. Object.defineProperty(exports, "__esModule", { value: true });
  98060. var babylonjs_1 = __webpack_require__(0);
  98061. /**
  98062. * The viewer manager is the container for all viewers currently registered on this page.
  98063. * It is possible to have more than one viewer on a single page.
  98064. */
  98065. var ViewerManager = /** @class */ (function () {
  98066. function ViewerManager() {
  98067. this._viewers = {};
  98068. this.onViewerAddedObservable = new babylonjs_1.Observable();
  98069. this.onViewerRemovedObservable = new babylonjs_1.Observable();
  98070. }
  98071. /**
  98072. * Adding a new viewer to the viewer manager and start tracking it.
  98073. * @param viewer the viewer to add
  98074. */
  98075. ViewerManager.prototype.addViewer = function (viewer) {
  98076. this._viewers[viewer.getBaseId()] = viewer;
  98077. this._onViewerAdded(viewer);
  98078. };
  98079. /**
  98080. * remove a viewer from the viewer manager
  98081. * @param viewer the viewer to remove
  98082. */
  98083. ViewerManager.prototype.removeViewer = function (viewer) {
  98084. var id = viewer.getBaseId();
  98085. delete this._viewers[id];
  98086. this.onViewerRemovedObservable.notifyObservers(id);
  98087. };
  98088. /**
  98089. * 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)
  98090. * @param id the id of the HTMl element (or the viewer's, if none provided)
  98091. */
  98092. ViewerManager.prototype.getViewerById = function (id) {
  98093. return this._viewers[id];
  98094. };
  98095. /**
  98096. * Get a viewer using a container element
  98097. * @param element the HTML element to search viewers associated with
  98098. */
  98099. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  98100. for (var id in this._viewers) {
  98101. if (this._viewers[id].containerElement === element) {
  98102. return this.getViewerById(id);
  98103. }
  98104. }
  98105. };
  98106. /**
  98107. * Get a promise that will fullfil when this viewer was initialized.
  98108. * Since viewer initialization and template injection is asynchronous, using the promise will guaranty that
  98109. * you will get the viewer after everything was already configured.
  98110. * @param id the viewer id to find
  98111. */
  98112. ViewerManager.prototype.getViewerPromiseById = function (id) {
  98113. var _this = this;
  98114. return new Promise(function (resolve, reject) {
  98115. var localViewer = _this.getViewerById(id);
  98116. if (localViewer) {
  98117. return resolve(localViewer);
  98118. }
  98119. var viewerFunction = function (viewer) {
  98120. if (viewer.getBaseId() === id) {
  98121. resolve(viewer);
  98122. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  98123. }
  98124. };
  98125. _this.onViewerAddedObservable.add(viewerFunction);
  98126. });
  98127. };
  98128. ViewerManager.prototype._onViewerAdded = function (viewer) {
  98129. this.onViewerAdded && this.onViewerAdded(viewer);
  98130. this.onViewerAddedObservable.notifyObservers(viewer);
  98131. };
  98132. /**
  98133. * dispose the manager and all of its associated viewers
  98134. */
  98135. ViewerManager.prototype.dispose = function () {
  98136. for (var id in this._viewers) {
  98137. this._viewers[id].dispose();
  98138. }
  98139. };
  98140. return ViewerManager;
  98141. }());
  98142. exports.ViewerManager = ViewerManager;
  98143. exports.viewerManager = new ViewerManager();
  98144. /***/ }),
  98145. /* 8 */
  98146. /***/ (function(module, exports, __webpack_require__) {
  98147. "use strict";
  98148. var __extends = (this && this.__extends) || (function () {
  98149. var extendStatics = Object.setPrototypeOf ||
  98150. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  98151. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  98152. return function (d, b) {
  98153. extendStatics(d, b);
  98154. function __() { this.constructor = d; }
  98155. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  98156. };
  98157. })();
  98158. Object.defineProperty(exports, "__esModule", { value: true });
  98159. var viewer_1 = __webpack_require__(9);
  98160. var babylonjs_1 = __webpack_require__(0);
  98161. /**
  98162. * The Default viewer is the default implementation of the AbstractViewer.
  98163. * It uses the templating system to render a new canvas and controls.
  98164. */
  98165. var DefaultViewer = /** @class */ (function (_super) {
  98166. __extends(DefaultViewer, _super);
  98167. /**
  98168. * Create a new default viewer
  98169. * @param containerElement the element in which the templates will be rendered
  98170. * @param initialConfiguration the initial configuration. Defaults to extending the default configuration
  98171. */
  98172. function DefaultViewer(containerElement, initialConfiguration) {
  98173. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  98174. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  98175. _this.containerElement = containerElement;
  98176. /**
  98177. * Toggle fullscreen of the entire viewer
  98178. */
  98179. _this.toggleFullscreen = function () {
  98180. var viewerTemplate = _this.templateManager.getTemplate('viewer');
  98181. var viewerElement = viewerTemplate && viewerTemplate.parent;
  98182. if (viewerElement) {
  98183. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  98184. if (!fullscreenElement) {
  98185. var requestFullScreen = viewerElement.requestFullscreen || viewerElement.webkitRequestFullscreen || viewerElement.msRequestFullscreen || viewerElement.mozRequestFullScreen;
  98186. requestFullScreen.call(viewerElement);
  98187. }
  98188. else {
  98189. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  98190. exitFullscreen.call(document);
  98191. }
  98192. }
  98193. };
  98194. _this._onModelLoaded = function (model) {
  98195. _this._configureTemplate(model);
  98196. // with a short timeout, making sure everything is there already.
  98197. var hideLoadingDelay = 500;
  98198. if (_this._configuration.lab && _this._configuration.lab.hideLoadingDelay !== undefined) {
  98199. hideLoadingDelay = _this._configuration.lab.hideLoadingDelay;
  98200. }
  98201. setTimeout(function () {
  98202. _this.hideLoadingScreen();
  98203. }, hideLoadingDelay);
  98204. return;
  98205. };
  98206. _this.onModelLoadedObservable.add(_this._onModelLoaded);
  98207. _this.sceneManager.onSceneInitObservable.add(function () {
  98208. // extendClassWithConfig(this.sceneManager.scene, this._configuration.scene);
  98209. return _this.sceneManager.scene;
  98210. });
  98211. _this.sceneManager.onLightsConfiguredObservable.add(function (data) {
  98212. _this._configureLights(data.newConfiguration, data.model);
  98213. });
  98214. return _this;
  98215. }
  98216. /**
  98217. * This will be executed when the templates initialize.
  98218. */
  98219. DefaultViewer.prototype._onTemplatesLoaded = function () {
  98220. var _this = this;
  98221. this.showLoadingScreen();
  98222. // navbar
  98223. this._initNavbar();
  98224. // close overlay button
  98225. var closeButton = document.getElementById('close-button');
  98226. if (closeButton) {
  98227. closeButton.addEventListener('pointerdown', function () {
  98228. _this.hideOverlayScreen();
  98229. });
  98230. }
  98231. return _super.prototype._onTemplatesLoaded.call(this);
  98232. };
  98233. DefaultViewer.prototype._initNavbar = function () {
  98234. var _this = this;
  98235. var navbar = this.templateManager.getTemplate('navBar');
  98236. if (navbar) {
  98237. var navbarHeight_1 = navbar.parent.clientHeight + 'px';
  98238. var navbarShown_1 = true;
  98239. var timeoutCancel_1 /*: number*/;
  98240. var triggerNavbar = function (show, evt) {
  98241. if (show === void 0) { show = false; }
  98242. // only left-click on no-button.
  98243. if (!navbar || evt.button > 0)
  98244. return;
  98245. // clear timeout
  98246. timeoutCancel_1 && clearTimeout(timeoutCancel_1);
  98247. // if state is the same, do nothing
  98248. if (show === navbarShown_1)
  98249. return;
  98250. //showing? simply show it!
  98251. if (show) {
  98252. navbar.parent.style.bottom = show ? '0px' : '-' + navbarHeight_1;
  98253. navbarShown_1 = show;
  98254. }
  98255. else {
  98256. var visibilityTimeout = 2000;
  98257. if (navbar.configuration.params && navbar.configuration.params.visibilityTimeout !== undefined) {
  98258. visibilityTimeout = navbar.configuration.params.visibilityTimeout;
  98259. }
  98260. // not showing? set timeout until it is removed.
  98261. timeoutCancel_1 = setTimeout(function () {
  98262. if (navbar) {
  98263. navbar.parent.style.bottom = '-' + navbarHeight_1;
  98264. }
  98265. navbarShown_1 = show;
  98266. }, visibilityTimeout);
  98267. }
  98268. };
  98269. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerout');
  98270. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, true), 'pointerdown');
  98271. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerup');
  98272. this.templateManager.eventManager.registerCallback('navBar', triggerNavbar.bind(this, true), 'pointerover');
  98273. this.templateManager.eventManager.registerCallback('navBar', this.toggleFullscreen, 'pointerdown', '#fullscreen-button');
  98274. this.templateManager.eventManager.registerCallback('navBar', function (data) {
  98275. if (data && data.event && data.event.target)
  98276. _this.sceneManager.models[0].playAnimation(data.event.target['value']);
  98277. }, 'change', '#animation-selector');
  98278. }
  98279. };
  98280. /**
  98281. * Preparing the container element to present the viewer
  98282. */
  98283. DefaultViewer.prototype._prepareContainerElement = function () {
  98284. this.containerElement.style.position = 'relative';
  98285. this.containerElement.style.display = 'flex';
  98286. };
  98287. /**
  98288. * This function will configure the templates and update them after a model was loaded
  98289. * It is mainly responsible to changing the title and subtitle etc'.
  98290. * @param model the model to be used to configure the templates by
  98291. */
  98292. DefaultViewer.prototype._configureTemplate = function (model) {
  98293. var navbar = this.templateManager.getTemplate('navBar');
  98294. if (!navbar)
  98295. return;
  98296. if (model.getAnimationNames().length > 1) {
  98297. navbar.updateParams({ animations: model.getAnimationNames() });
  98298. }
  98299. var modelConfiguration = model.configuration;
  98300. var metadataContainer = navbar.parent.querySelector('#model-metadata');
  98301. if (metadataContainer) {
  98302. if (modelConfiguration.title !== undefined) {
  98303. var element = metadataContainer.querySelector('span.model-title');
  98304. if (element) {
  98305. element.innerHTML = modelConfiguration.title;
  98306. }
  98307. }
  98308. if (modelConfiguration.subtitle !== undefined) {
  98309. var element = metadataContainer.querySelector('span.model-subtitle');
  98310. if (element) {
  98311. element.innerHTML = modelConfiguration.subtitle;
  98312. }
  98313. }
  98314. if (modelConfiguration.thumbnail !== undefined) {
  98315. metadataContainer.querySelector('.thumbnail').style.backgroundImage = "url('" + modelConfiguration.thumbnail + "')";
  98316. }
  98317. }
  98318. };
  98319. /**
  98320. * This will load a new model to the default viewer
  98321. * overriding the AbstractViewer's loadModel.
  98322. * The scene will automatically be cleared of the old models, if exist.
  98323. * @param model the configuration object (or URL) to load.
  98324. */
  98325. DefaultViewer.prototype.loadModel = function (model) {
  98326. var _this = this;
  98327. if (model === void 0) { model = this._configuration.model; }
  98328. this.showLoadingScreen();
  98329. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  98330. console.log(error);
  98331. _this.hideLoadingScreen();
  98332. _this.showOverlayScreen('error');
  98333. return Promise.reject(error);
  98334. });
  98335. };
  98336. /**
  98337. * Show the overlay and the defined sub-screen.
  98338. * Mainly used for help and errors
  98339. * @param subScreen the name of the subScreen. Those can be defined in the configuration object
  98340. */
  98341. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  98342. var _this = this;
  98343. var template = this.templateManager.getTemplate('overlay');
  98344. if (!template)
  98345. return Promise.resolve('Overlay template not found');
  98346. return template.show((function (template) {
  98347. var canvasRect = _this.containerElement.getBoundingClientRect();
  98348. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  98349. template.parent.style.display = 'flex';
  98350. template.parent.style.width = canvasRect.width + "px";
  98351. template.parent.style.height = canvasRect.height + "px";
  98352. template.parent.style.opacity = "1";
  98353. var subTemplate = _this.templateManager.getTemplate(subScreen);
  98354. if (!subTemplate) {
  98355. return Promise.reject(subScreen + ' template not found');
  98356. }
  98357. return subTemplate.show((function (template) {
  98358. template.parent.style.display = 'flex';
  98359. return Promise.resolve(template);
  98360. }));
  98361. }));
  98362. };
  98363. /**
  98364. * Hide the overlay screen.
  98365. */
  98366. DefaultViewer.prototype.hideOverlayScreen = function () {
  98367. var template = this.templateManager.getTemplate('overlay');
  98368. if (!template)
  98369. return Promise.resolve('Overlay template not found');
  98370. return template.hide((function (template) {
  98371. template.parent.style.opacity = "0";
  98372. var onTransitionEnd = function () {
  98373. template.parent.removeEventListener("transitionend", onTransitionEnd);
  98374. template.parent.style.display = 'none';
  98375. };
  98376. template.parent.addEventListener("transitionend", onTransitionEnd);
  98377. var overlays = template.parent.querySelectorAll('.overlay');
  98378. if (overlays) {
  98379. for (var i = 0; i < overlays.length; ++i) {
  98380. var htmlElement = overlays.item(i);
  98381. htmlElement.style.display = 'none';
  98382. }
  98383. }
  98384. return Promise.resolve(template);
  98385. }));
  98386. };
  98387. /**
  98388. * show the viewer (in case it was hidden)
  98389. *
  98390. * @param visibilityFunction an optional function to execute in order to show the container
  98391. */
  98392. DefaultViewer.prototype.show = function (visibilityFunction) {
  98393. var template = this.templateManager.getTemplate('main');
  98394. //not possible, but yet:
  98395. if (!template)
  98396. return Promise.reject('Main template not found');
  98397. return template.show(visibilityFunction);
  98398. };
  98399. /**
  98400. * hide the viewer (in case it is visible)
  98401. *
  98402. * @param visibilityFunction an optional function to execute in order to hide the container
  98403. */
  98404. DefaultViewer.prototype.hide = function (visibilityFunction) {
  98405. var template = this.templateManager.getTemplate('main');
  98406. //not possible, but yet:
  98407. if (!template)
  98408. return Promise.reject('Main template not found');
  98409. return template.hide(visibilityFunction);
  98410. };
  98411. /**
  98412. * Show the loading screen.
  98413. * The loading screen can be configured using the configuration object
  98414. */
  98415. DefaultViewer.prototype.showLoadingScreen = function () {
  98416. var _this = this;
  98417. var template = this.templateManager.getTemplate('loadingScreen');
  98418. if (!template)
  98419. return Promise.resolve('Loading Screen template not found');
  98420. return template.show((function (template) {
  98421. var canvasRect = _this.containerElement.getBoundingClientRect();
  98422. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  98423. template.parent.style.display = 'flex';
  98424. template.parent.style.width = canvasRect.width + "px";
  98425. template.parent.style.height = canvasRect.height + "px";
  98426. template.parent.style.opacity = "1";
  98427. // from the configuration!!!
  98428. template.parent.style.backgroundColor = "black";
  98429. return Promise.resolve(template);
  98430. }));
  98431. };
  98432. /**
  98433. * Hide the loading screen
  98434. */
  98435. DefaultViewer.prototype.hideLoadingScreen = function () {
  98436. var template = this.templateManager.getTemplate('loadingScreen');
  98437. if (!template)
  98438. return Promise.resolve('Loading Screen template not found');
  98439. return template.hide((function (template) {
  98440. template.parent.style.opacity = "0";
  98441. var onTransitionEnd = function () {
  98442. template.parent.removeEventListener("transitionend", onTransitionEnd);
  98443. template.parent.style.display = 'none';
  98444. };
  98445. template.parent.addEventListener("transitionend", onTransitionEnd);
  98446. return Promise.resolve(template);
  98447. }));
  98448. };
  98449. /**
  98450. * An extension of the light configuration of the abstract viewer.
  98451. * @param lightsConfiguration the light configuration to use
  98452. * @param model the model that will be used to configure the lights (if the lights are model-dependant)
  98453. */
  98454. DefaultViewer.prototype._configureLights = function (lightsConfiguration, model) {
  98455. var _this = this;
  98456. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  98457. // labs feature - flashlight
  98458. if (this._configuration.lab && this._configuration.lab.flashlight) {
  98459. var pointerPosition = babylonjs_1.Vector3.Zero();
  98460. var lightTarget_1;
  98461. var angle = 0.5;
  98462. var exponent = Math.PI / 2;
  98463. if (typeof this._configuration.lab.flashlight === "object") {
  98464. exponent = this._configuration.lab.flashlight.exponent || exponent;
  98465. angle = this._configuration.lab.flashlight.angle || angle;
  98466. }
  98467. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.sceneManager.scene);
  98468. if (typeof this._configuration.lab.flashlight === "object") {
  98469. flashlight.intensity = this._configuration.lab.flashlight.intensity || flashlight.intensity;
  98470. if (this._configuration.lab.flashlight.diffuse) {
  98471. flashlight.diffuse.r = this._configuration.lab.flashlight.diffuse.r;
  98472. flashlight.diffuse.g = this._configuration.lab.flashlight.diffuse.g;
  98473. flashlight.diffuse.b = this._configuration.lab.flashlight.diffuse.b;
  98474. }
  98475. if (this._configuration.lab.flashlight.specular) {
  98476. flashlight.specular.r = this._configuration.lab.flashlight.specular.r;
  98477. flashlight.specular.g = this._configuration.lab.flashlight.specular.g;
  98478. flashlight.specular.b = this._configuration.lab.flashlight.specular.b;
  98479. }
  98480. }
  98481. this.sceneManager.scene.constantlyUpdateMeshUnderPointer = true;
  98482. this.sceneManager.scene.onPointerObservable.add(function (eventData, eventState) {
  98483. if (eventData.type === 4 && eventData.pickInfo) {
  98484. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  98485. }
  98486. else {
  98487. lightTarget_1 = undefined;
  98488. }
  98489. });
  98490. var updateFlashlightFunction = function () {
  98491. if (_this.sceneManager.camera && flashlight) {
  98492. flashlight.position.copyFrom(_this.sceneManager.camera.position);
  98493. if (lightTarget_1) {
  98494. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  98495. }
  98496. }
  98497. };
  98498. this.sceneManager.scene.registerBeforeRender(updateFlashlightFunction);
  98499. this._registeredOnBeforeRenderFunctions.push(updateFlashlightFunction);
  98500. }
  98501. };
  98502. return DefaultViewer;
  98503. }(viewer_1.AbstractViewer));
  98504. exports.DefaultViewer = DefaultViewer;
  98505. /***/ }),
  98506. /* 9 */
  98507. /***/ (function(module, exports, __webpack_require__) {
  98508. "use strict";
  98509. Object.defineProperty(exports, "__esModule", { value: true });
  98510. var viewerManager_1 = __webpack_require__(7);
  98511. var sceneManager_1 = __webpack_require__(27);
  98512. var templateManager_1 = __webpack_require__(30);
  98513. var loader_1 = __webpack_require__(33);
  98514. var babylonjs_1 = __webpack_require__(0);
  98515. var deepmerge = __webpack_require__(1);
  98516. var modelLoader_1 = __webpack_require__(18);
  98517. var globals_1 = __webpack_require__(6);
  98518. var telemetryManager_1 = __webpack_require__(4);
  98519. /**
  98520. * The AbstractViewr is the center of Babylon's viewer.
  98521. * It is the basic implementation of the default viewer and is responsible of loading and showing the model and the templates
  98522. */
  98523. var AbstractViewer = /** @class */ (function () {
  98524. function AbstractViewer(containerElement, initialConfiguration) {
  98525. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  98526. var _this = this;
  98527. this.containerElement = containerElement;
  98528. /**
  98529. * A flag that controls whether or not the render loop should be executed
  98530. */
  98531. this.runRenderLoop = true;
  98532. /**
  98533. * is this viewer disposed?
  98534. */
  98535. this._isDisposed = false;
  98536. /**
  98537. * The resize function that will be registered with the window object
  98538. */
  98539. this._resize = function () {
  98540. // Only resize if Canvas is in the DOM
  98541. if (!_this.isCanvasInDOM()) {
  98542. return;
  98543. }
  98544. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  98545. return;
  98546. }
  98547. if (_this._configuration.engine && _this._configuration.engine.disableResize) {
  98548. return;
  98549. }
  98550. _this.engine.resize();
  98551. };
  98552. /**
  98553. * render loop that will be executed by the engine
  98554. */
  98555. this._render = function (force) {
  98556. if (force === void 0) { force = false; }
  98557. if (force || (_this.sceneManager.scene && _this.sceneManager.scene.activeCamera)) {
  98558. if (_this.runRenderLoop || force) {
  98559. _this.engine.performanceMonitor.enable();
  98560. _this.sceneManager.scene.render();
  98561. _this.onFrameRenderedObservable.notifyObservers(_this);
  98562. }
  98563. else {
  98564. _this.engine.performanceMonitor.disable();
  98565. // TODO - is this needed?
  98566. _this.sceneManager.scene.activeCamera && _this.sceneManager.scene.activeCamera.update();
  98567. }
  98568. }
  98569. };
  98570. // if exists, use the container id. otherwise, generate a random string.
  98571. if (containerElement.id) {
  98572. this.baseId = containerElement.id;
  98573. }
  98574. else {
  98575. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  98576. }
  98577. this.onSceneInitObservable = new babylonjs_1.Observable();
  98578. this.onEngineInitObservable = new babylonjs_1.Observable();
  98579. this.onModelLoadedObservable = new babylonjs_1.Observable();
  98580. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  98581. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  98582. this.onModelAddedObservable = new babylonjs_1.Observable();
  98583. this.onModelRemovedObservable = new babylonjs_1.Observable();
  98584. this.onInitDoneObservable = new babylonjs_1.Observable();
  98585. this.onLoaderInitObservable = new babylonjs_1.Observable();
  98586. this.onFrameRenderedObservable = new babylonjs_1.Observable();
  98587. this._registeredOnBeforeRenderFunctions = [];
  98588. this.modelLoader = new modelLoader_1.ModelLoader(this);
  98589. // add this viewer to the viewer manager
  98590. viewerManager_1.viewerManager.addViewer(this);
  98591. // create a new template manager. TODO - singleton?
  98592. this.templateManager = new templateManager_1.TemplateManager(containerElement);
  98593. this.sceneManager = new sceneManager_1.SceneManager(this);
  98594. this._prepareContainerElement();
  98595. // extend the configuration
  98596. this._configurationLoader = new loader_1.ConfigurationLoader();
  98597. this._configurationLoader.loadConfiguration(initialConfiguration, function (configuration) {
  98598. _this._configuration = deepmerge(_this._configuration || {}, configuration);
  98599. if (_this._configuration.observers) {
  98600. _this._configureObservers(_this._configuration.observers);
  98601. }
  98602. if (_this._configuration.loaderPlugins) {
  98603. // TODO should plugins be removed?
  98604. Object.keys(_this._configuration.loaderPlugins).forEach((function (name) {
  98605. if (_this._configuration.loaderPlugins && _this._configuration.loaderPlugins[name]) {
  98606. _this.modelLoader.addPlugin(name);
  98607. }
  98608. }));
  98609. }
  98610. // initialize the templates
  98611. var templateConfiguration = _this._configuration.templates || {};
  98612. _this.templateManager.initTemplate(templateConfiguration);
  98613. // when done, execute onTemplatesLoaded()
  98614. _this.templateManager.onAllLoaded.add(function () {
  98615. var canvas = _this.templateManager.getCanvas();
  98616. if (canvas) {
  98617. _this._canvas = canvas;
  98618. }
  98619. _this._onTemplateLoaded();
  98620. });
  98621. });
  98622. this.onModelLoadedObservable.add(function (model) {
  98623. _this.updateConfiguration(_this._configuration, model);
  98624. });
  98625. this.onInitDoneObservable.add(function () {
  98626. _this._isInit = true;
  98627. _this.engine.runRenderLoop(_this._render);
  98628. });
  98629. }
  98630. Object.defineProperty(AbstractViewer.prototype, "canvas", {
  98631. /**
  98632. * The (single) canvas of this viewer
  98633. */
  98634. get: function () {
  98635. return this._canvas;
  98636. },
  98637. enumerable: true,
  98638. configurable: true
  98639. });
  98640. /**
  98641. * get the baseId of this viewer
  98642. */
  98643. AbstractViewer.prototype.getBaseId = function () {
  98644. return this.baseId;
  98645. };
  98646. /**
  98647. * Do we have a canvas to render on, and is it a part of the scene
  98648. */
  98649. AbstractViewer.prototype.isCanvasInDOM = function () {
  98650. return !!this._canvas && !!this._canvas.parentElement;
  98651. };
  98652. Object.defineProperty(AbstractViewer.prototype, "renderInBackground", {
  98653. /**
  98654. * Is the engine currently set to rende even when the page is in background
  98655. */
  98656. get: function () {
  98657. return this.engine.renderEvenInBackground;
  98658. },
  98659. /**
  98660. * Set the viewer's background rendering flag.
  98661. */
  98662. set: function (value) {
  98663. this.engine.renderEvenInBackground = value;
  98664. },
  98665. enumerable: true,
  98666. configurable: true
  98667. });
  98668. Object.defineProperty(AbstractViewer.prototype, "configuration", {
  98669. /**
  98670. * Get the configuration object. This is a reference only.
  98671. * The configuration can ONLY be updated using the updateConfiguration function.
  98672. * changing this object will have no direct effect on the scene.
  98673. */
  98674. get: function () {
  98675. return this._configuration;
  98676. },
  98677. enumerable: true,
  98678. configurable: true
  98679. });
  98680. /**
  98681. * force resizing the engine.
  98682. */
  98683. AbstractViewer.prototype.forceResize = function () {
  98684. this._resize();
  98685. };
  98686. /**
  98687. * Force a single render loop execution.
  98688. */
  98689. AbstractViewer.prototype.forceRender = function () {
  98690. this._render(true);
  98691. };
  98692. /**
  98693. * Takes a screenshot of the scene and returns it as a base64 encoded png.
  98694. * @param callback optional callback that will be triggered when screenshot is done.
  98695. * @param width Optional screenshot width (default to 512).
  98696. * @param height Optional screenshot height (default to 512).
  98697. * @returns a promise with the screenshot data
  98698. */
  98699. AbstractViewer.prototype.takeScreenshot = function (callback, width, height) {
  98700. var _this = this;
  98701. if (width === void 0) { width = 0; }
  98702. if (height === void 0) { height = 0; }
  98703. width = width || this.canvas.clientWidth;
  98704. height = height || this.canvas.clientHeight;
  98705. // Create the screenshot
  98706. return new Promise(function (resolve, reject) {
  98707. try {
  98708. BABYLON.Tools.CreateScreenshot(_this.engine, _this.sceneManager.camera, { width: width, height: height }, function (data) {
  98709. if (callback) {
  98710. callback(data);
  98711. }
  98712. resolve(data);
  98713. });
  98714. }
  98715. catch (e) {
  98716. reject(e);
  98717. }
  98718. });
  98719. };
  98720. /**
  98721. * Update the current viewer configuration with new values.
  98722. * Only provided information will be updated, old configuration values will be kept.
  98723. * If this.configuration was manually changed, you can trigger this function with no parameters,
  98724. * and the entire configuration will be updated.
  98725. * @param newConfiguration
  98726. */
  98727. AbstractViewer.prototype.updateConfiguration = function (newConfiguration, mode) {
  98728. var _this = this;
  98729. if (newConfiguration === void 0) { newConfiguration = this._configuration; }
  98730. // update this.configuration with the new data
  98731. this._configuration = deepmerge(this._configuration || {}, newConfiguration);
  98732. this.sceneManager.updateConfiguration(newConfiguration, this._configuration, mode);
  98733. // observers in configuration
  98734. if (newConfiguration.observers) {
  98735. this._configureObservers(newConfiguration.observers);
  98736. }
  98737. if (newConfiguration.loaderPlugins) {
  98738. // TODO should plugins be removed?
  98739. Object.keys(newConfiguration.loaderPlugins).forEach((function (name) {
  98740. if (newConfiguration.loaderPlugins && newConfiguration.loaderPlugins[name]) {
  98741. _this.modelLoader.addPlugin(name);
  98742. }
  98743. }));
  98744. }
  98745. };
  98746. /**
  98747. * this is used to register native functions using the configuration object.
  98748. * This will configure the observers.
  98749. * @param observersConfiguration observers configuration
  98750. */
  98751. AbstractViewer.prototype._configureObservers = function (observersConfiguration) {
  98752. if (observersConfiguration.onEngineInit) {
  98753. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  98754. }
  98755. else {
  98756. if (observersConfiguration.onEngineInit === '' && this._configuration.observers && this._configuration.observers.onEngineInit) {
  98757. this.onEngineInitObservable.removeCallback(window[this._configuration.observers.onEngineInit]);
  98758. }
  98759. }
  98760. if (observersConfiguration.onSceneInit) {
  98761. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  98762. }
  98763. else {
  98764. if (observersConfiguration.onSceneInit === '' && this._configuration.observers && this._configuration.observers.onSceneInit) {
  98765. this.onSceneInitObservable.removeCallback(window[this._configuration.observers.onSceneInit]);
  98766. }
  98767. }
  98768. if (observersConfiguration.onModelLoaded) {
  98769. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  98770. }
  98771. else {
  98772. if (observersConfiguration.onModelLoaded === '' && this._configuration.observers && this._configuration.observers.onModelLoaded) {
  98773. this.onModelLoadedObservable.removeCallback(window[this._configuration.observers.onModelLoaded]);
  98774. }
  98775. }
  98776. };
  98777. /**
  98778. * Dispoe the entire viewer including the scene and the engine
  98779. */
  98780. AbstractViewer.prototype.dispose = function () {
  98781. if (this._isDisposed) {
  98782. return;
  98783. }
  98784. window.removeEventListener('resize', this._resize);
  98785. //observers
  98786. this.onEngineInitObservable.clear();
  98787. delete this.onEngineInitObservable;
  98788. this.onInitDoneObservable.clear();
  98789. delete this.onInitDoneObservable;
  98790. this.onLoaderInitObservable.clear();
  98791. delete this.onLoaderInitObservable;
  98792. this.onModelLoadedObservable.clear();
  98793. delete this.onModelLoadedObservable;
  98794. this.onModelLoadErrorObservable.clear();
  98795. delete this.onModelLoadErrorObservable;
  98796. this.onModelLoadProgressObservable.clear();
  98797. delete this.onModelLoadProgressObservable;
  98798. this.onSceneInitObservable.clear();
  98799. delete this.onSceneInitObservable;
  98800. this.onFrameRenderedObservable.clear();
  98801. delete this.onFrameRenderedObservable;
  98802. if (this.sceneManager.scene.activeCamera) {
  98803. this.sceneManager.scene.activeCamera.detachControl(this.canvas);
  98804. }
  98805. this._fpsTimeout && clearTimeout(this._fpsTimeout);
  98806. this.sceneManager.dispose();
  98807. this.modelLoader.dispose();
  98808. this.engine.dispose();
  98809. this.templateManager.dispose();
  98810. viewerManager_1.viewerManager.removeViewer(this);
  98811. this._isDisposed = true;
  98812. };
  98813. /**
  98814. * This function will execute when the HTML templates finished initializing.
  98815. * It should initialize the engine and continue execution.
  98816. *
  98817. * @returns {Promise<AbstractViewer>} The viewer object will be returned after the object was loaded.
  98818. */
  98819. AbstractViewer.prototype._onTemplatesLoaded = function () {
  98820. return Promise.resolve(this);
  98821. };
  98822. /**
  98823. * This will force the creation of an engine and a scene.
  98824. * It will also load a model if preconfigured.
  98825. * But first - it will load the extendible onTemplateLoaded()!
  98826. */
  98827. AbstractViewer.prototype._onTemplateLoaded = function () {
  98828. var _this = this;
  98829. return this._onTemplatesLoaded().then(function () {
  98830. var autoLoad = typeof _this._configuration.model === 'string' || (_this._configuration.model && _this._configuration.model.url);
  98831. return _this._initEngine().then(function (engine) {
  98832. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  98833. }).then(function () {
  98834. _this._initTelemetryEvents();
  98835. if (autoLoad) {
  98836. return _this.loadModel(_this._configuration.model).catch(function (e) { }).then(function () { return _this.sceneManager.scene; });
  98837. }
  98838. else {
  98839. return _this.sceneManager.scene || _this.sceneManager.initScene(_this._configuration.scene);
  98840. }
  98841. }).then(function (scene) {
  98842. if (!autoLoad) {
  98843. _this.updateConfiguration();
  98844. }
  98845. return _this.onSceneInitObservable.notifyObserversWithPromise(scene);
  98846. }).then(function () {
  98847. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  98848. }).catch(function (e) {
  98849. babylonjs_1.Tools.Warn(e.toString());
  98850. return _this;
  98851. });
  98852. });
  98853. };
  98854. /**
  98855. * Initialize the engine. Retruns a promise in case async calls are needed.
  98856. *
  98857. * @protected
  98858. * @returns {Promise<Engine>}
  98859. * @memberof Viewer
  98860. */
  98861. AbstractViewer.prototype._initEngine = function () {
  98862. // init custom shaders
  98863. this._injectCustomShaders();
  98864. var canvasElement = this.templateManager.getCanvas();
  98865. if (!canvasElement) {
  98866. return Promise.reject('Canvas element not found!');
  98867. }
  98868. var config = this._configuration.engine || {};
  98869. // TDO enable further configuration
  98870. // check for webgl2 support, force-disable if needed.
  98871. if (globals_1.viewerGlobals.disableWebGL2Support) {
  98872. config.engineOptions = config.engineOptions || {};
  98873. config.engineOptions.disableWebGL2Support = true;
  98874. }
  98875. this.engine = new babylonjs_1.Engine(canvasElement, !!config.antialiasing, config.engineOptions);
  98876. // Disable manifest checking
  98877. babylonjs_1.Database.IDBStorageEnabled = false;
  98878. if (!config.disableResize) {
  98879. window.addEventListener('resize', this._resize);
  98880. }
  98881. if (this._configuration.engine && this._configuration.engine.adaptiveQuality) {
  98882. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  98883. this.engine.setHardwareScalingLevel(scale);
  98884. }
  98885. return Promise.resolve(this.engine);
  98886. };
  98887. /**
  98888. * Initialize a model loading. The returns object (a ViewerModel object) will be loaded in the background.
  98889. * The difference between this and loadModel is that loadModel will fulfill the promise when the model finished loading.
  98890. *
  98891. * @param modelConfig model configuration to use when loading the model.
  98892. * @param clearScene should the scene be cleared before loading this model
  98893. * @returns a ViewerModel object that is not yet fully loaded.
  98894. */
  98895. AbstractViewer.prototype.initModel = function (modelConfig, clearScene) {
  98896. var _this = this;
  98897. if (clearScene === void 0) { clearScene = true; }
  98898. var modelUrl = (typeof modelConfig === 'string') ? modelConfig : modelConfig.url;
  98899. if (!modelUrl) {
  98900. throw new Error("no model url provided");
  98901. }
  98902. if (clearScene) {
  98903. }
  98904. var configuration;
  98905. if (typeof modelConfig === 'string') {
  98906. configuration = {
  98907. url: modelConfig
  98908. };
  98909. }
  98910. else {
  98911. configuration = modelConfig;
  98912. }
  98913. //merge the configuration for future models:
  98914. if (this._configuration.model && typeof this._configuration.model === 'object') {
  98915. deepmerge(this._configuration.model, configuration);
  98916. }
  98917. else {
  98918. this._configuration.model = configuration;
  98919. }
  98920. this._isLoading = true;
  98921. var model = this.modelLoader.load(configuration);
  98922. this.lastUsedLoader = model.loader;
  98923. model.onLoadErrorObservable.add(function (errorObject) {
  98924. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject);
  98925. });
  98926. model.onLoadProgressObservable.add(function (progressEvent) {
  98927. _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  98928. });
  98929. this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader);
  98930. model.onLoadedObservable.add(function () {
  98931. _this._isLoading = false;
  98932. });
  98933. return model;
  98934. };
  98935. /**
  98936. * load a model using the provided configuration
  98937. *
  98938. * @param modelConfig the model configuration or URL to load.
  98939. * @param clearScene Should the scene be cleared before loading the model
  98940. * @returns a Promise the fulfills when the model finished loading successfully.
  98941. */
  98942. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  98943. var _this = this;
  98944. if (clearScene === void 0) { clearScene = true; }
  98945. if (this._isLoading) {
  98946. // We can decide here whether or not to cancel the lst load, but the developer can do that.
  98947. return Promise.reject("another model is curently being loaded.");
  98948. }
  98949. return Promise.resolve(this.sceneManager.scene).then(function (scene) {
  98950. if (!scene)
  98951. return _this.sceneManager.initScene(_this._configuration.scene, _this._configuration.optimizer);
  98952. return scene;
  98953. }).then(function () {
  98954. var model = _this.initModel(modelConfig, clearScene);
  98955. return new Promise(function (resolve, reject) {
  98956. // at this point, configuration.model is an object, not a string
  98957. model.onLoadedObservable.add(function () {
  98958. resolve(model);
  98959. });
  98960. model.onLoadErrorObservable.add(function (error) {
  98961. reject(error);
  98962. });
  98963. });
  98964. });
  98965. };
  98966. AbstractViewer.prototype._initTelemetryEvents = function () {
  98967. var _this = this;
  98968. telemetryManager_1.telemetryManager.broadcast("Engine Capabilities", this, this.engine.getCaps());
  98969. telemetryManager_1.telemetryManager.broadcast("Platform Details", this, {
  98970. userAgent: navigator.userAgent,
  98971. platform: navigator.platform
  98972. });
  98973. telemetryManager_1.telemetryManager.flushWebGLErrors(this);
  98974. var trackFPS = function () {
  98975. telemetryManager_1.telemetryManager.broadcast("Current FPS", _this, { fps: _this.engine.getFps() });
  98976. };
  98977. trackFPS();
  98978. // Track the FPS again after 60 seconds
  98979. this._fpsTimeout = window.setTimeout(trackFPS, 60 * 1000);
  98980. };
  98981. /**
  98982. * Injects all the spectre shader in the babylon shader store
  98983. */
  98984. AbstractViewer.prototype._injectCustomShaders = function () {
  98985. var customShaders = this._configuration.customShaders;
  98986. // Inject all the spectre shader in the babylon shader store.
  98987. if (!customShaders) {
  98988. return;
  98989. }
  98990. if (customShaders.shaders) {
  98991. Object.keys(customShaders.shaders).forEach(function (key) {
  98992. // typescript considers a callback "unsafe", so... '!'
  98993. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  98994. });
  98995. }
  98996. if (customShaders.includes) {
  98997. Object.keys(customShaders.includes).forEach(function (key) {
  98998. // typescript considers a callback "unsafe", so... '!'
  98999. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  99000. });
  99001. }
  99002. };
  99003. return AbstractViewer;
  99004. }());
  99005. exports.AbstractViewer = AbstractViewer;
  99006. /***/ }),
  99007. /* 10 */
  99008. /***/ (function(module, exports, __webpack_require__) {
  99009. "use strict";
  99010. Object.defineProperty(exports, "__esModule", { value: true });
  99011. /**
  99012. * WebGL Pixel Formats
  99013. */
  99014. var PixelFormat;
  99015. (function (PixelFormat) {
  99016. PixelFormat[PixelFormat["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT";
  99017. PixelFormat[PixelFormat["ALPHA"] = 6406] = "ALPHA";
  99018. PixelFormat[PixelFormat["RGB"] = 6407] = "RGB";
  99019. PixelFormat[PixelFormat["RGBA"] = 6408] = "RGBA";
  99020. PixelFormat[PixelFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  99021. PixelFormat[PixelFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  99022. })(PixelFormat = exports.PixelFormat || (exports.PixelFormat = {}));
  99023. /**
  99024. * WebGL Pixel Types
  99025. */
  99026. var PixelType;
  99027. (function (PixelType) {
  99028. PixelType[PixelType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  99029. PixelType[PixelType["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4";
  99030. PixelType[PixelType["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1";
  99031. PixelType[PixelType["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5";
  99032. })(PixelType = exports.PixelType || (exports.PixelType = {}));
  99033. /**
  99034. * WebGL Texture Magnification Filter
  99035. */
  99036. var TextureMagFilter;
  99037. (function (TextureMagFilter) {
  99038. TextureMagFilter[TextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  99039. TextureMagFilter[TextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  99040. })(TextureMagFilter = exports.TextureMagFilter || (exports.TextureMagFilter = {}));
  99041. /**
  99042. * WebGL Texture Minification Filter
  99043. */
  99044. var TextureMinFilter;
  99045. (function (TextureMinFilter) {
  99046. TextureMinFilter[TextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  99047. TextureMinFilter[TextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  99048. TextureMinFilter[TextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  99049. TextureMinFilter[TextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  99050. TextureMinFilter[TextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  99051. TextureMinFilter[TextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  99052. })(TextureMinFilter = exports.TextureMinFilter || (exports.TextureMinFilter = {}));
  99053. /**
  99054. * WebGL Texture Wrap Modes
  99055. */
  99056. var TextureWrapMode;
  99057. (function (TextureWrapMode) {
  99058. TextureWrapMode[TextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  99059. TextureWrapMode[TextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  99060. TextureWrapMode[TextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  99061. })(TextureWrapMode = exports.TextureWrapMode || (exports.TextureWrapMode = {}));
  99062. /**
  99063. * A minimal WebGL cubemap descriptor
  99064. */
  99065. var TextureCube = /** @class */ (function () {
  99066. /**
  99067. * constructor
  99068. * @param internalFormat WebGL pixel format for the texture on the GPU
  99069. * @param type WebGL pixel type of the supplied data and texture on the GPU
  99070. * @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
  99071. */
  99072. function TextureCube(internalFormat, type, source) {
  99073. if (source === void 0) { source = []; }
  99074. this.internalFormat = internalFormat;
  99075. this.type = type;
  99076. this.source = source;
  99077. }
  99078. Object.defineProperty(TextureCube.prototype, "Width", {
  99079. /**
  99080. * Returns the width of a face of the texture or 0 if not available
  99081. */
  99082. get: function () {
  99083. return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].width : 0;
  99084. },
  99085. enumerable: true,
  99086. configurable: true
  99087. });
  99088. Object.defineProperty(TextureCube.prototype, "Height", {
  99089. /**
  99090. * Returns the height of a face of the texture or 0 if not available
  99091. */
  99092. get: function () {
  99093. return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].height : 0;
  99094. },
  99095. enumerable: true,
  99096. configurable: true
  99097. });
  99098. return TextureCube;
  99099. }());
  99100. exports.TextureCube = TextureCube;
  99101. /**
  99102. * A static class providing methods to aid working with Bablyon textures.
  99103. */
  99104. var TextureUtils = /** @class */ (function () {
  99105. function TextureUtils() {
  99106. }
  99107. /**
  99108. * Returns a BabylonCubeTexture instance from a Spectre texture cube, subject to sampling parameters.
  99109. * If such a texture has already been requested in the past, this texture will be returned, otherwise a new one will be created.
  99110. * The advantage of this is to enable working with texture objects without the need to initialize on the GPU until desired.
  99111. * @param scene A Babylon Scene instance
  99112. * @param textureCube A Spectre TextureCube object
  99113. * @param parameters WebGL texture sampling parameters
  99114. * @param automaticMipmaps Pass true to enable automatic mipmap generation where possible (requires power of images)
  99115. * @param environment Specifies that the texture will be used as an environment
  99116. * @param singleLod Specifies that the texture will be a singleLod (for environment)
  99117. * @return Babylon cube texture
  99118. */
  99119. TextureUtils.GetBabylonCubeTexture = function (scene, textureCube, automaticMipmaps, environment, singleLod) {
  99120. if (environment === void 0) { environment = false; }
  99121. if (singleLod === void 0) { singleLod = false; }
  99122. if (!textureCube)
  99123. throw new Error("no texture cube provided");
  99124. var parameters;
  99125. if (environment) {
  99126. parameters = singleLod ? TextureUtils._EnvironmentSingleMipSampling : TextureUtils._EnvironmentSampling;
  99127. }
  99128. else {
  99129. parameters = {
  99130. magFilter: 9728 /* NEAREST */,
  99131. minFilter: 9728 /* NEAREST */,
  99132. wrapS: 33071 /* CLAMP_TO_EDGE */,
  99133. wrapT: 33071 /* CLAMP_TO_EDGE */
  99134. };
  99135. }
  99136. var key = TextureUtils.BabylonTextureKeyPrefix + parameters.magFilter + '' + parameters.minFilter + '' + parameters.wrapS + '' + parameters.wrapT;
  99137. var babylonTexture = textureCube[key];
  99138. if (!babylonTexture) {
  99139. //initialize babylon texture
  99140. babylonTexture = new BABYLON.CubeTexture('', scene);
  99141. if (environment) {
  99142. babylonTexture.lodGenerationOffset = TextureUtils.EnvironmentLODOffset;
  99143. babylonTexture.lodGenerationScale = TextureUtils.EnvironmentLODScale;
  99144. }
  99145. babylonTexture.gammaSpace = false;
  99146. var internalTexture_1 = new BABYLON.InternalTexture(scene.getEngine(), BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  99147. var glTexture_1 = internalTexture_1._webGLTexture;
  99148. //babylon properties
  99149. internalTexture_1.isCube = true;
  99150. internalTexture_1.generateMipMaps = false;
  99151. babylonTexture._texture = internalTexture_1;
  99152. TextureUtils.ApplySamplingParameters(babylonTexture, parameters);
  99153. var maxMipLevel_1 = automaticMipmaps ? 0 : textureCube.source.length - 1;
  99154. var texturesUploaded_1 = 0;
  99155. var textureComplete = function () {
  99156. return texturesUploaded_1 === ((maxMipLevel_1 + 1) * 6);
  99157. };
  99158. var uploadFace = function (i, level, face) {
  99159. if (!glTexture_1)
  99160. return;
  99161. if (i === 0 && level === 0) {
  99162. internalTexture_1.width = face.width;
  99163. internalTexture_1.height = face.height;
  99164. }
  99165. var gl = (scene.getEngine())._gl;
  99166. gl.bindTexture(gl.TEXTURE_CUBE_MAP, glTexture_1);
  99167. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  99168. if (face instanceof HTMLElement || face instanceof ImageData) {
  99169. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureCube.internalFormat, textureCube.type, face);
  99170. }
  99171. else {
  99172. var textureData = face;
  99173. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureData.width, textureData.height, 0, textureData.format, textureCube.type, textureData.data);
  99174. }
  99175. texturesUploaded_1++;
  99176. if (textureComplete()) {
  99177. //generate mipmaps
  99178. if (automaticMipmaps) {
  99179. var w = face.width;
  99180. var h = face.height;
  99181. var isPot = (((w !== 0) && (w & (w - 1))) === 0) && (((h !== 0) && (h & (h - 1))) === 0);
  99182. if (isPot) {
  99183. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  99184. }
  99185. }
  99186. // Upload Separate lods in case there is no support for texture lod.
  99187. if (environment && !scene.getEngine().getCaps().textureLOD && !singleLod) {
  99188. var mipSlices = 3;
  99189. for (var i_1 = 0; i_1 < mipSlices; i_1++) {
  99190. var lodKey = TextureUtils.BabylonTextureKeyPrefix + 'lod' + i_1;
  99191. var lod = textureCube[lodKey];
  99192. //initialize lod texture if it doesn't already exist
  99193. if (lod == null && textureCube.Width) {
  99194. //compute LOD from even spacing in smoothness (matching shader calculation)
  99195. var smoothness = i_1 / (mipSlices - 1);
  99196. var roughness = 1 - smoothness;
  99197. var kMinimumVariance = 0.0005;
  99198. var alphaG = roughness * roughness + kMinimumVariance;
  99199. var microsurfaceAverageSlopeTexels = alphaG * textureCube.Width;
  99200. var environmentSpecularLOD = TextureUtils.EnvironmentLODScale * (BABYLON.Scalar.Log2(microsurfaceAverageSlopeTexels)) + TextureUtils.EnvironmentLODOffset;
  99201. var maxLODIndex = textureCube.source.length - 1;
  99202. var mipmapIndex = Math.min(Math.max(Math.round(environmentSpecularLOD), 0), maxLODIndex);
  99203. lod = TextureUtils.GetBabylonCubeTexture(scene, new TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */, [textureCube.source[mipmapIndex]]), false, true, true);
  99204. if (i_1 === 0) {
  99205. internalTexture_1._lodTextureLow = lod;
  99206. }
  99207. else if (i_1 === 1) {
  99208. internalTexture_1._lodTextureMid = lod;
  99209. }
  99210. else {
  99211. internalTexture_1._lodTextureHigh = lod;
  99212. }
  99213. textureCube[lodKey] = lod;
  99214. }
  99215. }
  99216. }
  99217. internalTexture_1.isReady = true;
  99218. }
  99219. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  99220. scene.getEngine().resetTextureCache();
  99221. };
  99222. var _loop_1 = function (i) {
  99223. var faces = textureCube.source[i];
  99224. var _loop_2 = function (j) {
  99225. var face = faces[j];
  99226. if (face instanceof HTMLImageElement && !face.complete) {
  99227. face.addEventListener('load', function () {
  99228. uploadFace(j, i, face);
  99229. }, false);
  99230. }
  99231. else {
  99232. uploadFace(j, i, face);
  99233. }
  99234. };
  99235. for (var j = 0; j < faces.length; j++) {
  99236. _loop_2(j);
  99237. }
  99238. };
  99239. for (var i = 0; i <= maxMipLevel_1; i++) {
  99240. _loop_1(i);
  99241. }
  99242. scene.getEngine().resetTextureCache();
  99243. babylonTexture.isReady = function () {
  99244. return textureComplete();
  99245. };
  99246. textureCube[key] = babylonTexture;
  99247. }
  99248. return babylonTexture;
  99249. };
  99250. /**
  99251. * Applies Spectre SamplingParameters to a Babylon texture by directly setting texture parameters on the internal WebGLTexture as well as setting Babylon fields
  99252. * @param babylonTexture Babylon texture to apply texture to (requires the Babylon texture has an initialize _texture field)
  99253. * @param parameters Spectre SamplingParameters to apply
  99254. */
  99255. TextureUtils.ApplySamplingParameters = function (babylonTexture, parameters) {
  99256. var scene = babylonTexture.getScene();
  99257. if (!scene)
  99258. return;
  99259. var gl = (scene.getEngine())._gl;
  99260. var target = babylonTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  99261. var internalTexture = babylonTexture._texture;
  99262. if (!internalTexture)
  99263. return;
  99264. var glTexture = internalTexture._webGLTexture;
  99265. gl.bindTexture(target, glTexture);
  99266. if (parameters.magFilter != null)
  99267. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, parameters.magFilter);
  99268. if (parameters.minFilter != null)
  99269. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, parameters.minFilter);
  99270. if (parameters.wrapS != null)
  99271. gl.texParameteri(target, gl.TEXTURE_WRAP_S, parameters.wrapS);
  99272. if (parameters.wrapT != null)
  99273. gl.texParameteri(target, gl.TEXTURE_WRAP_T, parameters.wrapT);
  99274. //set babylon wrap modes from sampling parameter
  99275. switch (parameters.wrapS) {
  99276. case 10497 /* REPEAT */:
  99277. babylonTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  99278. break;
  99279. case 33071 /* CLAMP_TO_EDGE */:
  99280. babylonTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99281. break;
  99282. case 33648 /* MIRRORED_REPEAT */:
  99283. babylonTexture.wrapU = BABYLON.Texture.MIRROR_ADDRESSMODE;
  99284. break;
  99285. default: babylonTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99286. }
  99287. switch (parameters.wrapT) {
  99288. case 10497 /* REPEAT */:
  99289. babylonTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  99290. break;
  99291. case 33071 /* CLAMP_TO_EDGE */:
  99292. babylonTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99293. break;
  99294. case 33648 /* MIRRORED_REPEAT */:
  99295. babylonTexture.wrapV = BABYLON.Texture.MIRROR_ADDRESSMODE;
  99296. break;
  99297. default: babylonTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99298. }
  99299. if (parameters.maxAnisotropy != null && parameters.maxAnisotropy > 1) {
  99300. var anisotropicExt = gl.getExtension('EXT_texture_filter_anisotropic');
  99301. if (anisotropicExt) {
  99302. var maxAnisotropicSamples = gl.getParameter(anisotropicExt.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  99303. var maxAnisotropy = Math.min(parameters.maxAnisotropy, maxAnisotropicSamples);
  99304. gl.texParameterf(target, anisotropicExt.TEXTURE_MAX_ANISOTROPY_EXT, maxAnisotropy);
  99305. babylonTexture.anisotropicFilteringLevel = maxAnisotropy;
  99306. }
  99307. }
  99308. gl.bindTexture(target, null);
  99309. scene.getEngine().resetTextureCache();
  99310. };
  99311. /**
  99312. * A prefix used when storing a babylon texture object reference on a Spectre texture object
  99313. */
  99314. TextureUtils.BabylonTextureKeyPrefix = '__babylonTexture_';
  99315. /**
  99316. * Controls anisotropic filtering for deserialized textures.
  99317. */
  99318. TextureUtils.MaxAnisotropy = 4;
  99319. TextureUtils._EnvironmentSampling = {
  99320. magFilter: 9729 /* LINEAR */,
  99321. minFilter: 9987 /* LINEAR_MIPMAP_LINEAR */,
  99322. wrapS: 33071 /* CLAMP_TO_EDGE */,
  99323. wrapT: 33071 /* CLAMP_TO_EDGE */,
  99324. maxAnisotropy: 1
  99325. };
  99326. TextureUtils._EnvironmentSingleMipSampling = {
  99327. magFilter: 9729 /* LINEAR */,
  99328. minFilter: 9729 /* LINEAR */,
  99329. wrapS: 33071 /* CLAMP_TO_EDGE */,
  99330. wrapT: 33071 /* CLAMP_TO_EDGE */,
  99331. maxAnisotropy: 1
  99332. };
  99333. //from "/Internal/Lighting.EnvironmentFilterScale" in Engine/*/Configuration.cpp
  99334. /**
  99335. * Environment preprocessing dedicated value (Internal Use or Advanced only).
  99336. */
  99337. TextureUtils.EnvironmentLODScale = 0.8;
  99338. /**
  99339. * Environment preprocessing dedicated value (Internal Use or Advanced only)..
  99340. */
  99341. TextureUtils.EnvironmentLODOffset = 1.0;
  99342. return TextureUtils;
  99343. }());
  99344. exports.TextureUtils = TextureUtils;
  99345. /***/ }),
  99346. /* 11 */
  99347. /***/ (function(module, exports) {
  99348. module.exports = "<viewer></viewer> <loading-screen></loading-screen> <overlay></overlay>";
  99349. /***/ }),
  99350. /* 12 */
  99351. /***/ (function(module, exports) {
  99352. 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 2s ease;-moz-transition:opacity 2s ease;transition:opacity 2s 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}}>";
  99353. /***/ }),
  99354. /* 13 */
  99355. /***/ (function(module, exports) {
  99356. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAStUlEQVR42uyaA7TrShiFn23btm3btm3btm3btm372LWd9+318nSRNk2mtz3trLXX5PbmZOafPT9nxmq1VmuKFggEZs1ms0uVSqUj8vn8Q/SP5nK5lRpMjFYLh8NTZTKZhSBxi2KxeDlEPgh+BQVrhKbfwDNgZf45QZ2J0mrxeHxGtHJRCDoUQm+FpLd4joKc5aKJaDbDNzxuZT3yyLg1FqPVWPip0un0PBCxMUScD+6wtTJr+dz49hdsmh14nMiAKK0WiUSmgbjFC4XCYSz2VeB9/p2wyaxJK9EY93set+dxwhYr1QU9U7B4s4CNIfMM+pvAzyBm1VFjPl+D3cDELdacyVy4kMsdLBMrX0kf4beM1QCt9Ff7hY14nGRpWiIHBgYmU+BDwLMRi3EMJN4KpJUBa5g05OlHthORc4amIJXgZ30EPtXWyiHITFtN0JBziDz6DB6nHtYEI+i04BZQtJqwIfcAOBXM0hCEdXR0TM1k5ydV2Iv+CLTyeXbqgWeeeeY4DmnMOGjxTrw/aDVpkxtirW7Bos09xkns6+ublAlNA3Gr4S+3JCe4ksk9YOeWsdH4nkcTicTMZfLVuXjvrQYmKS54/EZaRReqaQvzz7FrZUYXBocz8BV2tWcQpEDR5eR7mPjGTmP98ssvEyra5N1CnZNZBL+Dp9mUF7A2a0W7u6dlE8/E82Ve0zVlCHz3HhFtnGAmfJWPC5Nm4pfSO6YLWIdVee/bOiFTiz1A/zL9xSpJqjLmpGHJZHJW9sDlvB/yul7gHlze4sY0Wr7UQLrwierA5fJf7eISrcaE9jHuh/TXsLk3j0aj81dbepRbUkXND40Gz7Hx1/SdaIRcz9BCxjDHh/A4nlMAxvjbKa0wZGaDKmeCO5nLAQoQOzs7fa86pVKpOfj2lSDsdc60N5Reat380uD5DfuyZ5KBwGzOc0jNiWCvet1QfONH+ushcz/M6AoqIUojapgWzgauBTEfiP6QzS+ix/E0qW6CB9MFCL7/G5Pd1DGd+uyz8SHmKB0eVPC9KAvwA3iK56Py6fTasVhseoMnVuMrs6h0seWelFnI9PqgIG+DTT2dSSsFsgw3+1z1ZpUsyyzOMrz7+QgH77+CB9gAp/HTWqFQaEqZMMOp4hKMd7hN1DcgxfMzLiLfsZFlMf7mScngA9Gfqp7w3XffuSe6WCi8Y9WufUYwsUKZY0EVVA5FoB3wR3MZNquTg3mxMNvSXw0+Bn1OrgBcid+ds9IxkHc51ljWJuNDAPsb67I/j5O5EfKaGkeyaSZ5hEktdEhxZrGs3GqMfxKL9aYCPJCtYqET4BIep6zQzI9N1L20rIA02geiO5HhYKunZ5JKdtgpNThSCzGpt+2z3YN0N8rkOaoW1K7Iicy9Gfs2HeuBrM+ytWuh3WiULvQxn2d90uh2OmUIkzpp8MZ+ayj4lcFvl6ZiznRxbRKTEe0j3JdizPkYb3fGvUim1n1FzptG4XP3rjQQ03tgWeW/oFBlPv8s8h6tG6GO1tBOKYoeKkFt4HmdhbI7V+F7Rk9P2traJlKRoZTP6x7WOeAl5tFZJyXOt3Xm/eabb47nwkWuCl4YHQf8nheh4BkgQpfWGrjxwdOAlEsNvR/sh6ldsJbXShlrXDbSyfV8tmznse/SL+ZCrnGUSvJ3X/6toUAaeowIVbXNa1rQ78IcfaCc1s+bkWj+ijKvCvjoj6Sf0Mm/5jOZbXinrc4PLdJQfbdSKzeuxkjFTSdJbs43qw2QtFNtX7mrTmr+c1+5OMIYz5VLRfj/2XnvlQa4ypMBCi6nMW7hwmFdI553VDXpB1wQHKyEYL0DZrHvLJ8LXnbjK2WmdCb9iMOF88+cK2D1d8MD96Kqm5+ZAlgHKBZ5Q8rHml3i6VRJGlfJDUI7Oo/4UAG7tdx4mPhlHSpy9Ub0oA4/qvGryrsVlOmuG/37IDniiZy4HOkPC9nsTm4miXlcrZIJ4X82gaA/2zvneNmdHoz/bNu2bdu2bdu2bdu2bdu2fbz3zfe9+eOizelMs93uns7n08uz0+48nUzwJPnFyQO2QAZi/IXNwgGTdXlTgFrfMnH4P9mRS6m18GgWFio/7xFVWiJAS59aHu5Tj7MMBQyxbIktFo1d0kS86mmMtZsmNGYOlknB6wkCTA8mWS5EtPz888+cxXc6vfkPmAqYcsAMxbFUmvZX77wzlhF82SqU4Pf++++PmjeqhBg4OS1QYCldAs4NTgvzrTzDWuxY435wwPYtMweMNXdk3NjzYd8GTHRWyhyE1xboxUzaS47JLieHwhmcvb0oYIvJz35Z0nP4o14YNxcEznenGVXKCTAi5VYCC3CnrXOS//dKJiP4j7entxCk/Bzet1rJAL463D9h42K9LSdmnUhE3yuWSNFA/f6WQsROh9HoyAHbRz1glptzh/JkKdqAqFfrjZD5RFrtZ+3glcNlvX1mCIA3GvYegQ54TM85Ltg9YsNNZu0KAXmz8uzgrtMss0/W7z8v64YdvKQHwElaL1xiK4dJFv2RvPYrURe513dynfYtgXD/8Kj7YFM5BoG6xEs2kyXvx8k6IYFzWcRxEjIKt0/5eezgqSzxqYVRahFsymc06jKHIaJLCLC94zr//XcBXno3F3I/IbOxYHkMalnk2SzfMp4t68yBSmP5lTVH6HUB9VxscXljxzGwLDXA7DjJJZ7F6znVmTRsb1/+qTwA828Z+FjbWvYrGQcDShICFPLw10C9wSHDbrchbBqArR3HZtk2cL779aOmAnJ/1gnZjSbAtv16ouWDVc7WHvIzM1iaeCsDjIYduIOvyPLl9wh4wF0Tio1NEVCt5lZxYY5arzpZcovV5Zq8rAALlfZdi9pDFC3whdktyw7ekLWPnZBzNDDm+xxi12FXjkbylizKkfLnxwZgTy5R4h18fy9YvB8yn4j0DTMFkUkBzaLN4hjxyJTAr2x5ogwxPp0sws4Q/nCypzxzmQG+1yHjxNCJjBik/PDFGWT+fV6pMMpEWNPSsDUBey2lv3xoBhHKDzAb5AS7XEaQRdPz66+/Tpp5dzwnpK/u7p7HI0QMouWDyDf6scQXpn+Nj5fCmZSl38G7eWV94meIKB3YDwf9s4HsSgC+JeYLy+e+I7nK1iZbB2Ap/radEQGbP3Dt3o4uwZvmK64JFQd6pxcgmgg+Qh8BmO87vaFg7Ro41zl5CppN2dNT+96w43wA1vn6EMDTegX6SYTLaVeS61r7KQu7Um52pifAHW1tJ7cawCiIkn4ygbGDbwqcb+nsaBrnAmJ0EHblwoaLzQNg5tu6BQH+2DERoSbYLBiUfZDmK2Yi3j7/BTRF9Ip9CWAUTfn/DwLm+o30o6BkNHKG0/KP2jq6t+Kl0cmXcwT4b1HaxuoLAFPawTEODCtmhKD0TBK7RI0/PM3b1dnZvSM7OSFNggdcIfaLy73nbH2AbaqOUpjbA+Z6MCoZTQt0pXqXNCfojATTas5IdgZn+mJ9ZAefYYRLlwt8We4MhBfwOm8bIBd4rbSzuo00CUvEOAAiZZKWazWAKfriFc4kyz9XicP+jS+6Vg34rCvAYoot0GoAW1Qd6EeBO3iXGJNop0GZGAT4iwPY4Iq1AMBSI3Mhr0C/YDVvzA6eNYngJl4tRLI5cF/KGfO9IyBjtRLAOIgsogME/ZD5BJNpggHmQykP959c0+WqGGAHrTdtOYDDqTofhSTJx1CaACiVmaEPMJU3wPo2Ht/qAFvsR0zQkNojYFGXGpY8BEEIb4ApJ9jqAFtUHanDOXkIN7ynq+uaaIDxtvTyJn6QlqcrovYOLwcA+a5yr7+bGWCtoUU9MbrQLO4U6AeDs/Ls4LMy3OBjkrttdmY+gHGZQnZvNoAV1E9kjc6jQFyGemI4OZYOtIHXjQZYPnxQxrfoLbp9ebQKAGBb5JcZYC3P39PzBlWFtIDZUHVusbBEIQRxrVc1Ql8EWIn8b9IEC8J+niq6pO6EBGfylGTCVFoy8IvejPqfI4aL0X53MwDM4mrVm508a1ozp3e9svBsQ/umt5LhB98oCuD29rfKCrD65R+mRieZE57Vc2uSXgvHO6CuGEfjO5izeQCGm/tv6EJop7SZPQPhnZ0d9xcNcK3/+EELr64FqJ5FVXEmAaoIeM3E8DO37OGgvVJ63hFgRP5ZRQGsvQavFY12JepcOye+TUoNbfn9BUDNGZE6x+OBHi+eymJrl94Aaz3mD4hty6Kt4pkQp1ki0xLxYS0B1ZU473DoH9mqAJMNoHlYmDPh/ly7itDMslP3o/J8LlDt9N1V/FvftQDA+NFlvnm1iq3LoPEmJSQE1MPpy1iTUTyvOmLwlmTl+cr4yuGhO+67777R/AH2HzgxKFkhgB4TkAzn1joQgmJhre+0edW4ohG+m/fhP/3008kSCAg7lwFgCIk07+LokuvdRhRW0w42l7n1GeLNzLLznn766THFszKjgPyTt+gRE2XDRgGMKEf8yqIeX8RONepmP6/tDsb27g72cpaHkMJdU+nPL8Bb5gkw/1YkwLhdaXujlerfb9BORbt/n3omBmsj/yDCgRcnABjs1o1565oJYJwPKn5P1CZa3Q3s+X8Jz2Jo975Dazz2hACjBn1XmQHWvhLzyoIeS3y7iJ1q+LZvo8oBzTfrCqZBJTkzBBit93F22QBWX/lSBN8bulO1kRat6SS3aLzi0LSTwV8KAYa+wFqQNPMQhWr9pNL2eQCmtyANl2lxC1GtwU2z3tR48cwR+tDwHX//PXNAnDmcbSkPl9iSXTTotQ0x+EwA8W6HQed4/fXXJ470iZ+tjSl/LkT82r0GLxSrZIGYeDFVeeXIO1S1+Hvr3cp8Wbk6E2K5OxsPODH+3lgfqzg/EKse3VuKtldvr0mTENI7I9Z5XMS3xp07jIp2/ucxiWehzm91EX4bDnBxncod7dXdJHth7BgRLEfJalQBxFsVsj7u7VxpsBF4Y0Q8u//vpgXYtldPoK1cjM0NKY+MQ/oRZwgTLlOUZj0KpkXom6U1JNuaHWC1Vy+CXBdjr2rA/2BAlaun0CBDgEiZEgUiVHRQQcDol7tXWQFWe/VW+eMaFKAJPdrQRQTUrRDjkY2hvyq8NT5Bcs0+vCThv4c0amKekqTZtv377/Up93m3gabNk/Qb/O6778aNad9L02iZ4344bjnTXj50BS9gRx4u5XHvShFFU6SxHeQztw36JVLm4R6PNMBePepvsTtjzlWZY0FKAnva3dQQbQjAGN7yhu+SIloBcYyUlnej0kUzC5kMznRR9iolo2JEIbxo+iLXy0OGS3WIRo201Ayp1PIeIKa0vQO48eXBv2kQwCza/+3V7nh7dXL57E4yhw/nymZ5LjZE2YZU67lHF/LWNBebiMFZ8TYVBbDaq8/J7xvHdOZGwULRkjnuqHdzavQbuQ987JU0F7iBwwBGz7VT08jaND7my9QLYOxVje0eGGOv0otJRPeisCkwkQoIRKADHGk/a4kAZtRkiEZ5jGEbbk32QIoWfUZsa3WaZckf5yD4EXGuTq89nb50az5t94G6VV6khQs3h7zSUMnAs6q7S87xRoiiBH/2UYF+YMjra8ifR40IjeLc30vmeAlxXoAn7AV6L9r9K0oOcELVnhUD51k5w1mForNtjB8YjV4WeWOZ4yG52gryhF0K30uPraYciNZT076gXFPnSWfVanxvYK/WpElHxMs3IpXlWOgi4sQ8L1IBp4laFc0/iO/WZKR84c9EJE8WCrDaqxfI2z976FlFzhWfG4B7VSvIvj5ZpNaMTbpbbda/fLknDDv09Sz2p9JsbqPYKRptRCLd1Dhj5Pe3CgL1P7ke1V5UfL/WHXiy5HrFWAyAG763EGXwfYVmhANDbd6Ogsokfaahw6k0h7hvDNEQ58KZYcQ5r7HFbbBz/wbO+YJZkavri9o3hyzAyobZwULtmyPgMR9lhWx71d0Z8Q7FauTlnVB3azWIGxux4G4KoWYNcGiX0n1ELr7CZwssRXgpzAp1vVYjodv39cYCdspILRaGjUsf/gHJaAWdrW+QG0Rv/QrFbPHSBywngFzzDeiEkB2zovybktEch90C9wcI/zQjSelhUQ3DJTkpdrCxwD+IJroCvCdPXnMAg2PLfDU6qoF/eX6TZVl8Lclzax0dsyrVqBpO4pqAQHcDecz3EvxQwkI16kGkp9m0v2ljxoU/UGfElBUCxYCMK/HKejMj5LpRriWVx1yNIgfmhyz+83U4WzFvDsAZUa1yYwfcLAh4P3kwI+S6RMybBcrHjKg8XQshTiOZESR+bS+prONUK1niITtvezTcAGYEid2zasSpGUY1ekSztpgRcpHpsK5co1er1YRDu6DelsCMOL5d6DmVo78FBgRzcRy+pgTzFeiqVq1Ki43KZo0b/wP23paVqC/D3gAAAABJRU5ErkJggg=="
  99357. /***/ }),
  99358. /* 14 */
  99359. /***/ (function(module, exports) {
  99360. module.exports = "<style>viewer{position:relative;overflow:hidden;flex:1;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 id={{canvasId}}> </canvas> <nav-bar></nav-bar>";
  99361. /***/ }),
  99362. /* 15 */
  99363. /***/ (function(module, exports) {
  99364. 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>";
  99365. /***/ }),
  99366. /* 16 */
  99367. /***/ (function(module, exports) {
  99368. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  99369. /***/ }),
  99370. /* 17 */
  99371. /***/ (function(module, exports) {
  99372. module.exports = "Error loading the model";
  99373. /***/ }),
  99374. /* 18 */
  99375. /***/ (function(module, exports, __webpack_require__) {
  99376. "use strict";
  99377. Object.defineProperty(exports, "__esModule", { value: true });
  99378. var babylonjs_1 = __webpack_require__(0);
  99379. var babylonjs_loaders_1 = __webpack_require__(19);
  99380. var viewerModel_1 = __webpack_require__(20);
  99381. var _1 = __webpack_require__(44);
  99382. /**
  99383. * An instance of the class is in charge of loading the model correctly.
  99384. * This class will continously be expended with tasks required from the specific loaders Babylon has.
  99385. *
  99386. * A Model loader is unique per (Abstract)Viewer. It is being generated by the viewer
  99387. */
  99388. var ModelLoader = /** @class */ (function () {
  99389. /**
  99390. * Create a new Model loader
  99391. * @param _viewer the viewer using this model loader
  99392. */
  99393. function ModelLoader(_viewer) {
  99394. this._viewer = _viewer;
  99395. this._disposed = false;
  99396. this._loaders = [];
  99397. this._loadId = 0;
  99398. this._plugins = [];
  99399. }
  99400. ModelLoader.prototype.addPlugin = function (plugin) {
  99401. var actualPlugin = {};
  99402. if (typeof plugin === 'string') {
  99403. var loadedPlugin = _1.getLoaderPluginByName(plugin);
  99404. if (loadedPlugin) {
  99405. actualPlugin = loadedPlugin;
  99406. }
  99407. }
  99408. else {
  99409. actualPlugin = plugin;
  99410. }
  99411. if (actualPlugin && this._plugins.indexOf(actualPlugin) === -1) {
  99412. this._plugins.push(actualPlugin);
  99413. }
  99414. };
  99415. /**
  99416. * Load a model using predefined configuration
  99417. * @param modelConfiguration the modelConfiguration to use to load the model
  99418. */
  99419. ModelLoader.prototype.load = function (modelConfiguration) {
  99420. var _this = this;
  99421. var model = new viewerModel_1.ViewerModel(this._viewer, modelConfiguration);
  99422. model.loadId = this._loadId++;
  99423. if (!modelConfiguration.url) {
  99424. model.state = viewerModel_1.ModelState.ERROR;
  99425. babylonjs_1.Tools.Error("No URL provided");
  99426. return model;
  99427. }
  99428. var filename = babylonjs_1.Tools.GetFilename(modelConfiguration.url) || modelConfiguration.url;
  99429. var base = modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(modelConfiguration.url);
  99430. var plugin = modelConfiguration.loader;
  99431. model.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, this._viewer.sceneManager.scene, function (meshes, particleSystems, skeletons, animationGroups) {
  99432. meshes.forEach(function (mesh) {
  99433. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  99434. model.addMesh(mesh);
  99435. });
  99436. model.particleSystems = particleSystems;
  99437. model.skeletons = skeletons;
  99438. for (var _i = 0, animationGroups_1 = animationGroups; _i < animationGroups_1.length; _i++) {
  99439. var animationGroup = animationGroups_1[_i];
  99440. model.addAnimationGroup(animationGroup);
  99441. }
  99442. _this._checkAndRun("onLoaded", model);
  99443. model.onLoadedObservable.notifyObserversWithPromise(model);
  99444. }, function (progressEvent) {
  99445. _this._checkAndRun("onProgress", progressEvent);
  99446. model.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  99447. }, function (scene, m, exception) {
  99448. model.state = viewerModel_1.ModelState.ERROR;
  99449. babylonjs_1.Tools.Error("Load Error: There was an error loading the model. " + m);
  99450. _this._checkAndRun("onError", m, exception);
  99451. model.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  99452. }, plugin);
  99453. if (model.loader.name === "gltf") {
  99454. var gltfLoader_1 = model.loader;
  99455. gltfLoader_1.animationStartMode = babylonjs_loaders_1.GLTFLoaderAnimationStartMode.NONE;
  99456. gltfLoader_1.compileMaterials = true;
  99457. // if ground is set to "mirror":
  99458. if (this._viewer.configuration.ground && typeof this._viewer.configuration.ground === 'object' && this._viewer.configuration.ground.mirror) {
  99459. gltfLoader_1.useClipPlane = true;
  99460. }
  99461. Object.keys(gltfLoader_1).filter(function (name) { return name.indexOf('on') === 0 && name.indexOf('Observable') !== -1; }).forEach(function (functionName) {
  99462. gltfLoader_1[functionName].add(function (payload) {
  99463. _this._checkAndRun(functionName.replace("Observable", ''), payload);
  99464. });
  99465. });
  99466. gltfLoader_1.onParsedObservable.add(function (data) {
  99467. if (data && data.json && data.json['asset']) {
  99468. model.loadInfo = data.json['asset'];
  99469. }
  99470. });
  99471. }
  99472. this._checkAndRun("onInit", model.loader, model);
  99473. this._loaders.push(model.loader);
  99474. return model;
  99475. };
  99476. ModelLoader.prototype.cancelLoad = function (model) {
  99477. var loader = model.loader || this._loaders[model.loadId];
  99478. // ATM only available in the GLTF Loader
  99479. if (loader && loader.name === "gltf") {
  99480. var gltfLoader = loader;
  99481. gltfLoader.dispose();
  99482. model.state = viewerModel_1.ModelState.CANCELED;
  99483. }
  99484. else {
  99485. babylonjs_1.Tools.Warn("This type of loader cannot cancel the request");
  99486. }
  99487. };
  99488. /**
  99489. * dispose the model loader.
  99490. * If loaders are registered and are in the middle of loading, they will be disposed and the request(s) will be cancelled.
  99491. */
  99492. ModelLoader.prototype.dispose = function () {
  99493. this._loaders.forEach(function (loader) {
  99494. if (loader.name === "gltf") {
  99495. loader.dispose();
  99496. }
  99497. });
  99498. this._loaders.length = 0;
  99499. this._disposed = true;
  99500. };
  99501. ModelLoader.prototype._checkAndRun = function (functionName) {
  99502. var _this = this;
  99503. var payload = [];
  99504. for (var _i = 1; _i < arguments.length; _i++) {
  99505. payload[_i - 1] = arguments[_i];
  99506. }
  99507. if (this._disposed)
  99508. return;
  99509. this._plugins.filter(function (p) { return p[functionName]; }).forEach(function (plugin) {
  99510. try {
  99511. plugin[functionName].apply(_this, payload);
  99512. }
  99513. catch (e) { }
  99514. });
  99515. };
  99516. return ModelLoader;
  99517. }());
  99518. exports.ModelLoader = ModelLoader;
  99519. /***/ }),
  99520. /* 19 */
  99521. /***/ (function(module, exports, __webpack_require__) {
  99522. (function universalModuleDefinition(root, factory) {
  99523. var amdDependencies = [];
  99524. var BABYLON = root.BABYLON || this.BABYLON;
  99525. if(true) {
  99526. BABYLON = BABYLON || __webpack_require__(0);
  99527. module.exports = factory(BABYLON);
  99528. } else if(typeof define === 'function' && define.amd) {
  99529. amdDependencies.push("babylonjs");
  99530. define("babylonjs-loaders", amdDependencies, factory);
  99531. } else if(typeof exports === 'object') {
  99532. BABYLON = BABYLON || require("babylonjs");
  99533. exports["babylonjs-loaders"] = factory(BABYLON);
  99534. } else {
  99535. root["BABYLON"] = factory(BABYLON);
  99536. }
  99537. })(this, function(BABYLON) {
  99538. BABYLON = BABYLON || this.BABYLON;
  99539. 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};
  99540. 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)}}();
  99541. var BABYLON;
  99542. (function (BABYLON) {
  99543. var STLFileLoader = /** @class */ (function () {
  99544. function STLFileLoader() {
  99545. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  99546. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  99547. 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;
  99548. 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;
  99549. this.name = "stl";
  99550. // force data to come in as an ArrayBuffer
  99551. // we'll convert to string if it looks like it's an ASCII .stl
  99552. this.extensions = {
  99553. ".stl": { isBinary: true },
  99554. };
  99555. }
  99556. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  99557. var matches;
  99558. if (this.isBinary(data)) {
  99559. // binary .stl
  99560. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  99561. this.parseBinary(babylonMesh, data);
  99562. if (meshes) {
  99563. meshes.push(babylonMesh);
  99564. }
  99565. return true;
  99566. }
  99567. // ASCII .stl
  99568. // convert to string
  99569. var array_buffer = new Uint8Array(data);
  99570. var str = '';
  99571. for (var i = 0; i < data.byteLength; i++) {
  99572. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  99573. }
  99574. data = str;
  99575. while (matches = this.solidPattern.exec(data)) {
  99576. var meshName = matches[1];
  99577. var meshNameFromEnd = matches[3];
  99578. if (meshName != meshNameFromEnd) {
  99579. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  99580. return false;
  99581. }
  99582. // check meshesNames
  99583. if (meshesNames && meshName) {
  99584. if (meshesNames instanceof Array) {
  99585. if (!meshesNames.indexOf(meshName)) {
  99586. continue;
  99587. }
  99588. }
  99589. else {
  99590. if (meshName !== meshesNames) {
  99591. continue;
  99592. }
  99593. }
  99594. }
  99595. // stl mesh name can be empty as well
  99596. meshName = meshName || "stlmesh";
  99597. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  99598. this.parseASCII(babylonMesh, matches[2]);
  99599. if (meshes) {
  99600. meshes.push(babylonMesh);
  99601. }
  99602. }
  99603. return true;
  99604. };
  99605. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  99606. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  99607. if (result) {
  99608. scene.createDefaultCameraOrLight();
  99609. }
  99610. return result;
  99611. };
  99612. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  99613. var container = new BABYLON.AssetContainer(scene);
  99614. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  99615. container.removeAllFromScene();
  99616. return container;
  99617. };
  99618. STLFileLoader.prototype.isBinary = function (data) {
  99619. // check if file size is correct for binary stl
  99620. var faceSize, nFaces, reader;
  99621. reader = new DataView(data);
  99622. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  99623. nFaces = reader.getUint32(80, true);
  99624. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  99625. return true;
  99626. }
  99627. // check characters higher than ASCII to confirm binary
  99628. var fileLength = reader.byteLength;
  99629. for (var index = 0; index < fileLength; index++) {
  99630. if (reader.getUint8(index) > 127) {
  99631. return true;
  99632. }
  99633. }
  99634. return false;
  99635. };
  99636. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  99637. var reader = new DataView(data);
  99638. var faces = reader.getUint32(80, true);
  99639. var dataOffset = 84;
  99640. var faceLength = 12 * 4 + 2;
  99641. var offset = 0;
  99642. var positions = new Float32Array(faces * 3 * 3);
  99643. var normals = new Float32Array(faces * 3 * 3);
  99644. var indices = new Uint32Array(faces * 3);
  99645. var indicesCount = 0;
  99646. for (var face = 0; face < faces; face++) {
  99647. var start = dataOffset + face * faceLength;
  99648. var normalX = reader.getFloat32(start, true);
  99649. var normalY = reader.getFloat32(start + 4, true);
  99650. var normalZ = reader.getFloat32(start + 8, true);
  99651. for (var i = 1; i <= 3; i++) {
  99652. var vertexstart = start + i * 12;
  99653. // ordering is intentional to match ascii import
  99654. positions[offset] = reader.getFloat32(vertexstart, true);
  99655. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  99656. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  99657. normals[offset] = normalX;
  99658. normals[offset + 2] = normalY;
  99659. normals[offset + 1] = normalZ;
  99660. offset += 3;
  99661. }
  99662. indices[indicesCount] = indicesCount++;
  99663. indices[indicesCount] = indicesCount++;
  99664. indices[indicesCount] = indicesCount++;
  99665. }
  99666. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  99667. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  99668. mesh.setIndices(indices);
  99669. mesh.computeWorldMatrix(true);
  99670. };
  99671. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  99672. var positions = [];
  99673. var normals = [];
  99674. var indices = [];
  99675. var indicesCount = 0;
  99676. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  99677. var matches;
  99678. while (matches = this.facetsPattern.exec(solidData)) {
  99679. var facet = matches[1];
  99680. //one normal per face
  99681. var normalMatches = this.normalPattern.exec(facet);
  99682. this.normalPattern.lastIndex = 0;
  99683. if (!normalMatches) {
  99684. continue;
  99685. }
  99686. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  99687. var vertexMatch;
  99688. while (vertexMatch = this.vertexPattern.exec(facet)) {
  99689. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  99690. normals.push(normal[0], normal[1], normal[2]);
  99691. }
  99692. indices.push(indicesCount++, indicesCount++, indicesCount++);
  99693. this.vertexPattern.lastIndex = 0;
  99694. }
  99695. this.facetsPattern.lastIndex = 0;
  99696. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  99697. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  99698. mesh.setIndices(indices);
  99699. mesh.computeWorldMatrix(true);
  99700. };
  99701. return STLFileLoader;
  99702. }());
  99703. BABYLON.STLFileLoader = STLFileLoader;
  99704. if (BABYLON.SceneLoader) {
  99705. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  99706. }
  99707. })(BABYLON || (BABYLON = {}));
  99708. //# sourceMappingURL=babylon.stlFileLoader.js.map
  99709. var BABYLON;
  99710. (function (BABYLON) {
  99711. /**
  99712. * Class reading and parsing the MTL file bundled with the obj file.
  99713. */
  99714. var MTLFileLoader = /** @class */ (function () {
  99715. function MTLFileLoader() {
  99716. // All material loaded from the mtl will be set here
  99717. this.materials = [];
  99718. }
  99719. /**
  99720. * This function will read the mtl file and create each material described inside
  99721. * This function could be improve by adding :
  99722. * -some component missing (Ni, Tf...)
  99723. * -including the specific options available
  99724. *
  99725. * @param scene
  99726. * @param data
  99727. * @param rootUrl
  99728. */
  99729. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  99730. if (data instanceof ArrayBuffer) {
  99731. return;
  99732. }
  99733. //Split the lines from the file
  99734. var lines = data.split('\n');
  99735. //Space char
  99736. var delimiter_pattern = /\s+/;
  99737. //Array with RGB colors
  99738. var color;
  99739. //New material
  99740. var material = null;
  99741. //Look at each line
  99742. for (var i = 0; i < lines.length; i++) {
  99743. var line = lines[i].trim();
  99744. // Blank line or comment
  99745. if (line.length === 0 || line.charAt(0) === '#') {
  99746. continue;
  99747. }
  99748. //Get the first parameter (keyword)
  99749. var pos = line.indexOf(' ');
  99750. var key = (pos >= 0) ? line.substring(0, pos) : line;
  99751. key = key.toLowerCase();
  99752. //Get the data following the key
  99753. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  99754. //This mtl keyword will create the new material
  99755. if (key === "newmtl") {
  99756. //Check if it is the first material.
  99757. // Materials specifications are described after this keyword.
  99758. if (material) {
  99759. //Add the previous material in the material array.
  99760. this.materials.push(material);
  99761. }
  99762. //Create a new material.
  99763. // value is the name of the material read in the mtl file
  99764. material = new BABYLON.StandardMaterial(value, scene);
  99765. }
  99766. else if (key === "kd" && material) {
  99767. // Diffuse color (color under white light) using RGB values
  99768. //value = "r g b"
  99769. color = value.split(delimiter_pattern, 3).map(parseFloat);
  99770. //color = [r,g,b]
  99771. //Set tghe color into the material
  99772. material.diffuseColor = BABYLON.Color3.FromArray(color);
  99773. }
  99774. else if (key === "ka" && material) {
  99775. // Ambient color (color under shadow) using RGB values
  99776. //value = "r g b"
  99777. color = value.split(delimiter_pattern, 3).map(parseFloat);
  99778. //color = [r,g,b]
  99779. //Set tghe color into the material
  99780. material.ambientColor = BABYLON.Color3.FromArray(color);
  99781. }
  99782. else if (key === "ks" && material) {
  99783. // Specular color (color when light is reflected from shiny surface) using RGB values
  99784. //value = "r g b"
  99785. color = value.split(delimiter_pattern, 3).map(parseFloat);
  99786. //color = [r,g,b]
  99787. //Set the color into the material
  99788. material.specularColor = BABYLON.Color3.FromArray(color);
  99789. }
  99790. else if (key === "ke" && material) {
  99791. // Emissive color using RGB values
  99792. color = value.split(delimiter_pattern, 3).map(parseFloat);
  99793. material.emissiveColor = BABYLON.Color3.FromArray(color);
  99794. }
  99795. else if (key === "ns" && material) {
  99796. //value = "Integer"
  99797. material.specularPower = parseFloat(value);
  99798. }
  99799. else if (key === "d" && material) {
  99800. //d is dissolve for current material. It mean alpha for BABYLON
  99801. material.alpha = parseFloat(value);
  99802. //Texture
  99803. //This part can be improved by adding the possible options of texture
  99804. }
  99805. else if (key === "map_ka" && material) {
  99806. // ambient texture map with a loaded image
  99807. //We must first get the folder of the image
  99808. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  99809. }
  99810. else if (key === "map_kd" && material) {
  99811. // Diffuse texture map with a loaded image
  99812. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  99813. }
  99814. else if (key === "map_ks" && material) {
  99815. // Specular texture map with a loaded image
  99816. //We must first get the folder of the image
  99817. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  99818. }
  99819. else if (key === "map_ns") {
  99820. //Specular
  99821. //Specular highlight component
  99822. //We must first get the folder of the image
  99823. //
  99824. //Not supported by BABYLON
  99825. //
  99826. // continue;
  99827. }
  99828. else if (key === "map_bump" && material) {
  99829. //The bump texture
  99830. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  99831. }
  99832. else if (key === "map_d" && material) {
  99833. // The dissolve of the material
  99834. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  99835. //Options for illumination
  99836. }
  99837. else if (key === "illum") {
  99838. //Illumination
  99839. if (value === "0") {
  99840. //That mean Kd == Kd
  99841. }
  99842. else if (value === "1") {
  99843. //Color on and Ambient on
  99844. }
  99845. else if (value === "2") {
  99846. //Highlight on
  99847. }
  99848. else if (value === "3") {
  99849. //Reflection on and Ray trace on
  99850. }
  99851. else if (value === "4") {
  99852. //Transparency: Glass on, Reflection: Ray trace on
  99853. }
  99854. else if (value === "5") {
  99855. //Reflection: Fresnel on and Ray trace on
  99856. }
  99857. else if (value === "6") {
  99858. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  99859. }
  99860. else if (value === "7") {
  99861. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  99862. }
  99863. else if (value === "8") {
  99864. //Reflection on and Ray trace off
  99865. }
  99866. else if (value === "9") {
  99867. //Transparency: Glass on, Reflection: Ray trace off
  99868. }
  99869. else if (value === "10") {
  99870. //Casts shadows onto invisible surfaces
  99871. }
  99872. }
  99873. else {
  99874. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  99875. }
  99876. }
  99877. //At the end of the file, add the last material
  99878. if (material) {
  99879. this.materials.push(material);
  99880. }
  99881. };
  99882. /**
  99883. * Gets the texture for the material.
  99884. *
  99885. * If the material is imported from input file,
  99886. * We sanitize the url to ensure it takes the textre from aside the material.
  99887. *
  99888. * @param rootUrl The root url to load from
  99889. * @param value The value stored in the mtl
  99890. * @return The Texture
  99891. */
  99892. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  99893. if (!value) {
  99894. return null;
  99895. }
  99896. var url = rootUrl;
  99897. // Load from input file.
  99898. if (rootUrl === "file:") {
  99899. var lastDelimiter = value.lastIndexOf("\\");
  99900. if (lastDelimiter === -1) {
  99901. lastDelimiter = value.lastIndexOf("/");
  99902. }
  99903. if (lastDelimiter > -1) {
  99904. url += value.substr(lastDelimiter + 1);
  99905. }
  99906. else {
  99907. url += value;
  99908. }
  99909. }
  99910. // Not from input file.
  99911. else {
  99912. url += value;
  99913. }
  99914. return new BABYLON.Texture(url, scene);
  99915. };
  99916. return MTLFileLoader;
  99917. }());
  99918. BABYLON.MTLFileLoader = MTLFileLoader;
  99919. var OBJFileLoader = /** @class */ (function () {
  99920. function OBJFileLoader() {
  99921. this.name = "obj";
  99922. this.extensions = ".obj";
  99923. this.obj = /^o/;
  99924. this.group = /^g/;
  99925. this.mtllib = /^mtllib /;
  99926. this.usemtl = /^usemtl /;
  99927. this.smooth = /^s /;
  99928. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  99929. // vn float float float
  99930. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  99931. // vt float float
  99932. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  99933. // f vertex vertex vertex ...
  99934. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  99935. // f vertex/uvs vertex/uvs vertex/uvs ...
  99936. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  99937. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  99938. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  99939. // f vertex//normal vertex//normal vertex//normal ...
  99940. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  99941. }
  99942. /**
  99943. * Calls synchronously the MTL file attached to this obj.
  99944. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  99945. * Without this function materials are not displayed in the first frame (but displayed after).
  99946. * In consequence it is impossible to get material information in your HTML file
  99947. *
  99948. * @param url The URL of the MTL file
  99949. * @param rootUrl
  99950. * @param onSuccess Callback function to be called when the MTL file is loaded
  99951. * @private
  99952. */
  99953. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  99954. //The complete path to the mtl file
  99955. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  99956. // Loads through the babylon tools to allow fileInput search.
  99957. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  99958. };
  99959. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  99960. //get the meshes from OBJ file
  99961. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  99962. //Push meshes from OBJ file into the variable mesh of this function
  99963. if (meshes) {
  99964. loadedMeshes.forEach(function (mesh) {
  99965. meshes.push(mesh);
  99966. });
  99967. }
  99968. return true;
  99969. };
  99970. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  99971. //Get the 3D model
  99972. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  99973. };
  99974. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  99975. var container = new BABYLON.AssetContainer(scene);
  99976. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  99977. container.removeAllFromScene();
  99978. return container;
  99979. };
  99980. /**
  99981. * Read the OBJ file and create an Array of meshes.
  99982. * Each mesh contains all information given by the OBJ and the MTL file.
  99983. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  99984. *
  99985. * @param meshesNames
  99986. * @param scene BABYLON.Scene The scene where are displayed the data
  99987. * @param data String The content of the obj file
  99988. * @param rootUrl String The path to the folder
  99989. * @returns Array<AbstractMesh>
  99990. * @private
  99991. */
  99992. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  99993. var positions = []; //values for the positions of vertices
  99994. var normals = []; //Values for the normals
  99995. var uvs = []; //Values for the textures
  99996. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  99997. var handledMesh; //The current mesh of meshes array
  99998. var indicesForBabylon = []; //The list of indices for VertexData
  99999. var wrappedPositionForBabylon = []; //The list of position in vectors
  100000. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  100001. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  100002. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  100003. var curPositionInIndices = 0;
  100004. var hasMeshes = false; //Meshes are defined in the file
  100005. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  100006. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  100007. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  100008. var triangles = []; //Indices from new triangles coming from polygons
  100009. var materialNameFromObj = ""; //The name of the current material
  100010. var fileToLoad = ""; //The name of the mtlFile to load
  100011. var materialsFromMTLFile = new MTLFileLoader();
  100012. var objMeshName = ""; //The name of the current obj mesh
  100013. var increment = 1; //Id for meshes created by the multimaterial
  100014. var isFirstMaterial = true;
  100015. /**
  100016. * Search for obj in the given array.
  100017. * This function is called to check if a couple of data already exists in an array.
  100018. *
  100019. * If found, returns the index of the founded tuple index. Returns -1 if not found
  100020. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  100021. * @param obj Array<number>
  100022. * @returns {boolean}
  100023. */
  100024. var isInArray = function (arr, obj) {
  100025. if (!arr[obj[0]])
  100026. arr[obj[0]] = { normals: [], idx: [] };
  100027. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  100028. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  100029. };
  100030. var isInArrayUV = function (arr, obj) {
  100031. if (!arr[obj[0]])
  100032. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  100033. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  100034. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  100035. return arr[obj[0]].idx[idx];
  100036. }
  100037. return -1;
  100038. };
  100039. /**
  100040. * This function set the data for each triangle.
  100041. * Data are position, normals and uvs
  100042. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  100043. * If the tuple already exist, add only their indice
  100044. *
  100045. * @param indicePositionFromObj Integer The index in positions array
  100046. * @param indiceUvsFromObj Integer The index in uvs array
  100047. * @param indiceNormalFromObj Integer The index in normals array
  100048. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  100049. * @param textureVectorFromOBJ Vector3 The value of uvs
  100050. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  100051. */
  100052. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  100053. //Check if this tuple already exists in the list of tuples
  100054. var _index;
  100055. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  100056. _index = isInArrayUV(tuplePosNorm, [
  100057. indicePositionFromObj,
  100058. indiceNormalFromObj,
  100059. indiceUvsFromObj
  100060. ]);
  100061. }
  100062. else {
  100063. _index = isInArray(tuplePosNorm, [
  100064. indicePositionFromObj,
  100065. indiceNormalFromObj
  100066. ]);
  100067. }
  100068. //If it not exists
  100069. if (_index == -1) {
  100070. //Add an new indice.
  100071. //The array of indices is only an array with his length equal to the number of triangles - 1.
  100072. //We add vertices data in this order
  100073. indicesForBabylon.push(wrappedPositionForBabylon.length);
  100074. //Push the position of vertice for Babylon
  100075. //Each element is a BABYLON.Vector3(x,y,z)
  100076. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  100077. //Push the uvs for Babylon
  100078. //Each element is a BABYLON.Vector3(u,v)
  100079. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  100080. //Push the normals for Babylon
  100081. //Each element is a BABYLON.Vector3(x,y,z)
  100082. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  100083. //Add the tuple in the comparison list
  100084. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  100085. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  100086. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  100087. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  100088. }
  100089. else {
  100090. //The tuple already exists
  100091. //Add the index of the already existing tuple
  100092. //At this index we can get the value of position, normal and uvs of vertex
  100093. indicesForBabylon.push(_index);
  100094. }
  100095. };
  100096. /**
  100097. * Transform BABYLON.Vector() object onto 3 digits in an array
  100098. */
  100099. var unwrapData = function () {
  100100. //Every array has the same length
  100101. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  100102. //Push the x, y, z values of each element in the unwrapped array
  100103. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  100104. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  100105. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  100106. }
  100107. // Reset arrays for the next new meshes
  100108. wrappedPositionForBabylon = [];
  100109. wrappedNormalsForBabylon = [];
  100110. wrappedUvsForBabylon = [];
  100111. tuplePosNorm = [];
  100112. curPositionInIndices = 0;
  100113. };
  100114. /**
  100115. * Create triangles from polygons by recursion
  100116. * The best to understand how it works is to draw it in the same time you get the recursion.
  100117. * It is important to notice that a triangle is a polygon
  100118. * We get 4 patterns of face defined in OBJ File :
  100119. * facePattern1 = ["1","2","3","4","5","6"]
  100120. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  100121. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  100122. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  100123. * Each pattern is divided by the same method
  100124. * @param face Array[String] The indices of elements
  100125. * @param v Integer The variable to increment
  100126. */
  100127. var getTriangles = function (face, v) {
  100128. //Work for each element of the array
  100129. if (v + 1 < face.length) {
  100130. //Add on the triangle variable the indexes to obtain triangles
  100131. triangles.push(face[0], face[v], face[v + 1]);
  100132. //Incrementation for recursion
  100133. v += 1;
  100134. //Recursion
  100135. getTriangles(face, v);
  100136. }
  100137. //Result obtained after 2 iterations:
  100138. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  100139. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  100140. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  100141. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  100142. };
  100143. /**
  100144. * Create triangles and push the data for each polygon for the pattern 1
  100145. * In this pattern we get vertice positions
  100146. * @param face
  100147. * @param v
  100148. */
  100149. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  100150. //Get the indices of triangles for each polygon
  100151. getTriangles(face, v);
  100152. //For each element in the triangles array.
  100153. //This var could contains 1 to an infinity of triangles
  100154. for (var k = 0; k < triangles.length; k++) {
  100155. // Set position indice
  100156. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  100157. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  100158. positions[indicePositionFromObj], //Get the vectors data
  100159. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  100160. );
  100161. }
  100162. //Reset variable for the next line
  100163. triangles = [];
  100164. };
  100165. /**
  100166. * Create triangles and push the data for each polygon for the pattern 2
  100167. * In this pattern we get vertice positions and uvsu
  100168. * @param face
  100169. * @param v
  100170. */
  100171. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  100172. //Get the indices of triangles for each polygon
  100173. getTriangles(face, v);
  100174. for (var k = 0; k < triangles.length; k++) {
  100175. //triangle[k] = "1/1"
  100176. //Split the data for getting position and uv
  100177. var point = triangles[k].split("/"); // ["1", "1"]
  100178. //Set position indice
  100179. var indicePositionFromObj = parseInt(point[0]) - 1;
  100180. //Set uv indice
  100181. var indiceUvsFromObj = parseInt(point[1]) - 1;
  100182. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  100183. positions[indicePositionFromObj], //Get the values for each element
  100184. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  100185. );
  100186. }
  100187. //Reset variable for the next line
  100188. triangles = [];
  100189. };
  100190. /**
  100191. * Create triangles and push the data for each polygon for the pattern 3
  100192. * In this pattern we get vertice positions, uvs and normals
  100193. * @param face
  100194. * @param v
  100195. */
  100196. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  100197. //Get the indices of triangles for each polygon
  100198. getTriangles(face, v);
  100199. for (var k = 0; k < triangles.length; k++) {
  100200. //triangle[k] = "1/1/1"
  100201. //Split the data for getting position, uv, and normals
  100202. var point = triangles[k].split("/"); // ["1", "1", "1"]
  100203. // Set position indice
  100204. var indicePositionFromObj = parseInt(point[0]) - 1;
  100205. // Set uv indice
  100206. var indiceUvsFromObj = parseInt(point[1]) - 1;
  100207. // Set normal indice
  100208. var indiceNormalFromObj = parseInt(point[2]) - 1;
  100209. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  100210. );
  100211. }
  100212. //Reset variable for the next line
  100213. triangles = [];
  100214. };
  100215. /**
  100216. * Create triangles and push the data for each polygon for the pattern 4
  100217. * In this pattern we get vertice positions and normals
  100218. * @param face
  100219. * @param v
  100220. */
  100221. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  100222. getTriangles(face, v);
  100223. for (var k = 0; k < triangles.length; k++) {
  100224. //triangle[k] = "1//1"
  100225. //Split the data for getting position and normals
  100226. var point = triangles[k].split("//"); // ["1", "1"]
  100227. // We check indices, and normals
  100228. var indicePositionFromObj = parseInt(point[0]) - 1;
  100229. var indiceNormalFromObj = parseInt(point[1]) - 1;
  100230. setData(indicePositionFromObj, 1, //Default value for uv
  100231. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  100232. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  100233. }
  100234. //Reset variable for the next line
  100235. triangles = [];
  100236. };
  100237. var addPreviousObjMesh = function () {
  100238. //Check if it is not the first mesh. Otherwise we don't have data.
  100239. if (meshesFromObj.length > 0) {
  100240. //Get the previous mesh for applying the data about the faces
  100241. //=> in obj file, faces definition append after the name of the mesh
  100242. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  100243. //Set the data into Array for the mesh
  100244. unwrapData();
  100245. // Reverse tab. Otherwise face are displayed in the wrong sens
  100246. indicesForBabylon.reverse();
  100247. //Set the information for the mesh
  100248. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  100249. handledMesh.indices = indicesForBabylon.slice();
  100250. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  100251. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  100252. handledMesh.uvs = unwrappedUVForBabylon.slice();
  100253. //Reset the array for the next mesh
  100254. indicesForBabylon = [];
  100255. unwrappedPositionsForBabylon = [];
  100256. unwrappedNormalsForBabylon = [];
  100257. unwrappedUVForBabylon = [];
  100258. }
  100259. };
  100260. //Main function
  100261. //Split the file into lines
  100262. var lines = data.split('\n');
  100263. //Look at each line
  100264. for (var i = 0; i < lines.length; i++) {
  100265. var line = lines[i].trim();
  100266. var result;
  100267. //Comment or newLine
  100268. if (line.length === 0 || line.charAt(0) === '#') {
  100269. continue;
  100270. //Get information about one position possible for the vertices
  100271. }
  100272. else if ((result = this.vertexPattern.exec(line)) !== null) {
  100273. //Create a Vector3 with the position x, y, z
  100274. //Value of result:
  100275. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  100276. //Add the Vector in the list of positions
  100277. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  100278. }
  100279. else if ((result = this.normalPattern.exec(line)) !== null) {
  100280. //Create a Vector3 with the normals x, y, z
  100281. //Value of result
  100282. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  100283. //Add the Vector in the list of normals
  100284. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  100285. }
  100286. else if ((result = this.uvPattern.exec(line)) !== null) {
  100287. //Create a Vector2 with the normals u, v
  100288. //Value of result
  100289. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  100290. //Add the Vector in the list of uvs
  100291. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  100292. //Identify patterns of faces
  100293. //Face could be defined in different type of pattern
  100294. }
  100295. else if ((result = this.facePattern3.exec(line)) !== null) {
  100296. //Value of result:
  100297. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  100298. //Set the data for this face
  100299. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  100300. 1);
  100301. }
  100302. else if ((result = this.facePattern4.exec(line)) !== null) {
  100303. //Value of result:
  100304. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  100305. //Set the data for this face
  100306. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  100307. 1);
  100308. }
  100309. else if ((result = this.facePattern2.exec(line)) !== null) {
  100310. //Value of result:
  100311. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  100312. //Set the data for this face
  100313. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  100314. 1);
  100315. }
  100316. else if ((result = this.facePattern1.exec(line)) !== null) {
  100317. //Value of result
  100318. //["f 1 2 3", "1 2 3"...]
  100319. //Set the data for this face
  100320. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  100321. 1);
  100322. //Define a mesh or an object
  100323. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  100324. }
  100325. else if (this.group.test(line) || this.obj.test(line)) {
  100326. //Create a new mesh corresponding to the name of the group.
  100327. //Definition of the mesh
  100328. var objMesh =
  100329. //Set the name of the current obj mesh
  100330. {
  100331. name: line.substring(2).trim(),
  100332. indices: undefined,
  100333. positions: undefined,
  100334. normals: undefined,
  100335. uvs: undefined,
  100336. materialName: ""
  100337. };
  100338. addPreviousObjMesh();
  100339. //Push the last mesh created with only the name
  100340. meshesFromObj.push(objMesh);
  100341. //Set this variable to indicate that now meshesFromObj has objects defined inside
  100342. hasMeshes = true;
  100343. isFirstMaterial = true;
  100344. increment = 1;
  100345. //Keyword for applying a material
  100346. }
  100347. else if (this.usemtl.test(line)) {
  100348. //Get the name of the material
  100349. materialNameFromObj = line.substring(7).trim();
  100350. //If this new material is in the same mesh
  100351. if (!isFirstMaterial) {
  100352. //Set the data for the previous mesh
  100353. addPreviousObjMesh();
  100354. //Create a new mesh
  100355. var objMesh =
  100356. //Set the name of the current obj mesh
  100357. {
  100358. name: objMeshName + "_mm" + increment.toString(),
  100359. indices: undefined,
  100360. positions: undefined,
  100361. normals: undefined,
  100362. uvs: undefined,
  100363. materialName: materialNameFromObj
  100364. };
  100365. increment++;
  100366. //If meshes are already defined
  100367. meshesFromObj.push(objMesh);
  100368. }
  100369. //Set the material name if the previous line define a mesh
  100370. if (hasMeshes && isFirstMaterial) {
  100371. //Set the material name to the previous mesh (1 material per mesh)
  100372. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  100373. isFirstMaterial = false;
  100374. }
  100375. //Keyword for loading the mtl file
  100376. }
  100377. else if (this.mtllib.test(line)) {
  100378. //Get the name of mtl file
  100379. fileToLoad = line.substring(7).trim();
  100380. //Apply smoothing
  100381. }
  100382. else if (this.smooth.test(line)) {
  100383. // smooth shading => apply smoothing
  100384. //Toda y I don't know it work with babylon and with obj.
  100385. //With the obj file an integer is set
  100386. }
  100387. else {
  100388. //If there is another possibility
  100389. console.log("Unhandled expression at line : " + line);
  100390. }
  100391. }
  100392. //At the end of the file, add the last mesh into the meshesFromObj array
  100393. if (hasMeshes) {
  100394. //Set the data for the last mesh
  100395. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  100396. //Reverse indices for displaying faces in the good sens
  100397. indicesForBabylon.reverse();
  100398. //Get the good array
  100399. unwrapData();
  100400. //Set array
  100401. handledMesh.indices = indicesForBabylon;
  100402. handledMesh.positions = unwrappedPositionsForBabylon;
  100403. handledMesh.normals = unwrappedNormalsForBabylon;
  100404. handledMesh.uvs = unwrappedUVForBabylon;
  100405. }
  100406. //If any o or g keyword found, create a mesj with a random id
  100407. if (!hasMeshes) {
  100408. // reverse tab of indices
  100409. indicesForBabylon.reverse();
  100410. //Get positions normals uvs
  100411. unwrapData();
  100412. //Set data for one mesh
  100413. meshesFromObj.push({
  100414. name: BABYLON.Geometry.RandomId(),
  100415. indices: indicesForBabylon,
  100416. positions: unwrappedPositionsForBabylon,
  100417. normals: unwrappedNormalsForBabylon,
  100418. uvs: unwrappedUVForBabylon,
  100419. materialName: materialNameFromObj
  100420. });
  100421. }
  100422. //Create a BABYLON.Mesh list
  100423. var babylonMeshesArray = []; //The mesh for babylon
  100424. var materialToUse = new Array();
  100425. //Set data for each mesh
  100426. for (var j = 0; j < meshesFromObj.length; j++) {
  100427. //check meshesNames (stlFileLoader)
  100428. if (meshesNames && meshesFromObj[j].name) {
  100429. if (meshesNames instanceof Array) {
  100430. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  100431. continue;
  100432. }
  100433. }
  100434. else {
  100435. if (meshesFromObj[j].name !== meshesNames) {
  100436. continue;
  100437. }
  100438. }
  100439. }
  100440. //Get the current mesh
  100441. //Set the data with VertexBuffer for each mesh
  100442. handledMesh = meshesFromObj[j];
  100443. //Create a BABYLON.Mesh with the name of the obj mesh
  100444. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  100445. //Push the name of the material to an array
  100446. //This is indispensable for the importMesh function
  100447. materialToUse.push(meshesFromObj[j].materialName);
  100448. var vertexData = new BABYLON.VertexData(); //The container for the values
  100449. //Set the data for the babylonMesh
  100450. vertexData.positions = handledMesh.positions;
  100451. vertexData.normals = handledMesh.normals;
  100452. vertexData.uvs = handledMesh.uvs;
  100453. vertexData.indices = handledMesh.indices;
  100454. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  100455. vertexData.applyToMesh(babylonMesh);
  100456. if (OBJFileLoader.INVERT_Y) {
  100457. babylonMesh.scaling.y *= -1;
  100458. }
  100459. //Push the mesh into an array
  100460. babylonMeshesArray.push(babylonMesh);
  100461. }
  100462. //load the materials
  100463. //Check if we have a file to load
  100464. if (fileToLoad !== "") {
  100465. //Load the file synchronously
  100466. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  100467. //Create materials thanks MTLLoader function
  100468. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  100469. //Look at each material loaded in the mtl file
  100470. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  100471. //Three variables to get all meshes with the same material
  100472. var startIndex = 0;
  100473. var _indices = [];
  100474. var _index;
  100475. //The material from MTL file is used in the meshes loaded
  100476. //Push the indice in an array
  100477. //Check if the material is not used for another mesh
  100478. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  100479. _indices.push(_index);
  100480. startIndex = _index + 1;
  100481. }
  100482. //If the material is not used dispose it
  100483. if (_index == -1 && _indices.length == 0) {
  100484. //If the material is not needed, remove it
  100485. materialsFromMTLFile.materials[n].dispose();
  100486. }
  100487. else {
  100488. for (var o = 0; o < _indices.length; o++) {
  100489. //Apply the material to the BABYLON.Mesh for each mesh with the material
  100490. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  100491. }
  100492. }
  100493. }
  100494. });
  100495. }
  100496. //Return an array with all BABYLON.Mesh
  100497. return babylonMeshesArray;
  100498. };
  100499. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  100500. OBJFileLoader.INVERT_Y = false;
  100501. return OBJFileLoader;
  100502. }());
  100503. BABYLON.OBJFileLoader = OBJFileLoader;
  100504. if (BABYLON.SceneLoader) {
  100505. //Add this loader into the register plugin
  100506. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  100507. }
  100508. })(BABYLON || (BABYLON = {}));
  100509. //# sourceMappingURL=babylon.objFileLoader.js.map
  100510. var BABYLON;
  100511. (function (BABYLON) {
  100512. /**
  100513. * Mode that determines the coordinate system to use.
  100514. */
  100515. var GLTFLoaderCoordinateSystemMode;
  100516. (function (GLTFLoaderCoordinateSystemMode) {
  100517. /**
  100518. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  100519. */
  100520. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  100521. /**
  100522. * Sets the useRightHandedSystem flag on the scene.
  100523. */
  100524. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  100525. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  100526. /**
  100527. * Mode that determines what animations will start.
  100528. */
  100529. var GLTFLoaderAnimationStartMode;
  100530. (function (GLTFLoaderAnimationStartMode) {
  100531. /**
  100532. * No animation will start.
  100533. */
  100534. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  100535. /**
  100536. * The first animation will start.
  100537. */
  100538. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  100539. /**
  100540. * All animations will start.
  100541. */
  100542. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  100543. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  100544. /**
  100545. * Loader state.
  100546. */
  100547. var GLTFLoaderState;
  100548. (function (GLTFLoaderState) {
  100549. /**
  100550. * The asset is loading.
  100551. */
  100552. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  100553. /**
  100554. * The asset is ready for rendering.
  100555. */
  100556. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  100557. /**
  100558. * The asset is completely loaded.
  100559. */
  100560. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  100561. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  100562. /**
  100563. * File loader for loading glTF files into a scene.
  100564. */
  100565. var GLTFFileLoader = /** @class */ (function () {
  100566. function GLTFFileLoader() {
  100567. // #region Common options
  100568. /**
  100569. * Raised when the asset has been parsed
  100570. */
  100571. this.onParsedObservable = new BABYLON.Observable();
  100572. // #endregion
  100573. // #region V2 options
  100574. /**
  100575. * The coordinate system mode. Defaults to AUTO.
  100576. */
  100577. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  100578. /**
  100579. * The animation start mode. Defaults to FIRST.
  100580. */
  100581. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  100582. /**
  100583. * Defines if the loader should compile materials before raising the success callback. Defaults to false.
  100584. */
  100585. this.compileMaterials = false;
  100586. /**
  100587. * Defines if the loader should also compile materials with clip planes. Defaults to false.
  100588. */
  100589. this.useClipPlane = false;
  100590. /**
  100591. * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.
  100592. */
  100593. this.compileShadowGenerators = false;
  100594. /**
  100595. * Defines if the Alpha blended materials are only applied as coverage.
  100596. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  100597. * If true, no extra effects are applied to transparent pixels.
  100598. */
  100599. this.transparencyAsCoverage = false;
  100600. /**
  100601. * Function called before loading a url referenced by the asset.
  100602. */
  100603. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  100604. /**
  100605. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  100606. */
  100607. this.onMeshLoadedObservable = new BABYLON.Observable();
  100608. /**
  100609. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  100610. */
  100611. this.onTextureLoadedObservable = new BABYLON.Observable();
  100612. /**
  100613. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  100614. */
  100615. this.onMaterialLoadedObservable = new BABYLON.Observable();
  100616. /**
  100617. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  100618. */
  100619. this.onCameraLoadedObservable = new BABYLON.Observable();
  100620. /**
  100621. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  100622. * For assets with LODs, raised when all of the LODs are complete.
  100623. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  100624. */
  100625. this.onCompleteObservable = new BABYLON.Observable();
  100626. /**
  100627. * Observable raised after the loader is disposed.
  100628. */
  100629. this.onDisposeObservable = new BABYLON.Observable();
  100630. /**
  100631. * Observable raised after a loader extension is created.
  100632. * Set additional options for a loader extension in this event.
  100633. */
  100634. this.onExtensionLoadedObservable = new BABYLON.Observable();
  100635. // #endregion
  100636. this._loader = null;
  100637. /**
  100638. * Name of the loader ("gltf")
  100639. */
  100640. this.name = "gltf";
  100641. /**
  100642. * Supported file extensions of the loader (.gltf, .glb)
  100643. */
  100644. this.extensions = {
  100645. ".gltf": { isBinary: false },
  100646. ".glb": { isBinary: true }
  100647. };
  100648. }
  100649. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  100650. /**
  100651. * Raised when the asset has been parsed
  100652. */
  100653. set: function (callback) {
  100654. if (this._onParsedObserver) {
  100655. this.onParsedObservable.remove(this._onParsedObserver);
  100656. }
  100657. this._onParsedObserver = this.onParsedObservable.add(callback);
  100658. },
  100659. enumerable: true,
  100660. configurable: true
  100661. });
  100662. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  100663. /**
  100664. * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  100665. */
  100666. set: function (callback) {
  100667. if (this._onMeshLoadedObserver) {
  100668. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  100669. }
  100670. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  100671. },
  100672. enumerable: true,
  100673. configurable: true
  100674. });
  100675. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  100676. /**
  100677. * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.
  100678. */
  100679. set: function (callback) {
  100680. if (this._onTextureLoadedObserver) {
  100681. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  100682. }
  100683. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  100684. },
  100685. enumerable: true,
  100686. configurable: true
  100687. });
  100688. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  100689. /**
  100690. * Callback raised when the loader creates a material after parsing the glTF properties of the material.
  100691. */
  100692. set: function (callback) {
  100693. if (this._onMaterialLoadedObserver) {
  100694. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  100695. }
  100696. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  100697. },
  100698. enumerable: true,
  100699. configurable: true
  100700. });
  100701. Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", {
  100702. /**
  100703. * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.
  100704. */
  100705. set: function (callback) {
  100706. if (this._onCameraLoadedObserver) {
  100707. this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);
  100708. }
  100709. this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);
  100710. },
  100711. enumerable: true,
  100712. configurable: true
  100713. });
  100714. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  100715. /**
  100716. * Callback raised when the asset is completely loaded, immediately before the loader is disposed.
  100717. */
  100718. set: function (callback) {
  100719. if (this._onCompleteObserver) {
  100720. this.onCompleteObservable.remove(this._onCompleteObserver);
  100721. }
  100722. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  100723. },
  100724. enumerable: true,
  100725. configurable: true
  100726. });
  100727. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  100728. /**
  100729. * Callback raised after the loader is disposed.
  100730. */
  100731. set: function (callback) {
  100732. if (this._onDisposeObserver) {
  100733. this.onDisposeObservable.remove(this._onDisposeObserver);
  100734. }
  100735. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  100736. },
  100737. enumerable: true,
  100738. configurable: true
  100739. });
  100740. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  100741. /**
  100742. * Callback raised after a loader extension is created.
  100743. */
  100744. set: function (callback) {
  100745. if (this._onExtensionLoadedObserver) {
  100746. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  100747. }
  100748. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  100749. },
  100750. enumerable: true,
  100751. configurable: true
  100752. });
  100753. /**
  100754. * Returns a promise that resolves when the asset is completely loaded.
  100755. * @returns a promise that resolves when the asset is completely loaded.
  100756. */
  100757. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  100758. var _this = this;
  100759. return new Promise(function (resolve) {
  100760. _this.onCompleteObservable.add(function () {
  100761. resolve();
  100762. }, undefined, undefined, undefined, true);
  100763. });
  100764. };
  100765. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  100766. /**
  100767. * The loader state or null if the loader is not active.
  100768. */
  100769. get: function () {
  100770. return this._loader ? this._loader.state : null;
  100771. },
  100772. enumerable: true,
  100773. configurable: true
  100774. });
  100775. /**
  100776. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  100777. */
  100778. GLTFFileLoader.prototype.dispose = function () {
  100779. if (this._loader) {
  100780. this._loader.dispose();
  100781. this._loader = null;
  100782. }
  100783. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  100784. this.onMeshLoadedObservable.clear();
  100785. this.onTextureLoadedObservable.clear();
  100786. this.onMaterialLoadedObservable.clear();
  100787. this.onCameraLoadedObservable.clear();
  100788. this.onCompleteObservable.clear();
  100789. this.onExtensionLoadedObservable.clear();
  100790. this.onDisposeObservable.notifyObservers(this);
  100791. this.onDisposeObservable.clear();
  100792. };
  100793. /**
  100794. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  100795. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  100796. * @param scene the scene the meshes should be added to
  100797. * @param data the glTF data to load
  100798. * @param rootUrl root url to load from
  100799. * @param onProgress event that fires when loading progress has occured
  100800. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  100801. */
  100802. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  100803. var _this = this;
  100804. return Promise.resolve().then(function () {
  100805. var loaderData = _this._parse(data);
  100806. _this._loader = _this._getLoader(loaderData);
  100807. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  100808. });
  100809. };
  100810. /**
  100811. * Imports all objects from the loaded glTF data and adds them to the scene
  100812. * @param scene the scene the objects should be added to
  100813. * @param data the glTF data to load
  100814. * @param rootUrl root url to load from
  100815. * @param onProgress event that fires when loading progress has occured
  100816. * @returns a promise which completes when objects have been loaded to the scene
  100817. */
  100818. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  100819. var _this = this;
  100820. return Promise.resolve().then(function () {
  100821. var loaderData = _this._parse(data);
  100822. _this._loader = _this._getLoader(loaderData);
  100823. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  100824. });
  100825. };
  100826. /**
  100827. * Load into an asset container.
  100828. * @param scene The scene to load into
  100829. * @param data The data to import
  100830. * @param rootUrl The root url for scene and resources
  100831. * @param onProgress The callback when the load progresses
  100832. * @returns The loaded asset container
  100833. */
  100834. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  100835. var _this = this;
  100836. return Promise.resolve().then(function () {
  100837. var loaderData = _this._parse(data);
  100838. _this._loader = _this._getLoader(loaderData);
  100839. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  100840. var container = new BABYLON.AssetContainer(scene);
  100841. Array.prototype.push.apply(container.meshes, result.meshes);
  100842. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  100843. Array.prototype.push.apply(container.skeletons, result.skeletons);
  100844. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  100845. container.removeAllFromScene();
  100846. return container;
  100847. });
  100848. });
  100849. };
  100850. /**
  100851. * If the data string can be loaded directly.
  100852. * @param data string contianing the file data
  100853. * @returns if the data can be loaded directly
  100854. */
  100855. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  100856. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  100857. };
  100858. /**
  100859. * Instantiates a glTF file loader plugin.
  100860. * @returns the created plugin
  100861. */
  100862. GLTFFileLoader.prototype.createPlugin = function () {
  100863. return new GLTFFileLoader();
  100864. };
  100865. GLTFFileLoader.prototype._parse = function (data) {
  100866. var parsedData;
  100867. if (data instanceof ArrayBuffer) {
  100868. parsedData = GLTFFileLoader._parseBinary(data);
  100869. }
  100870. else {
  100871. parsedData = {
  100872. json: JSON.parse(data),
  100873. bin: null
  100874. };
  100875. }
  100876. this.onParsedObservable.notifyObservers(parsedData);
  100877. this.onParsedObservable.clear();
  100878. return parsedData;
  100879. };
  100880. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  100881. var _this = this;
  100882. var loaderVersion = { major: 2, minor: 0 };
  100883. var asset = loaderData.json.asset || {};
  100884. var version = GLTFFileLoader._parseVersion(asset.version);
  100885. if (!version) {
  100886. throw new Error("Invalid version: " + asset.version);
  100887. }
  100888. if (asset.minVersion !== undefined) {
  100889. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  100890. if (!minVersion) {
  100891. throw new Error("Invalid minimum version: " + asset.minVersion);
  100892. }
  100893. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  100894. throw new Error("Incompatible minimum version: " + asset.minVersion);
  100895. }
  100896. }
  100897. var createLoaders = {
  100898. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  100899. 2: GLTFFileLoader.CreateGLTFLoaderV2
  100900. };
  100901. var createLoader = createLoaders[version.major];
  100902. if (!createLoader) {
  100903. throw new Error("Unsupported version: " + asset.version);
  100904. }
  100905. var loader = createLoader();
  100906. loader.coordinateSystemMode = this.coordinateSystemMode;
  100907. loader.animationStartMode = this.animationStartMode;
  100908. loader.compileMaterials = this.compileMaterials;
  100909. loader.useClipPlane = this.useClipPlane;
  100910. loader.compileShadowGenerators = this.compileShadowGenerators;
  100911. loader.transparencyAsCoverage = this.transparencyAsCoverage;
  100912. loader.preprocessUrlAsync = this.preprocessUrlAsync;
  100913. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  100914. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  100915. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  100916. loader.onCameraLoadedObservable.add(function (camera) { return _this.onCameraLoadedObservable.notifyObservers(camera); });
  100917. loader.onExtensionLoadedObservable.add(function (extension) {
  100918. _this.onExtensionLoadedObservable.notifyObservers(extension);
  100919. _this.onExtensionLoadedObservable.clear();
  100920. });
  100921. loader.onCompleteObservable.add(function () {
  100922. _this.onMeshLoadedObservable.clear();
  100923. _this.onTextureLoadedObservable.clear();
  100924. _this.onMaterialLoadedObservable.clear();
  100925. _this.onCameraLoadedObservable.clear();
  100926. _this.onCompleteObservable.notifyObservers(_this);
  100927. _this.onCompleteObservable.clear();
  100928. });
  100929. return loader;
  100930. };
  100931. GLTFFileLoader._parseBinary = function (data) {
  100932. var Binary = {
  100933. Magic: 0x46546C67
  100934. };
  100935. var binaryReader = new BinaryReader(data);
  100936. var magic = binaryReader.readUint32();
  100937. if (magic !== Binary.Magic) {
  100938. throw new Error("Unexpected magic: " + magic);
  100939. }
  100940. var version = binaryReader.readUint32();
  100941. switch (version) {
  100942. case 1: return GLTFFileLoader._parseV1(binaryReader);
  100943. case 2: return GLTFFileLoader._parseV2(binaryReader);
  100944. }
  100945. throw new Error("Unsupported version: " + version);
  100946. };
  100947. GLTFFileLoader._parseV1 = function (binaryReader) {
  100948. var ContentFormat = {
  100949. JSON: 0
  100950. };
  100951. var length = binaryReader.readUint32();
  100952. if (length != binaryReader.getLength()) {
  100953. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  100954. }
  100955. var contentLength = binaryReader.readUint32();
  100956. var contentFormat = binaryReader.readUint32();
  100957. var content;
  100958. switch (contentFormat) {
  100959. case ContentFormat.JSON: {
  100960. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  100961. break;
  100962. }
  100963. default: {
  100964. throw new Error("Unexpected content format: " + contentFormat);
  100965. }
  100966. }
  100967. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  100968. var body = binaryReader.readUint8Array(bytesRemaining);
  100969. return {
  100970. json: content,
  100971. bin: body
  100972. };
  100973. };
  100974. GLTFFileLoader._parseV2 = function (binaryReader) {
  100975. var ChunkFormat = {
  100976. JSON: 0x4E4F534A,
  100977. BIN: 0x004E4942
  100978. };
  100979. var length = binaryReader.readUint32();
  100980. if (length !== binaryReader.getLength()) {
  100981. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  100982. }
  100983. // JSON chunk
  100984. var chunkLength = binaryReader.readUint32();
  100985. var chunkFormat = binaryReader.readUint32();
  100986. if (chunkFormat !== ChunkFormat.JSON) {
  100987. throw new Error("First chunk format is not JSON");
  100988. }
  100989. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  100990. // Look for BIN chunk
  100991. var bin = null;
  100992. while (binaryReader.getPosition() < binaryReader.getLength()) {
  100993. var chunkLength_1 = binaryReader.readUint32();
  100994. var chunkFormat_1 = binaryReader.readUint32();
  100995. switch (chunkFormat_1) {
  100996. case ChunkFormat.JSON: {
  100997. throw new Error("Unexpected JSON chunk");
  100998. }
  100999. case ChunkFormat.BIN: {
  101000. bin = binaryReader.readUint8Array(chunkLength_1);
  101001. break;
  101002. }
  101003. default: {
  101004. // ignore unrecognized chunkFormat
  101005. binaryReader.skipBytes(chunkLength_1);
  101006. break;
  101007. }
  101008. }
  101009. }
  101010. return {
  101011. json: json,
  101012. bin: bin
  101013. };
  101014. };
  101015. GLTFFileLoader._parseVersion = function (version) {
  101016. if (version === "1.0" || version === "1.0.1") {
  101017. return {
  101018. major: 1,
  101019. minor: 0
  101020. };
  101021. }
  101022. var match = (version + "").match(/^(\d+)\.(\d+)/);
  101023. if (!match) {
  101024. return null;
  101025. }
  101026. return {
  101027. major: parseInt(match[1]),
  101028. minor: parseInt(match[2])
  101029. };
  101030. };
  101031. GLTFFileLoader._compareVersion = function (a, b) {
  101032. if (a.major > b.major)
  101033. return 1;
  101034. if (a.major < b.major)
  101035. return -1;
  101036. if (a.minor > b.minor)
  101037. return 1;
  101038. if (a.minor < b.minor)
  101039. return -1;
  101040. return 0;
  101041. };
  101042. GLTFFileLoader._decodeBufferToText = function (buffer) {
  101043. var result = "";
  101044. var length = buffer.byteLength;
  101045. for (var i = 0; i < length; i++) {
  101046. result += String.fromCharCode(buffer[i]);
  101047. }
  101048. return result;
  101049. };
  101050. // #endregion
  101051. // #region V1 options
  101052. /**
  101053. * 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.
  101054. * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.
  101055. * Defaults to true.
  101056. */
  101057. GLTFFileLoader.IncrementalLoading = true;
  101058. /**
  101059. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.
  101060. * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.
  101061. */
  101062. GLTFFileLoader.HomogeneousCoordinates = false;
  101063. return GLTFFileLoader;
  101064. }());
  101065. BABYLON.GLTFFileLoader = GLTFFileLoader;
  101066. var BinaryReader = /** @class */ (function () {
  101067. function BinaryReader(arrayBuffer) {
  101068. this._arrayBuffer = arrayBuffer;
  101069. this._dataView = new DataView(arrayBuffer);
  101070. this._byteOffset = 0;
  101071. }
  101072. BinaryReader.prototype.getPosition = function () {
  101073. return this._byteOffset;
  101074. };
  101075. BinaryReader.prototype.getLength = function () {
  101076. return this._arrayBuffer.byteLength;
  101077. };
  101078. BinaryReader.prototype.readUint32 = function () {
  101079. var value = this._dataView.getUint32(this._byteOffset, true);
  101080. this._byteOffset += 4;
  101081. return value;
  101082. };
  101083. BinaryReader.prototype.readUint8Array = function (length) {
  101084. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  101085. this._byteOffset += length;
  101086. return value;
  101087. };
  101088. BinaryReader.prototype.skipBytes = function (length) {
  101089. this._byteOffset += length;
  101090. };
  101091. return BinaryReader;
  101092. }());
  101093. if (BABYLON.SceneLoader) {
  101094. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  101095. }
  101096. })(BABYLON || (BABYLON = {}));
  101097. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  101098. var BABYLON;
  101099. (function (BABYLON) {
  101100. var GLTF1;
  101101. (function (GLTF1) {
  101102. /**
  101103. * Enums
  101104. */
  101105. var EComponentType;
  101106. (function (EComponentType) {
  101107. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  101108. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  101109. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  101110. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  101111. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  101112. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  101113. var EShaderType;
  101114. (function (EShaderType) {
  101115. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  101116. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  101117. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  101118. var EParameterType;
  101119. (function (EParameterType) {
  101120. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  101121. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  101122. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  101123. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  101124. EParameterType[EParameterType["INT"] = 5124] = "INT";
  101125. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  101126. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  101127. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  101128. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  101129. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  101130. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  101131. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  101132. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  101133. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  101134. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  101135. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  101136. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  101137. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  101138. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  101139. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  101140. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  101141. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  101142. var ETextureWrapMode;
  101143. (function (ETextureWrapMode) {
  101144. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  101145. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  101146. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  101147. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  101148. var ETextureFilterType;
  101149. (function (ETextureFilterType) {
  101150. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  101151. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  101152. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  101153. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  101154. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  101155. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  101156. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  101157. var ETextureFormat;
  101158. (function (ETextureFormat) {
  101159. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  101160. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  101161. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  101162. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  101163. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  101164. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  101165. var ECullingType;
  101166. (function (ECullingType) {
  101167. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  101168. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  101169. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  101170. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  101171. var EBlendingFunction;
  101172. (function (EBlendingFunction) {
  101173. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  101174. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  101175. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  101176. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  101177. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  101178. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  101179. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  101180. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  101181. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  101182. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  101183. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  101184. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  101185. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  101186. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  101187. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  101188. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  101189. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  101190. })(BABYLON || (BABYLON = {}));
  101191. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  101192. var BABYLON;
  101193. (function (BABYLON) {
  101194. var GLTF1;
  101195. (function (GLTF1) {
  101196. /**
  101197. * Tokenizer. Used for shaders compatibility
  101198. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  101199. */
  101200. var ETokenType;
  101201. (function (ETokenType) {
  101202. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  101203. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  101204. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  101205. })(ETokenType || (ETokenType = {}));
  101206. var Tokenizer = /** @class */ (function () {
  101207. function Tokenizer(toParse) {
  101208. this._pos = 0;
  101209. this.currentToken = ETokenType.UNKNOWN;
  101210. this.currentIdentifier = "";
  101211. this.currentString = "";
  101212. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  101213. this._toParse = toParse;
  101214. this._maxPos = toParse.length;
  101215. }
  101216. Tokenizer.prototype.getNextToken = function () {
  101217. if (this.isEnd())
  101218. return ETokenType.END_OF_INPUT;
  101219. this.currentString = this.read();
  101220. this.currentToken = ETokenType.UNKNOWN;
  101221. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  101222. this.currentToken = ETokenType.IDENTIFIER;
  101223. this.currentIdentifier = this.currentString;
  101224. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  101225. this.currentIdentifier += this.currentString;
  101226. this.forward();
  101227. }
  101228. }
  101229. return this.currentToken;
  101230. };
  101231. Tokenizer.prototype.peek = function () {
  101232. return this._toParse[this._pos];
  101233. };
  101234. Tokenizer.prototype.read = function () {
  101235. return this._toParse[this._pos++];
  101236. };
  101237. Tokenizer.prototype.forward = function () {
  101238. this._pos++;
  101239. };
  101240. Tokenizer.prototype.isEnd = function () {
  101241. return this._pos >= this._maxPos;
  101242. };
  101243. return Tokenizer;
  101244. }());
  101245. /**
  101246. * Values
  101247. */
  101248. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  101249. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  101250. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  101251. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  101252. /**
  101253. * Parse
  101254. */
  101255. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  101256. for (var buf in parsedBuffers) {
  101257. var parsedBuffer = parsedBuffers[buf];
  101258. gltfRuntime.buffers[buf] = parsedBuffer;
  101259. gltfRuntime.buffersCount++;
  101260. }
  101261. };
  101262. var parseShaders = function (parsedShaders, gltfRuntime) {
  101263. for (var sha in parsedShaders) {
  101264. var parsedShader = parsedShaders[sha];
  101265. gltfRuntime.shaders[sha] = parsedShader;
  101266. gltfRuntime.shaderscount++;
  101267. }
  101268. };
  101269. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  101270. for (var object in parsedObjects) {
  101271. var parsedObject = parsedObjects[object];
  101272. gltfRuntime[runtimeProperty][object] = parsedObject;
  101273. }
  101274. };
  101275. /**
  101276. * Utils
  101277. */
  101278. var normalizeUVs = function (buffer) {
  101279. if (!buffer) {
  101280. return;
  101281. }
  101282. for (var i = 0; i < buffer.length / 2; i++) {
  101283. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  101284. }
  101285. };
  101286. var getAttribute = function (attributeParameter) {
  101287. if (attributeParameter.semantic === "NORMAL") {
  101288. return "normal";
  101289. }
  101290. else if (attributeParameter.semantic === "POSITION") {
  101291. return "position";
  101292. }
  101293. else if (attributeParameter.semantic === "JOINT") {
  101294. return "matricesIndices";
  101295. }
  101296. else if (attributeParameter.semantic === "WEIGHT") {
  101297. return "matricesWeights";
  101298. }
  101299. else if (attributeParameter.semantic === "COLOR") {
  101300. return "color";
  101301. }
  101302. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  101303. var channel = Number(attributeParameter.semantic.split("_")[1]);
  101304. return "uv" + (channel === 0 ? "" : channel + 1);
  101305. }
  101306. return null;
  101307. };
  101308. /**
  101309. * Loads and creates animations
  101310. */
  101311. var loadAnimations = function (gltfRuntime) {
  101312. for (var anim in gltfRuntime.animations) {
  101313. var animation = gltfRuntime.animations[anim];
  101314. if (!animation.channels || !animation.samplers) {
  101315. continue;
  101316. }
  101317. var lastAnimation = null;
  101318. for (var i = 0; i < animation.channels.length; i++) {
  101319. // Get parameters and load buffers
  101320. var channel = animation.channels[i];
  101321. var sampler = animation.samplers[channel.sampler];
  101322. if (!sampler) {
  101323. continue;
  101324. }
  101325. var inputData = null;
  101326. var outputData = null;
  101327. if (animation.parameters) {
  101328. inputData = animation.parameters[sampler.input];
  101329. outputData = animation.parameters[sampler.output];
  101330. }
  101331. else {
  101332. inputData = sampler.input;
  101333. outputData = sampler.output;
  101334. }
  101335. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  101336. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  101337. var targetID = channel.target.id;
  101338. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  101339. if (targetNode === null) {
  101340. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  101341. }
  101342. if (targetNode === null) {
  101343. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  101344. continue;
  101345. }
  101346. var isBone = targetNode instanceof BABYLON.Bone;
  101347. // Get target path (position, rotation or scaling)
  101348. var targetPath = channel.target.path;
  101349. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  101350. if (targetPathIndex !== -1) {
  101351. targetPath = babylonAnimationPaths[targetPathIndex];
  101352. }
  101353. // Determine animation type
  101354. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  101355. if (!isBone) {
  101356. if (targetPath === "rotationQuaternion") {
  101357. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  101358. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  101359. }
  101360. else {
  101361. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  101362. }
  101363. }
  101364. // Create animation and key frames
  101365. var babylonAnimation = null;
  101366. var keys = [];
  101367. var arrayOffset = 0;
  101368. var modifyKey = false;
  101369. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  101370. babylonAnimation = lastAnimation;
  101371. modifyKey = true;
  101372. }
  101373. if (!modifyKey) {
  101374. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  101375. }
  101376. // For each frame
  101377. for (var j = 0; j < bufferInput.length; j++) {
  101378. var value = null;
  101379. if (targetPath === "rotationQuaternion") { // VEC4
  101380. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  101381. arrayOffset += 4;
  101382. }
  101383. else { // Position and scaling are VEC3
  101384. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  101385. arrayOffset += 3;
  101386. }
  101387. if (isBone) {
  101388. var bone = targetNode;
  101389. var translation = BABYLON.Vector3.Zero();
  101390. var rotationQuaternion = new BABYLON.Quaternion();
  101391. var scaling = BABYLON.Vector3.Zero();
  101392. // Warning on decompose
  101393. var mat = bone.getBaseMatrix();
  101394. if (modifyKey && lastAnimation) {
  101395. mat = lastAnimation.getKeys()[j].value;
  101396. }
  101397. mat.decompose(scaling, rotationQuaternion, translation);
  101398. if (targetPath === "position") {
  101399. translation = value;
  101400. }
  101401. else if (targetPath === "rotationQuaternion") {
  101402. rotationQuaternion = value;
  101403. }
  101404. else {
  101405. scaling = value;
  101406. }
  101407. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  101408. }
  101409. if (!modifyKey) {
  101410. keys.push({
  101411. frame: bufferInput[j],
  101412. value: value
  101413. });
  101414. }
  101415. else if (lastAnimation) {
  101416. lastAnimation.getKeys()[j].value = value;
  101417. }
  101418. }
  101419. // Finish
  101420. if (!modifyKey && babylonAnimation) {
  101421. babylonAnimation.setKeys(keys);
  101422. targetNode.animations.push(babylonAnimation);
  101423. }
  101424. lastAnimation = babylonAnimation;
  101425. gltfRuntime.scene.stopAnimation(targetNode);
  101426. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  101427. }
  101428. }
  101429. };
  101430. /**
  101431. * Returns the bones transformation matrix
  101432. */
  101433. var configureBoneTransformation = function (node) {
  101434. var mat = null;
  101435. if (node.translation || node.rotation || node.scale) {
  101436. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  101437. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  101438. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  101439. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  101440. }
  101441. else {
  101442. mat = BABYLON.Matrix.FromArray(node.matrix);
  101443. }
  101444. return mat;
  101445. };
  101446. /**
  101447. * Returns the parent bone
  101448. */
  101449. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  101450. // Try to find
  101451. for (var i = 0; i < newSkeleton.bones.length; i++) {
  101452. if (newSkeleton.bones[i].name === jointName) {
  101453. return newSkeleton.bones[i];
  101454. }
  101455. }
  101456. // Not found, search in gltf nodes
  101457. var nodes = gltfRuntime.nodes;
  101458. for (var nde in nodes) {
  101459. var node = nodes[nde];
  101460. if (!node.jointName) {
  101461. continue;
  101462. }
  101463. var children = node.children;
  101464. for (var i = 0; i < children.length; i++) {
  101465. var child = gltfRuntime.nodes[children[i]];
  101466. if (!child.jointName) {
  101467. continue;
  101468. }
  101469. if (child.jointName === jointName) {
  101470. var mat = configureBoneTransformation(node);
  101471. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  101472. bone.id = nde;
  101473. return bone;
  101474. }
  101475. }
  101476. }
  101477. return null;
  101478. };
  101479. /**
  101480. * Returns the appropriate root node
  101481. */
  101482. var getNodeToRoot = function (nodesToRoot, id) {
  101483. for (var i = 0; i < nodesToRoot.length; i++) {
  101484. var nodeToRoot = nodesToRoot[i];
  101485. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  101486. var child = nodeToRoot.node.children[j];
  101487. if (child === id) {
  101488. return nodeToRoot.bone;
  101489. }
  101490. }
  101491. }
  101492. return null;
  101493. };
  101494. /**
  101495. * Returns the node with the joint name
  101496. */
  101497. var getJointNode = function (gltfRuntime, jointName) {
  101498. var nodes = gltfRuntime.nodes;
  101499. var node = nodes[jointName];
  101500. if (node) {
  101501. return {
  101502. node: node,
  101503. id: jointName
  101504. };
  101505. }
  101506. for (var nde in nodes) {
  101507. node = nodes[nde];
  101508. if (node.jointName === jointName) {
  101509. return {
  101510. node: node,
  101511. id: nde
  101512. };
  101513. }
  101514. }
  101515. return null;
  101516. };
  101517. /**
  101518. * Checks if a nodes is in joints
  101519. */
  101520. var nodeIsInJoints = function (skins, id) {
  101521. for (var i = 0; i < skins.jointNames.length; i++) {
  101522. if (skins.jointNames[i] === id) {
  101523. return true;
  101524. }
  101525. }
  101526. return false;
  101527. };
  101528. /**
  101529. * Fills the nodes to root for bones and builds hierarchy
  101530. */
  101531. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  101532. // Creates nodes for root
  101533. for (var nde in gltfRuntime.nodes) {
  101534. var node = gltfRuntime.nodes[nde];
  101535. var id = nde;
  101536. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  101537. continue;
  101538. }
  101539. // Create node to root bone
  101540. var mat = configureBoneTransformation(node);
  101541. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  101542. bone.id = id;
  101543. nodesToRoot.push({ bone: bone, node: node, id: id });
  101544. }
  101545. // Parenting
  101546. for (var i = 0; i < nodesToRoot.length; i++) {
  101547. var nodeToRoot = nodesToRoot[i];
  101548. var children = nodeToRoot.node.children;
  101549. for (var j = 0; j < children.length; j++) {
  101550. var child = null;
  101551. for (var k = 0; k < nodesToRoot.length; k++) {
  101552. if (nodesToRoot[k].id === children[j]) {
  101553. child = nodesToRoot[k];
  101554. break;
  101555. }
  101556. }
  101557. if (child) {
  101558. child.bone._parent = nodeToRoot.bone;
  101559. nodeToRoot.bone.children.push(child.bone);
  101560. }
  101561. }
  101562. }
  101563. };
  101564. /**
  101565. * Imports a skeleton
  101566. */
  101567. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  101568. if (!newSkeleton) {
  101569. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  101570. }
  101571. if (!skins.babylonSkeleton) {
  101572. return newSkeleton;
  101573. }
  101574. // Find the root bones
  101575. var nodesToRoot = [];
  101576. var nodesToRootToAdd = [];
  101577. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  101578. newSkeleton.bones = [];
  101579. // Joints
  101580. for (var i = 0; i < skins.jointNames.length; i++) {
  101581. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  101582. if (!jointNode) {
  101583. continue;
  101584. }
  101585. var node = jointNode.node;
  101586. if (!node) {
  101587. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  101588. continue;
  101589. }
  101590. var id = jointNode.id;
  101591. // Optimize, if the bone already exists...
  101592. var existingBone = gltfRuntime.scene.getBoneByID(id);
  101593. if (existingBone) {
  101594. newSkeleton.bones.push(existingBone);
  101595. continue;
  101596. }
  101597. // Search for parent bone
  101598. var foundBone = false;
  101599. var parentBone = null;
  101600. for (var j = 0; j < i; j++) {
  101601. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  101602. if (!jointNode_1) {
  101603. continue;
  101604. }
  101605. var joint = jointNode_1.node;
  101606. if (!joint) {
  101607. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  101608. continue;
  101609. }
  101610. var children = joint.children;
  101611. if (!children) {
  101612. continue;
  101613. }
  101614. foundBone = false;
  101615. for (var k = 0; k < children.length; k++) {
  101616. if (children[k] === id) {
  101617. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  101618. foundBone = true;
  101619. break;
  101620. }
  101621. }
  101622. if (foundBone) {
  101623. break;
  101624. }
  101625. }
  101626. // Create bone
  101627. var mat = configureBoneTransformation(node);
  101628. if (!parentBone && nodesToRoot.length > 0) {
  101629. parentBone = getNodeToRoot(nodesToRoot, id);
  101630. if (parentBone) {
  101631. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  101632. nodesToRootToAdd.push(parentBone);
  101633. }
  101634. }
  101635. }
  101636. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  101637. bone.id = id;
  101638. }
  101639. // Polish
  101640. var bones = newSkeleton.bones;
  101641. newSkeleton.bones = [];
  101642. for (var i = 0; i < skins.jointNames.length; i++) {
  101643. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  101644. if (!jointNode) {
  101645. continue;
  101646. }
  101647. for (var j = 0; j < bones.length; j++) {
  101648. if (bones[j].id === jointNode.id) {
  101649. newSkeleton.bones.push(bones[j]);
  101650. break;
  101651. }
  101652. }
  101653. }
  101654. newSkeleton.prepare();
  101655. // Finish
  101656. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  101657. newSkeleton.bones.push(nodesToRootToAdd[i]);
  101658. }
  101659. return newSkeleton;
  101660. };
  101661. /**
  101662. * Imports a mesh and its geometries
  101663. */
  101664. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  101665. if (!newMesh) {
  101666. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  101667. newMesh.id = id;
  101668. }
  101669. if (!node.babylonNode) {
  101670. return newMesh;
  101671. }
  101672. var subMaterials = [];
  101673. var vertexData = null;
  101674. var verticesStarts = new Array();
  101675. var verticesCounts = new Array();
  101676. var indexStarts = new Array();
  101677. var indexCounts = new Array();
  101678. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  101679. var meshID = meshes[meshIndex];
  101680. var mesh = gltfRuntime.meshes[meshID];
  101681. if (!mesh) {
  101682. continue;
  101683. }
  101684. // Positions, normals and UVs
  101685. for (var i = 0; i < mesh.primitives.length; i++) {
  101686. // Temporary vertex data
  101687. var tempVertexData = new BABYLON.VertexData();
  101688. var primitive = mesh.primitives[i];
  101689. if (primitive.mode !== 4) {
  101690. // continue;
  101691. }
  101692. var attributes = primitive.attributes;
  101693. var accessor = null;
  101694. var buffer = null;
  101695. // Set positions, normal and uvs
  101696. for (var semantic in attributes) {
  101697. // Link accessor and buffer view
  101698. accessor = gltfRuntime.accessors[attributes[semantic]];
  101699. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  101700. if (semantic === "NORMAL") {
  101701. tempVertexData.normals = new Float32Array(buffer.length);
  101702. tempVertexData.normals.set(buffer);
  101703. }
  101704. else if (semantic === "POSITION") {
  101705. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  101706. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  101707. for (var j = 0; j < buffer.length; j += 4) {
  101708. tempVertexData.positions[j] = buffer[j];
  101709. tempVertexData.positions[j + 1] = buffer[j + 1];
  101710. tempVertexData.positions[j + 2] = buffer[j + 2];
  101711. }
  101712. }
  101713. else {
  101714. tempVertexData.positions = new Float32Array(buffer.length);
  101715. tempVertexData.positions.set(buffer);
  101716. }
  101717. verticesCounts.push(tempVertexData.positions.length);
  101718. }
  101719. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  101720. var channel = Number(semantic.split("_")[1]);
  101721. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  101722. var uvs = new Float32Array(buffer.length);
  101723. uvs.set(buffer);
  101724. normalizeUVs(uvs);
  101725. tempVertexData.set(uvs, uvKind);
  101726. }
  101727. else if (semantic === "JOINT") {
  101728. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  101729. tempVertexData.matricesIndices.set(buffer);
  101730. }
  101731. else if (semantic === "WEIGHT") {
  101732. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  101733. tempVertexData.matricesWeights.set(buffer);
  101734. }
  101735. else if (semantic === "COLOR") {
  101736. tempVertexData.colors = new Float32Array(buffer.length);
  101737. tempVertexData.colors.set(buffer);
  101738. }
  101739. }
  101740. // Indices
  101741. accessor = gltfRuntime.accessors[primitive.indices];
  101742. if (accessor) {
  101743. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  101744. tempVertexData.indices = new Int32Array(buffer.length);
  101745. tempVertexData.indices.set(buffer);
  101746. indexCounts.push(tempVertexData.indices.length);
  101747. }
  101748. else {
  101749. // Set indices on the fly
  101750. var indices = [];
  101751. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  101752. indices.push(j);
  101753. }
  101754. tempVertexData.indices = new Int32Array(indices);
  101755. indexCounts.push(tempVertexData.indices.length);
  101756. }
  101757. if (!vertexData) {
  101758. vertexData = tempVertexData;
  101759. }
  101760. else {
  101761. vertexData.merge(tempVertexData);
  101762. }
  101763. // Sub material
  101764. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  101765. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  101766. // Update vertices start and index start
  101767. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  101768. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  101769. }
  101770. }
  101771. var material;
  101772. if (subMaterials.length > 1) {
  101773. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  101774. material.subMaterials = subMaterials;
  101775. }
  101776. else {
  101777. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  101778. }
  101779. if (subMaterials.length === 1) {
  101780. material = subMaterials[0];
  101781. }
  101782. if (!newMesh.material) {
  101783. newMesh.material = material;
  101784. }
  101785. // Apply geometry
  101786. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  101787. newMesh.computeWorldMatrix(true);
  101788. // Apply submeshes
  101789. newMesh.subMeshes = [];
  101790. var index = 0;
  101791. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  101792. var meshID = meshes[meshIndex];
  101793. var mesh = gltfRuntime.meshes[meshID];
  101794. if (!mesh) {
  101795. continue;
  101796. }
  101797. for (var i = 0; i < mesh.primitives.length; i++) {
  101798. if (mesh.primitives[i].mode !== 4) {
  101799. //continue;
  101800. }
  101801. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  101802. index++;
  101803. }
  101804. }
  101805. // Finish
  101806. return newMesh;
  101807. };
  101808. /**
  101809. * Configure node transformation from position, rotation and scaling
  101810. */
  101811. var configureNode = function (newNode, position, rotation, scaling) {
  101812. if (newNode.position) {
  101813. newNode.position = position;
  101814. }
  101815. if (newNode.rotationQuaternion || newNode.rotation) {
  101816. newNode.rotationQuaternion = rotation;
  101817. }
  101818. if (newNode.scaling) {
  101819. newNode.scaling = scaling;
  101820. }
  101821. };
  101822. /**
  101823. * Configures node from transformation matrix
  101824. */
  101825. var configureNodeFromMatrix = function (newNode, node, parent) {
  101826. if (node.matrix) {
  101827. var position = new BABYLON.Vector3(0, 0, 0);
  101828. var rotation = new BABYLON.Quaternion();
  101829. var scaling = new BABYLON.Vector3(0, 0, 0);
  101830. var mat = BABYLON.Matrix.FromArray(node.matrix);
  101831. mat.decompose(scaling, rotation, position);
  101832. configureNode(newNode, position, rotation, scaling);
  101833. }
  101834. else if (node.translation && node.rotation && node.scale) {
  101835. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  101836. }
  101837. newNode.computeWorldMatrix(true);
  101838. };
  101839. /**
  101840. * Imports a node
  101841. */
  101842. var importNode = function (gltfRuntime, node, id, parent) {
  101843. var lastNode = null;
  101844. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  101845. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  101846. return null;
  101847. }
  101848. }
  101849. // Meshes
  101850. if (node.skin) {
  101851. if (node.meshes) {
  101852. var skin = gltfRuntime.skins[node.skin];
  101853. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  101854. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  101855. if (newMesh.skeleton === null) {
  101856. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  101857. if (!skin.babylonSkeleton) {
  101858. skin.babylonSkeleton = newMesh.skeleton;
  101859. }
  101860. }
  101861. lastNode = newMesh;
  101862. }
  101863. }
  101864. else if (node.meshes) {
  101865. /**
  101866. * Improve meshes property
  101867. */
  101868. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  101869. lastNode = newMesh;
  101870. }
  101871. // Lights
  101872. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  101873. var light = gltfRuntime.lights[node.light];
  101874. if (light) {
  101875. if (light.type === "ambient") {
  101876. var ambienLight = light[light.type];
  101877. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  101878. hemiLight.name = node.name || "";
  101879. if (ambienLight.color) {
  101880. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  101881. }
  101882. lastNode = hemiLight;
  101883. }
  101884. else if (light.type === "directional") {
  101885. var directionalLight = light[light.type];
  101886. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  101887. dirLight.name = node.name || "";
  101888. if (directionalLight.color) {
  101889. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  101890. }
  101891. lastNode = dirLight;
  101892. }
  101893. else if (light.type === "point") {
  101894. var pointLight = light[light.type];
  101895. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  101896. ptLight.name = node.name || "";
  101897. if (pointLight.color) {
  101898. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  101899. }
  101900. lastNode = ptLight;
  101901. }
  101902. else if (light.type === "spot") {
  101903. var spotLight = light[light.type];
  101904. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  101905. spLight.name = node.name || "";
  101906. if (spotLight.color) {
  101907. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  101908. }
  101909. if (spotLight.fallOfAngle) {
  101910. spLight.angle = spotLight.fallOfAngle;
  101911. }
  101912. if (spotLight.fallOffExponent) {
  101913. spLight.exponent = spotLight.fallOffExponent;
  101914. }
  101915. lastNode = spLight;
  101916. }
  101917. }
  101918. }
  101919. // Cameras
  101920. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  101921. var camera = gltfRuntime.cameras[node.camera];
  101922. if (camera) {
  101923. if (camera.type === "orthographic") {
  101924. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  101925. orthoCamera.name = node.name || "";
  101926. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  101927. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  101928. lastNode = orthoCamera;
  101929. }
  101930. else if (camera.type === "perspective") {
  101931. var perspectiveCamera = camera[camera.type];
  101932. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  101933. persCamera.name = node.name || "";
  101934. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  101935. if (!perspectiveCamera.aspectRatio) {
  101936. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  101937. }
  101938. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  101939. persCamera.maxZ = perspectiveCamera.zfar;
  101940. persCamera.minZ = perspectiveCamera.znear;
  101941. }
  101942. lastNode = persCamera;
  101943. }
  101944. }
  101945. }
  101946. // Empty node
  101947. if (!node.jointName) {
  101948. if (node.babylonNode) {
  101949. return node.babylonNode;
  101950. }
  101951. else if (lastNode === null) {
  101952. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  101953. node.babylonNode = dummy;
  101954. lastNode = dummy;
  101955. }
  101956. }
  101957. if (lastNode !== null) {
  101958. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  101959. configureNodeFromMatrix(lastNode, node, parent);
  101960. }
  101961. else {
  101962. var translation = node.translation || [0, 0, 0];
  101963. var rotation = node.rotation || [0, 0, 0, 1];
  101964. var scale = node.scale || [1, 1, 1];
  101965. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  101966. }
  101967. lastNode.updateCache(true);
  101968. node.babylonNode = lastNode;
  101969. }
  101970. return lastNode;
  101971. };
  101972. /**
  101973. * Traverses nodes and creates them
  101974. */
  101975. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  101976. if (meshIncluded === void 0) { meshIncluded = false; }
  101977. var node = gltfRuntime.nodes[id];
  101978. var newNode = null;
  101979. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  101980. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  101981. meshIncluded = true;
  101982. }
  101983. else {
  101984. meshIncluded = false;
  101985. }
  101986. }
  101987. else {
  101988. meshIncluded = true;
  101989. }
  101990. if (!node.jointName && meshIncluded) {
  101991. newNode = importNode(gltfRuntime, node, id, parent);
  101992. if (newNode !== null) {
  101993. newNode.id = id;
  101994. newNode.parent = parent;
  101995. }
  101996. }
  101997. if (node.children) {
  101998. for (var i = 0; i < node.children.length; i++) {
  101999. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  102000. }
  102001. }
  102002. };
  102003. /**
  102004. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  102005. */
  102006. var postLoad = function (gltfRuntime) {
  102007. // Nodes
  102008. var currentScene = gltfRuntime.currentScene;
  102009. if (currentScene) {
  102010. for (var i = 0; i < currentScene.nodes.length; i++) {
  102011. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  102012. }
  102013. }
  102014. else {
  102015. for (var thing in gltfRuntime.scenes) {
  102016. currentScene = gltfRuntime.scenes[thing];
  102017. for (var i = 0; i < currentScene.nodes.length; i++) {
  102018. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  102019. }
  102020. }
  102021. }
  102022. // Set animations
  102023. loadAnimations(gltfRuntime);
  102024. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  102025. var skeleton = gltfRuntime.scene.skeletons[i];
  102026. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  102027. }
  102028. };
  102029. /**
  102030. * onBind shaderrs callback to set uniforms and matrices
  102031. */
  102032. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  102033. var materialValues = material.values || technique.parameters;
  102034. for (var unif in unTreatedUniforms) {
  102035. var uniform = unTreatedUniforms[unif];
  102036. var type = uniform.type;
  102037. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  102038. if (uniform.semantic && !uniform.source && !uniform.node) {
  102039. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  102040. }
  102041. else if (uniform.semantic && (uniform.source || uniform.node)) {
  102042. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  102043. if (source === null) {
  102044. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  102045. }
  102046. if (source === null) {
  102047. continue;
  102048. }
  102049. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  102050. }
  102051. }
  102052. else {
  102053. var value = materialValues[technique.uniforms[unif]];
  102054. if (!value) {
  102055. continue;
  102056. }
  102057. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  102058. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  102059. if (texture === null || texture === undefined) {
  102060. continue;
  102061. }
  102062. shaderMaterial.getEffect().setTexture(unif, texture);
  102063. }
  102064. else {
  102065. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  102066. }
  102067. }
  102068. }
  102069. onSuccess(shaderMaterial);
  102070. };
  102071. /**
  102072. * Prepare uniforms to send the only one time
  102073. * Loads the appropriate textures
  102074. */
  102075. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  102076. var materialValues = material.values || technique.parameters;
  102077. var techniqueUniforms = technique.uniforms;
  102078. /**
  102079. * Prepare values here (not matrices)
  102080. */
  102081. for (var unif in unTreatedUniforms) {
  102082. var uniform = unTreatedUniforms[unif];
  102083. var type = uniform.type;
  102084. var value = materialValues[techniqueUniforms[unif]];
  102085. if (value === undefined) {
  102086. // In case the value is the same for all materials
  102087. value = uniform.value;
  102088. }
  102089. if (!value) {
  102090. continue;
  102091. }
  102092. var onLoadTexture = function (uniformName) {
  102093. return function (texture) {
  102094. if (uniform.value && uniformName) {
  102095. // Static uniform
  102096. shaderMaterial.setTexture(uniformName, texture);
  102097. delete unTreatedUniforms[uniformName];
  102098. }
  102099. };
  102100. };
  102101. // Texture (sampler2D)
  102102. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  102103. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  102104. }
  102105. // Others
  102106. else {
  102107. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  102108. // Static uniform
  102109. delete unTreatedUniforms[unif];
  102110. }
  102111. }
  102112. }
  102113. };
  102114. /**
  102115. * Shader compilation failed
  102116. */
  102117. var onShaderCompileError = function (program, shaderMaterial, onError) {
  102118. return function (effect, error) {
  102119. shaderMaterial.dispose(true);
  102120. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  102121. };
  102122. };
  102123. /**
  102124. * Shader compilation success
  102125. */
  102126. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  102127. return function (_) {
  102128. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  102129. shaderMaterial.onBind = function (mesh) {
  102130. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  102131. };
  102132. };
  102133. };
  102134. /**
  102135. * Returns the appropriate uniform if already handled by babylon
  102136. */
  102137. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  102138. for (var unif in technique.uniforms) {
  102139. var uniform = technique.uniforms[unif];
  102140. var uniformParameter = technique.parameters[uniform];
  102141. if (tokenizer.currentIdentifier === unif) {
  102142. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  102143. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  102144. if (transformIndex !== -1) {
  102145. delete unTreatedUniforms[unif];
  102146. return babylonTransforms[transformIndex];
  102147. }
  102148. }
  102149. }
  102150. }
  102151. return tokenizer.currentIdentifier;
  102152. };
  102153. /**
  102154. * All shaders loaded. Create materials one by one
  102155. */
  102156. var importMaterials = function (gltfRuntime) {
  102157. // Create materials
  102158. for (var mat in gltfRuntime.materials) {
  102159. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  102160. }
  102161. };
  102162. /**
  102163. * Implementation of the base glTF spec
  102164. */
  102165. var GLTFLoaderBase = /** @class */ (function () {
  102166. function GLTFLoaderBase() {
  102167. }
  102168. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  102169. var gltfRuntime = {
  102170. extensions: {},
  102171. accessors: {},
  102172. buffers: {},
  102173. bufferViews: {},
  102174. meshes: {},
  102175. lights: {},
  102176. cameras: {},
  102177. nodes: {},
  102178. images: {},
  102179. textures: {},
  102180. shaders: {},
  102181. programs: {},
  102182. samplers: {},
  102183. techniques: {},
  102184. materials: {},
  102185. animations: {},
  102186. skins: {},
  102187. extensionsUsed: [],
  102188. scenes: {},
  102189. buffersCount: 0,
  102190. shaderscount: 0,
  102191. scene: scene,
  102192. rootUrl: rootUrl,
  102193. loadedBufferCount: 0,
  102194. loadedBufferViews: {},
  102195. loadedShaderCount: 0,
  102196. importOnlyMeshes: false,
  102197. dummyNodes: []
  102198. };
  102199. // Parse
  102200. if (parsedData.extensions) {
  102201. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  102202. }
  102203. if (parsedData.extensionsUsed) {
  102204. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  102205. }
  102206. if (parsedData.buffers) {
  102207. parseBuffers(parsedData.buffers, gltfRuntime);
  102208. }
  102209. if (parsedData.bufferViews) {
  102210. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  102211. }
  102212. if (parsedData.accessors) {
  102213. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  102214. }
  102215. if (parsedData.meshes) {
  102216. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  102217. }
  102218. if (parsedData.lights) {
  102219. parseObject(parsedData.lights, "lights", gltfRuntime);
  102220. }
  102221. if (parsedData.cameras) {
  102222. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  102223. }
  102224. if (parsedData.nodes) {
  102225. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  102226. }
  102227. if (parsedData.images) {
  102228. parseObject(parsedData.images, "images", gltfRuntime);
  102229. }
  102230. if (parsedData.textures) {
  102231. parseObject(parsedData.textures, "textures", gltfRuntime);
  102232. }
  102233. if (parsedData.shaders) {
  102234. parseShaders(parsedData.shaders, gltfRuntime);
  102235. }
  102236. if (parsedData.programs) {
  102237. parseObject(parsedData.programs, "programs", gltfRuntime);
  102238. }
  102239. if (parsedData.samplers) {
  102240. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  102241. }
  102242. if (parsedData.techniques) {
  102243. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  102244. }
  102245. if (parsedData.materials) {
  102246. parseObject(parsedData.materials, "materials", gltfRuntime);
  102247. }
  102248. if (parsedData.animations) {
  102249. parseObject(parsedData.animations, "animations", gltfRuntime);
  102250. }
  102251. if (parsedData.skins) {
  102252. parseObject(parsedData.skins, "skins", gltfRuntime);
  102253. }
  102254. if (parsedData.scenes) {
  102255. gltfRuntime.scenes = parsedData.scenes;
  102256. }
  102257. if (parsedData.scene && parsedData.scenes) {
  102258. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  102259. }
  102260. return gltfRuntime;
  102261. };
  102262. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  102263. var buffer = gltfRuntime.buffers[id];
  102264. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  102265. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  102266. }
  102267. else {
  102268. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  102269. if (request) {
  102270. onError(request.status + " " + request.statusText);
  102271. }
  102272. });
  102273. }
  102274. };
  102275. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  102276. var texture = gltfRuntime.textures[id];
  102277. if (!texture || !texture.source) {
  102278. onError("");
  102279. return;
  102280. }
  102281. if (texture.babylonTexture) {
  102282. onSuccess(null);
  102283. return;
  102284. }
  102285. var source = gltfRuntime.images[texture.source];
  102286. if (BABYLON.Tools.IsBase64(source.uri)) {
  102287. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  102288. }
  102289. else {
  102290. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  102291. if (request) {
  102292. onError(request.status + " " + request.statusText);
  102293. }
  102294. });
  102295. }
  102296. };
  102297. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  102298. var texture = gltfRuntime.textures[id];
  102299. if (texture.babylonTexture) {
  102300. onSuccess(texture.babylonTexture);
  102301. return;
  102302. }
  102303. var sampler = gltfRuntime.samplers[texture.sampler];
  102304. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  102305. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  102306. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  102307. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  102308. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  102309. var blob = new Blob([buffer]);
  102310. var blobURL = URL.createObjectURL(blob);
  102311. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  102312. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  102313. if (sampler.wrapS !== undefined) {
  102314. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  102315. }
  102316. if (sampler.wrapT !== undefined) {
  102317. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  102318. }
  102319. newTexture.name = id;
  102320. texture.babylonTexture = newTexture;
  102321. onSuccess(newTexture);
  102322. };
  102323. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  102324. var shader = gltfRuntime.shaders[id];
  102325. if (BABYLON.Tools.IsBase64(shader.uri)) {
  102326. var shaderString = atob(shader.uri.split(",")[1]);
  102327. if (onSuccess) {
  102328. onSuccess(shaderString);
  102329. }
  102330. }
  102331. else {
  102332. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  102333. if (request && onError) {
  102334. onError(request.status + " " + request.statusText);
  102335. }
  102336. });
  102337. }
  102338. };
  102339. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  102340. var material = gltfRuntime.materials[id];
  102341. if (!material.technique) {
  102342. if (onError) {
  102343. onError("No technique found.");
  102344. }
  102345. return;
  102346. }
  102347. var technique = gltfRuntime.techniques[material.technique];
  102348. if (!technique) {
  102349. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  102350. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  102351. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  102352. onSuccess(defaultMaterial);
  102353. return;
  102354. }
  102355. var program = gltfRuntime.programs[technique.program];
  102356. var states = technique.states;
  102357. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  102358. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  102359. var newVertexShader = "";
  102360. var newPixelShader = "";
  102361. var vertexTokenizer = new Tokenizer(vertexShader);
  102362. var pixelTokenizer = new Tokenizer(pixelShader);
  102363. var unTreatedUniforms = {};
  102364. var uniforms = [];
  102365. var attributes = [];
  102366. var samplers = [];
  102367. // Fill uniform, sampler2D and attributes
  102368. for (var unif in technique.uniforms) {
  102369. var uniform = technique.uniforms[unif];
  102370. var uniformParameter = technique.parameters[uniform];
  102371. unTreatedUniforms[unif] = uniformParameter;
  102372. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  102373. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  102374. if (transformIndex !== -1) {
  102375. uniforms.push(babylonTransforms[transformIndex]);
  102376. delete unTreatedUniforms[unif];
  102377. }
  102378. else {
  102379. uniforms.push(unif);
  102380. }
  102381. }
  102382. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  102383. samplers.push(unif);
  102384. }
  102385. else {
  102386. uniforms.push(unif);
  102387. }
  102388. }
  102389. for (var attr in technique.attributes) {
  102390. var attribute = technique.attributes[attr];
  102391. var attributeParameter = technique.parameters[attribute];
  102392. if (attributeParameter.semantic) {
  102393. attributes.push(getAttribute(attributeParameter));
  102394. }
  102395. }
  102396. // Configure vertex shader
  102397. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  102398. var tokenType = vertexTokenizer.currentToken;
  102399. if (tokenType !== ETokenType.IDENTIFIER) {
  102400. newVertexShader += vertexTokenizer.currentString;
  102401. continue;
  102402. }
  102403. var foundAttribute = false;
  102404. for (var attr in technique.attributes) {
  102405. var attribute = technique.attributes[attr];
  102406. var attributeParameter = technique.parameters[attribute];
  102407. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  102408. newVertexShader += getAttribute(attributeParameter);
  102409. foundAttribute = true;
  102410. break;
  102411. }
  102412. }
  102413. if (foundAttribute) {
  102414. continue;
  102415. }
  102416. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  102417. }
  102418. // Configure pixel shader
  102419. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  102420. var tokenType = pixelTokenizer.currentToken;
  102421. if (tokenType !== ETokenType.IDENTIFIER) {
  102422. newPixelShader += pixelTokenizer.currentString;
  102423. continue;
  102424. }
  102425. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  102426. }
  102427. // Create shader material
  102428. var shaderPath = {
  102429. vertex: program.vertexShader + id,
  102430. fragment: program.fragmentShader + id
  102431. };
  102432. var options = {
  102433. attributes: attributes,
  102434. uniforms: uniforms,
  102435. samplers: samplers,
  102436. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  102437. };
  102438. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  102439. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  102440. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  102441. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  102442. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  102443. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  102444. if (states && states.functions) {
  102445. var functions = states.functions;
  102446. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  102447. shaderMaterial.backFaceCulling = false;
  102448. }
  102449. var blendFunc = functions.blendFuncSeparate;
  102450. if (blendFunc) {
  102451. 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) {
  102452. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  102453. }
  102454. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  102455. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  102456. }
  102457. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  102458. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  102459. }
  102460. 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) {
  102461. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  102462. }
  102463. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  102464. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  102465. }
  102466. 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) {
  102467. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  102468. }
  102469. }
  102470. }
  102471. };
  102472. return GLTFLoaderBase;
  102473. }());
  102474. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  102475. /**
  102476. * glTF V1 Loader
  102477. */
  102478. var GLTFLoader = /** @class */ (function () {
  102479. function GLTFLoader() {
  102480. // #region Stubs for IGLTFLoader interface
  102481. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  102482. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  102483. this.compileMaterials = false;
  102484. this.useClipPlane = false;
  102485. this.compileShadowGenerators = false;
  102486. this.transparencyAsCoverage = false;
  102487. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  102488. this.onMeshLoadedObservable = new BABYLON.Observable();
  102489. this.onTextureLoadedObservable = new BABYLON.Observable();
  102490. this.onMaterialLoadedObservable = new BABYLON.Observable();
  102491. this.onCameraLoadedObservable = new BABYLON.Observable();
  102492. this.onCompleteObservable = new BABYLON.Observable();
  102493. this.onDisposeObservable = new BABYLON.Observable();
  102494. this.onExtensionLoadedObservable = new BABYLON.Observable();
  102495. this.state = null;
  102496. }
  102497. GLTFLoader.RegisterExtension = function (extension) {
  102498. if (GLTFLoader.Extensions[extension.name]) {
  102499. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  102500. return;
  102501. }
  102502. GLTFLoader.Extensions[extension.name] = extension;
  102503. };
  102504. GLTFLoader.prototype.dispose = function () { };
  102505. // #endregion
  102506. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  102507. var _this = this;
  102508. scene.useRightHandedSystem = true;
  102509. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  102510. gltfRuntime.importOnlyMeshes = true;
  102511. if (meshesNames === "") {
  102512. gltfRuntime.importMeshesNames = [];
  102513. }
  102514. else if (typeof meshesNames === "string") {
  102515. gltfRuntime.importMeshesNames = [meshesNames];
  102516. }
  102517. else if (meshesNames && !(meshesNames instanceof Array)) {
  102518. gltfRuntime.importMeshesNames = [meshesNames];
  102519. }
  102520. else {
  102521. gltfRuntime.importMeshesNames = [];
  102522. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  102523. }
  102524. // Create nodes
  102525. _this._createNodes(gltfRuntime);
  102526. var meshes = new Array();
  102527. var skeletons = new Array();
  102528. // Fill arrays of meshes and skeletons
  102529. for (var nde in gltfRuntime.nodes) {
  102530. var node = gltfRuntime.nodes[nde];
  102531. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  102532. meshes.push(node.babylonNode);
  102533. }
  102534. }
  102535. for (var skl in gltfRuntime.skins) {
  102536. var skin = gltfRuntime.skins[skl];
  102537. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  102538. skeletons.push(skin.babylonSkeleton);
  102539. }
  102540. }
  102541. // Load buffers, shaders, materials, etc.
  102542. _this._loadBuffersAsync(gltfRuntime, function () {
  102543. _this._loadShadersAsync(gltfRuntime, function () {
  102544. importMaterials(gltfRuntime);
  102545. postLoad(gltfRuntime);
  102546. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  102547. onSuccess(meshes, skeletons);
  102548. }
  102549. });
  102550. }, onProgress);
  102551. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  102552. onSuccess(meshes, skeletons);
  102553. }
  102554. }, onError);
  102555. return true;
  102556. };
  102557. /**
  102558. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  102559. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  102560. * @param scene the scene the meshes should be added to
  102561. * @param data gltf data containing information of the meshes in a loaded file
  102562. * @param rootUrl root url to load from
  102563. * @param onProgress event that fires when loading progress has occured
  102564. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  102565. */
  102566. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  102567. var _this = this;
  102568. return new Promise(function (resolve, reject) {
  102569. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  102570. resolve({
  102571. meshes: meshes,
  102572. particleSystems: [],
  102573. skeletons: skeletons,
  102574. animationGroups: []
  102575. });
  102576. }, onProgress, function (message) {
  102577. reject(new Error(message));
  102578. });
  102579. });
  102580. };
  102581. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  102582. var _this = this;
  102583. scene.useRightHandedSystem = true;
  102584. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  102585. // Load runtime extensios
  102586. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  102587. // Create nodes
  102588. _this._createNodes(gltfRuntime);
  102589. // Load buffers, shaders, materials, etc.
  102590. _this._loadBuffersAsync(gltfRuntime, function () {
  102591. _this._loadShadersAsync(gltfRuntime, function () {
  102592. importMaterials(gltfRuntime);
  102593. postLoad(gltfRuntime);
  102594. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  102595. onSuccess();
  102596. }
  102597. });
  102598. });
  102599. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  102600. onSuccess();
  102601. }
  102602. }, onError);
  102603. }, onError);
  102604. };
  102605. /**
  102606. * Imports all objects from a loaded gltf file and adds them to the scene
  102607. * @param scene the scene the objects should be added to
  102608. * @param data gltf data containing information of the meshes in a loaded file
  102609. * @param rootUrl root url to load from
  102610. * @param onProgress event that fires when loading progress has occured
  102611. * @returns a promise which completes when objects have been loaded to the scene
  102612. */
  102613. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  102614. var _this = this;
  102615. return new Promise(function (resolve, reject) {
  102616. _this._loadAsync(scene, data, rootUrl, function () {
  102617. resolve();
  102618. }, onProgress, function (message) {
  102619. reject(new Error(message));
  102620. });
  102621. });
  102622. };
  102623. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  102624. var hasShaders = false;
  102625. var processShader = function (sha, shader) {
  102626. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  102627. if (shaderString instanceof ArrayBuffer) {
  102628. return;
  102629. }
  102630. gltfRuntime.loadedShaderCount++;
  102631. if (shaderString) {
  102632. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  102633. }
  102634. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  102635. onload();
  102636. }
  102637. }, function () {
  102638. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  102639. });
  102640. };
  102641. for (var sha in gltfRuntime.shaders) {
  102642. hasShaders = true;
  102643. var shader = gltfRuntime.shaders[sha];
  102644. if (shader) {
  102645. processShader.bind(this, sha, shader)();
  102646. }
  102647. else {
  102648. BABYLON.Tools.Error("No shader named: " + sha);
  102649. }
  102650. }
  102651. if (!hasShaders) {
  102652. onload();
  102653. }
  102654. };
  102655. ;
  102656. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  102657. var hasBuffers = false;
  102658. var processBuffer = function (buf, buffer) {
  102659. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  102660. gltfRuntime.loadedBufferCount++;
  102661. if (bufferView) {
  102662. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  102663. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  102664. }
  102665. gltfRuntime.loadedBufferViews[buf] = bufferView;
  102666. }
  102667. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  102668. onLoad();
  102669. }
  102670. }, function () {
  102671. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  102672. });
  102673. };
  102674. for (var buf in gltfRuntime.buffers) {
  102675. hasBuffers = true;
  102676. var buffer = gltfRuntime.buffers[buf];
  102677. if (buffer) {
  102678. processBuffer.bind(this, buf, buffer)();
  102679. }
  102680. else {
  102681. BABYLON.Tools.Error("No buffer named: " + buf);
  102682. }
  102683. }
  102684. if (!hasBuffers) {
  102685. onLoad();
  102686. }
  102687. };
  102688. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  102689. var currentScene = gltfRuntime.currentScene;
  102690. if (currentScene) {
  102691. // Only one scene even if multiple scenes are defined
  102692. for (var i = 0; i < currentScene.nodes.length; i++) {
  102693. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  102694. }
  102695. }
  102696. else {
  102697. // Load all scenes
  102698. for (var thing in gltfRuntime.scenes) {
  102699. currentScene = gltfRuntime.scenes[thing];
  102700. for (var i = 0; i < currentScene.nodes.length; i++) {
  102701. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  102702. }
  102703. }
  102704. }
  102705. };
  102706. GLTFLoader.Extensions = {};
  102707. return GLTFLoader;
  102708. }());
  102709. GLTF1.GLTFLoader = GLTFLoader;
  102710. ;
  102711. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  102712. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  102713. })(BABYLON || (BABYLON = {}));
  102714. //# sourceMappingURL=babylon.glTFLoader.js.map
  102715. var BABYLON;
  102716. (function (BABYLON) {
  102717. var GLTF1;
  102718. (function (GLTF1) {
  102719. /**
  102720. * Utils functions for GLTF
  102721. */
  102722. var GLTFUtils = /** @class */ (function () {
  102723. function GLTFUtils() {
  102724. }
  102725. /**
  102726. * Sets the given "parameter" matrix
  102727. * @param scene: the {BABYLON.Scene} object
  102728. * @param source: the source node where to pick the matrix
  102729. * @param parameter: the GLTF technique parameter
  102730. * @param uniformName: the name of the shader's uniform
  102731. * @param shaderMaterial: the shader material
  102732. */
  102733. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  102734. var mat = null;
  102735. if (parameter.semantic === "MODEL") {
  102736. mat = source.getWorldMatrix();
  102737. }
  102738. else if (parameter.semantic === "PROJECTION") {
  102739. mat = scene.getProjectionMatrix();
  102740. }
  102741. else if (parameter.semantic === "VIEW") {
  102742. mat = scene.getViewMatrix();
  102743. }
  102744. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  102745. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  102746. }
  102747. else if (parameter.semantic === "MODELVIEW") {
  102748. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  102749. }
  102750. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  102751. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  102752. }
  102753. else if (parameter.semantic === "MODELINVERSE") {
  102754. mat = source.getWorldMatrix().invert();
  102755. }
  102756. else if (parameter.semantic === "VIEWINVERSE") {
  102757. mat = scene.getViewMatrix().invert();
  102758. }
  102759. else if (parameter.semantic === "PROJECTIONINVERSE") {
  102760. mat = scene.getProjectionMatrix().invert();
  102761. }
  102762. else if (parameter.semantic === "MODELVIEWINVERSE") {
  102763. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  102764. }
  102765. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  102766. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  102767. }
  102768. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  102769. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  102770. }
  102771. else {
  102772. debugger;
  102773. }
  102774. if (mat) {
  102775. switch (parameter.type) {
  102776. case GLTF1.EParameterType.FLOAT_MAT2:
  102777. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  102778. break;
  102779. case GLTF1.EParameterType.FLOAT_MAT3:
  102780. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  102781. break;
  102782. case GLTF1.EParameterType.FLOAT_MAT4:
  102783. shaderMaterial.setMatrix(uniformName, mat);
  102784. break;
  102785. default: break;
  102786. }
  102787. }
  102788. };
  102789. /**
  102790. * Sets the given "parameter" matrix
  102791. * @param shaderMaterial: the shader material
  102792. * @param uniform: the name of the shader's uniform
  102793. * @param value: the value of the uniform
  102794. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  102795. */
  102796. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  102797. switch (type) {
  102798. case GLTF1.EParameterType.FLOAT:
  102799. shaderMaterial.setFloat(uniform, value);
  102800. return true;
  102801. case GLTF1.EParameterType.FLOAT_VEC2:
  102802. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  102803. return true;
  102804. case GLTF1.EParameterType.FLOAT_VEC3:
  102805. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  102806. return true;
  102807. case GLTF1.EParameterType.FLOAT_VEC4:
  102808. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  102809. return true;
  102810. default: return false;
  102811. }
  102812. };
  102813. /**
  102814. * Returns the wrap mode of the texture
  102815. * @param mode: the mode value
  102816. */
  102817. GLTFUtils.GetWrapMode = function (mode) {
  102818. switch (mode) {
  102819. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  102820. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  102821. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  102822. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  102823. }
  102824. };
  102825. /**
  102826. * Returns the byte stride giving an accessor
  102827. * @param accessor: the GLTF accessor objet
  102828. */
  102829. GLTFUtils.GetByteStrideFromType = function (accessor) {
  102830. // Needs this function since "byteStride" isn't requiered in glTF format
  102831. var type = accessor.type;
  102832. switch (type) {
  102833. case "VEC2": return 2;
  102834. case "VEC3": return 3;
  102835. case "VEC4": return 4;
  102836. case "MAT2": return 4;
  102837. case "MAT3": return 9;
  102838. case "MAT4": return 16;
  102839. default: return 1;
  102840. }
  102841. };
  102842. /**
  102843. * Returns the texture filter mode giving a mode value
  102844. * @param mode: the filter mode value
  102845. */
  102846. GLTFUtils.GetTextureFilterMode = function (mode) {
  102847. switch (mode) {
  102848. case GLTF1.ETextureFilterType.LINEAR:
  102849. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  102850. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  102851. case GLTF1.ETextureFilterType.NEAREST:
  102852. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  102853. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  102854. }
  102855. };
  102856. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  102857. var byteOffset = bufferView.byteOffset + byteOffset;
  102858. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  102859. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  102860. throw new Error("Buffer access is out of range");
  102861. }
  102862. var buffer = loadedBufferView.buffer;
  102863. byteOffset += loadedBufferView.byteOffset;
  102864. switch (componentType) {
  102865. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  102866. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  102867. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  102868. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  102869. default: return new Float32Array(buffer, byteOffset, byteLength);
  102870. }
  102871. };
  102872. /**
  102873. * Returns a buffer from its accessor
  102874. * @param gltfRuntime: the GLTF runtime
  102875. * @param accessor: the GLTF accessor
  102876. */
  102877. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  102878. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  102879. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  102880. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  102881. };
  102882. /**
  102883. * Decodes a buffer view into a string
  102884. * @param view: the buffer view
  102885. */
  102886. GLTFUtils.DecodeBufferToText = function (view) {
  102887. var result = "";
  102888. var length = view.byteLength;
  102889. for (var i = 0; i < length; ++i) {
  102890. result += String.fromCharCode(view[i]);
  102891. }
  102892. return result;
  102893. };
  102894. /**
  102895. * Returns the default material of gltf. Related to
  102896. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  102897. * @param scene: the Babylon.js scene
  102898. */
  102899. GLTFUtils.GetDefaultMaterial = function (scene) {
  102900. if (!GLTFUtils._DefaultMaterial) {
  102901. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  102902. "precision highp float;",
  102903. "",
  102904. "uniform mat4 worldView;",
  102905. "uniform mat4 projection;",
  102906. "",
  102907. "attribute vec3 position;",
  102908. "",
  102909. "void main(void)",
  102910. "{",
  102911. " gl_Position = projection * worldView * vec4(position, 1.0);",
  102912. "}"
  102913. ].join("\n");
  102914. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  102915. "precision highp float;",
  102916. "",
  102917. "uniform vec4 u_emission;",
  102918. "",
  102919. "void main(void)",
  102920. "{",
  102921. " gl_FragColor = u_emission;",
  102922. "}"
  102923. ].join("\n");
  102924. var shaderPath = {
  102925. vertex: "GLTFDefaultMaterial",
  102926. fragment: "GLTFDefaultMaterial"
  102927. };
  102928. var options = {
  102929. attributes: ["position"],
  102930. uniforms: ["worldView", "projection", "u_emission"],
  102931. samplers: new Array(),
  102932. needAlphaBlending: false
  102933. };
  102934. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  102935. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  102936. }
  102937. return GLTFUtils._DefaultMaterial;
  102938. };
  102939. // The GLTF default material
  102940. GLTFUtils._DefaultMaterial = null;
  102941. return GLTFUtils;
  102942. }());
  102943. GLTF1.GLTFUtils = GLTFUtils;
  102944. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  102945. })(BABYLON || (BABYLON = {}));
  102946. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  102947. var BABYLON;
  102948. (function (BABYLON) {
  102949. var GLTF1;
  102950. (function (GLTF1) {
  102951. var GLTFLoaderExtension = /** @class */ (function () {
  102952. function GLTFLoaderExtension(name) {
  102953. this._name = name;
  102954. }
  102955. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  102956. get: function () {
  102957. return this._name;
  102958. },
  102959. enumerable: true,
  102960. configurable: true
  102961. });
  102962. /**
  102963. * Defines an override for loading the runtime
  102964. * Return true to stop further extensions from loading the runtime
  102965. */
  102966. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  102967. return false;
  102968. };
  102969. /**
  102970. * Defines an onverride for creating gltf runtime
  102971. * Return true to stop further extensions from creating the runtime
  102972. */
  102973. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  102974. return false;
  102975. };
  102976. /**
  102977. * Defines an override for loading buffers
  102978. * Return true to stop further extensions from loading this buffer
  102979. */
  102980. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  102981. return false;
  102982. };
  102983. /**
  102984. * Defines an override for loading texture buffers
  102985. * Return true to stop further extensions from loading this texture data
  102986. */
  102987. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  102988. return false;
  102989. };
  102990. /**
  102991. * Defines an override for creating textures
  102992. * Return true to stop further extensions from loading this texture
  102993. */
  102994. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  102995. return false;
  102996. };
  102997. /**
  102998. * Defines an override for loading shader strings
  102999. * Return true to stop further extensions from loading this shader data
  103000. */
  103001. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  103002. return false;
  103003. };
  103004. /**
  103005. * Defines an override for loading materials
  103006. * Return true to stop further extensions from loading this material
  103007. */
  103008. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  103009. return false;
  103010. };
  103011. // ---------
  103012. // Utilities
  103013. // ---------
  103014. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  103015. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  103016. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  103017. }, function () {
  103018. setTimeout(function () {
  103019. if (!onSuccess) {
  103020. return;
  103021. }
  103022. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  103023. });
  103024. });
  103025. };
  103026. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  103027. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  103028. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  103029. }, function () {
  103030. setTimeout(function () {
  103031. onSuccess();
  103032. });
  103033. });
  103034. };
  103035. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  103036. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  103037. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  103038. }, function () {
  103039. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  103040. });
  103041. };
  103042. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  103043. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  103044. if (buffer) {
  103045. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  103046. }
  103047. }, onError);
  103048. };
  103049. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  103050. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  103051. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  103052. }, function () {
  103053. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  103054. });
  103055. };
  103056. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  103057. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  103058. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  103059. }, function () {
  103060. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  103061. });
  103062. };
  103063. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  103064. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  103065. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  103066. }, function () {
  103067. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  103068. });
  103069. };
  103070. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  103071. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  103072. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  103073. }, function () {
  103074. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  103075. });
  103076. };
  103077. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  103078. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  103079. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  103080. if (func(loaderExtension)) {
  103081. return;
  103082. }
  103083. }
  103084. defaultFunc();
  103085. };
  103086. return GLTFLoaderExtension;
  103087. }());
  103088. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  103089. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  103090. })(BABYLON || (BABYLON = {}));
  103091. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  103092. var BABYLON;
  103093. (function (BABYLON) {
  103094. var GLTF1;
  103095. (function (GLTF1) {
  103096. var BinaryExtensionBufferName = "binary_glTF";
  103097. ;
  103098. ;
  103099. var GLTFBinaryExtension = /** @class */ (function (_super) {
  103100. __extends(GLTFBinaryExtension, _super);
  103101. function GLTFBinaryExtension() {
  103102. return _super.call(this, "KHR_binary_glTF") || this;
  103103. }
  103104. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  103105. var extensionsUsed = data.json.extensionsUsed;
  103106. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  103107. return false;
  103108. }
  103109. this._bin = data.bin;
  103110. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  103111. return true;
  103112. };
  103113. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  103114. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  103115. return false;
  103116. }
  103117. if (id !== BinaryExtensionBufferName) {
  103118. return false;
  103119. }
  103120. onSuccess(this._bin);
  103121. return true;
  103122. };
  103123. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  103124. var texture = gltfRuntime.textures[id];
  103125. var source = gltfRuntime.images[texture.source];
  103126. if (!source.extensions || !(this.name in source.extensions)) {
  103127. return false;
  103128. }
  103129. var sourceExt = source.extensions[this.name];
  103130. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  103131. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  103132. onSuccess(buffer);
  103133. return true;
  103134. };
  103135. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  103136. var shader = gltfRuntime.shaders[id];
  103137. if (!shader.extensions || !(this.name in shader.extensions)) {
  103138. return false;
  103139. }
  103140. var binaryExtensionShader = shader.extensions[this.name];
  103141. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  103142. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  103143. setTimeout(function () {
  103144. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  103145. onSuccess(shaderString);
  103146. });
  103147. return true;
  103148. };
  103149. return GLTFBinaryExtension;
  103150. }(GLTF1.GLTFLoaderExtension));
  103151. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  103152. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  103153. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  103154. })(BABYLON || (BABYLON = {}));
  103155. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  103156. var BABYLON;
  103157. (function (BABYLON) {
  103158. var GLTF1;
  103159. (function (GLTF1) {
  103160. ;
  103161. ;
  103162. ;
  103163. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  103164. __extends(GLTFMaterialsCommonExtension, _super);
  103165. function GLTFMaterialsCommonExtension() {
  103166. return _super.call(this, "KHR_materials_common") || this;
  103167. }
  103168. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  103169. if (!gltfRuntime.extensions)
  103170. return false;
  103171. var extension = gltfRuntime.extensions[this.name];
  103172. if (!extension)
  103173. return false;
  103174. // Create lights
  103175. var lights = extension.lights;
  103176. if (lights) {
  103177. for (var thing in lights) {
  103178. var light = lights[thing];
  103179. switch (light.type) {
  103180. case "ambient":
  103181. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  103182. var ambient = light.ambient;
  103183. if (ambient) {
  103184. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  103185. }
  103186. break;
  103187. case "point":
  103188. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  103189. var point = light.point;
  103190. if (point) {
  103191. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  103192. }
  103193. break;
  103194. case "directional":
  103195. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  103196. var directional = light.directional;
  103197. if (directional) {
  103198. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  103199. }
  103200. break;
  103201. case "spot":
  103202. var spot = light.spot;
  103203. if (spot) {
  103204. 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);
  103205. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  103206. }
  103207. break;
  103208. default:
  103209. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  103210. break;
  103211. }
  103212. }
  103213. }
  103214. return false;
  103215. };
  103216. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  103217. var material = gltfRuntime.materials[id];
  103218. if (!material || !material.extensions)
  103219. return false;
  103220. var extension = material.extensions[this.name];
  103221. if (!extension)
  103222. return false;
  103223. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  103224. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  103225. if (extension.technique === "CONSTANT") {
  103226. standardMaterial.disableLighting = true;
  103227. }
  103228. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  103229. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  103230. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  103231. // Ambient
  103232. if (typeof extension.values.ambient === "string") {
  103233. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  103234. }
  103235. else {
  103236. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  103237. }
  103238. // Diffuse
  103239. if (typeof extension.values.diffuse === "string") {
  103240. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  103241. }
  103242. else {
  103243. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  103244. }
  103245. // Emission
  103246. if (typeof extension.values.emission === "string") {
  103247. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  103248. }
  103249. else {
  103250. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  103251. }
  103252. // Specular
  103253. if (typeof extension.values.specular === "string") {
  103254. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  103255. }
  103256. else {
  103257. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  103258. }
  103259. return true;
  103260. };
  103261. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  103262. // Create buffer from texture url
  103263. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  103264. // Create texture from buffer
  103265. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  103266. }, onError);
  103267. };
  103268. return GLTFMaterialsCommonExtension;
  103269. }(GLTF1.GLTFLoaderExtension));
  103270. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  103271. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  103272. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  103273. })(BABYLON || (BABYLON = {}));
  103274. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  103275. var BABYLON;
  103276. (function (BABYLON) {
  103277. var GLTF2;
  103278. (function (GLTF2) {
  103279. /** @hidden */
  103280. var _ArrayItem = /** @class */ (function () {
  103281. function _ArrayItem() {
  103282. }
  103283. /** @hidden */
  103284. _ArrayItem.Assign = function (values) {
  103285. if (values) {
  103286. for (var index = 0; index < values.length; index++) {
  103287. values[index]._index = index;
  103288. }
  103289. }
  103290. };
  103291. return _ArrayItem;
  103292. }());
  103293. GLTF2._ArrayItem = _ArrayItem;
  103294. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  103295. })(BABYLON || (BABYLON = {}));
  103296. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  103297. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  103298. /**
  103299. * Defines the module used to import/export glTF 2.0 assets
  103300. */
  103301. var BABYLON;
  103302. (function (BABYLON) {
  103303. var GLTF2;
  103304. (function (GLTF2) {
  103305. /**
  103306. * Loader for loading a glTF 2.0 asset
  103307. */
  103308. var GLTFLoader = /** @class */ (function () {
  103309. function GLTFLoader() {
  103310. /** @hidden */
  103311. this._completePromises = new Array();
  103312. this._disposed = false;
  103313. this._state = null;
  103314. this._extensions = {};
  103315. this._defaultSampler = {};
  103316. this._defaultBabylonMaterials = {};
  103317. this._requests = new Array();
  103318. /**
  103319. * Mode that determines the coordinate system to use.
  103320. */
  103321. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  103322. /**
  103323. * Mode that determines what animations will start.
  103324. */
  103325. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  103326. /**
  103327. * Defines if the loader should compile materials.
  103328. */
  103329. this.compileMaterials = false;
  103330. /**
  103331. * Defines if the loader should also compile materials with clip planes.
  103332. */
  103333. this.useClipPlane = false;
  103334. /**
  103335. * Defines if the loader should compile shadow generators.
  103336. */
  103337. this.compileShadowGenerators = false;
  103338. /**
  103339. * Defines if the Alpha blended materials are only applied as coverage.
  103340. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  103341. * If true, no extra effects are applied to transparent pixels.
  103342. */
  103343. this.transparencyAsCoverage = false;
  103344. /**
  103345. * Function called before loading a url referenced by the asset.
  103346. */
  103347. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  103348. /**
  103349. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  103350. */
  103351. this.onMeshLoadedObservable = new BABYLON.Observable();
  103352. /**
  103353. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  103354. */
  103355. this.onTextureLoadedObservable = new BABYLON.Observable();
  103356. /**
  103357. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  103358. */
  103359. this.onMaterialLoadedObservable = new BABYLON.Observable();
  103360. /**
  103361. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  103362. */
  103363. this.onCameraLoadedObservable = new BABYLON.Observable();
  103364. /**
  103365. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  103366. * For assets with LODs, raised when all of the LODs are complete.
  103367. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  103368. */
  103369. this.onCompleteObservable = new BABYLON.Observable();
  103370. /**
  103371. * Observable raised after the loader is disposed.
  103372. */
  103373. this.onDisposeObservable = new BABYLON.Observable();
  103374. /**
  103375. * Observable raised after a loader extension is created.
  103376. * Set additional options for a loader extension in this event.
  103377. */
  103378. this.onExtensionLoadedObservable = new BABYLON.Observable();
  103379. }
  103380. /** @hidden */
  103381. GLTFLoader._Register = function (name, factory) {
  103382. if (GLTFLoader._ExtensionFactories[name]) {
  103383. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  103384. return;
  103385. }
  103386. GLTFLoader._ExtensionFactories[name] = factory;
  103387. // Keep the order of registration so that extensions registered first are called first.
  103388. GLTFLoader._ExtensionNames.push(name);
  103389. };
  103390. Object.defineProperty(GLTFLoader.prototype, "state", {
  103391. /**
  103392. * Loader state or null if the loader is not active.
  103393. */
  103394. get: function () {
  103395. return this._state;
  103396. },
  103397. enumerable: true,
  103398. configurable: true
  103399. });
  103400. /**
  103401. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  103402. */
  103403. GLTFLoader.prototype.dispose = function () {
  103404. if (this._disposed) {
  103405. return;
  103406. }
  103407. this._disposed = true;
  103408. this.onDisposeObservable.notifyObservers(this);
  103409. this.onDisposeObservable.clear();
  103410. this._clear();
  103411. };
  103412. /**
  103413. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  103414. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  103415. * @param scene the scene the meshes should be added to
  103416. * @param data the glTF data to load
  103417. * @param rootUrl root url to load from
  103418. * @param onProgress event that fires when loading progress has occured
  103419. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  103420. */
  103421. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  103422. var _this = this;
  103423. return Promise.resolve().then(function () {
  103424. var nodes = null;
  103425. if (meshesNames) {
  103426. var nodeMap_1 = {};
  103427. if (_this._gltf.nodes) {
  103428. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  103429. var node = _a[_i];
  103430. if (node.name) {
  103431. nodeMap_1[node.name] = node;
  103432. }
  103433. }
  103434. }
  103435. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  103436. nodes = names.map(function (name) {
  103437. var node = nodeMap_1[name];
  103438. if (!node) {
  103439. throw new Error("Failed to find node '" + name + "'");
  103440. }
  103441. return node;
  103442. });
  103443. }
  103444. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  103445. return {
  103446. meshes: _this._getMeshes(),
  103447. particleSystems: [],
  103448. skeletons: _this._getSkeletons(),
  103449. animationGroups: _this._getAnimationGroups()
  103450. };
  103451. });
  103452. });
  103453. };
  103454. /**
  103455. * Imports all objects from the loaded glTF data and adds them to the scene
  103456. * @param scene the scene the objects should be added to
  103457. * @param data the glTF data to load
  103458. * @param rootUrl root url to load from
  103459. * @param onProgress event that fires when loading progress has occured
  103460. * @returns a promise which completes when objects have been loaded to the scene
  103461. */
  103462. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  103463. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  103464. };
  103465. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  103466. var _this = this;
  103467. return Promise.resolve().then(function () {
  103468. _this._babylonScene = scene;
  103469. _this._rootUrl = rootUrl;
  103470. _this._progressCallback = onProgress;
  103471. _this._state = BABYLON.GLTFLoaderState.LOADING;
  103472. _this._loadData(data);
  103473. _this._loadExtensions();
  103474. _this._checkExtensions();
  103475. var promises = new Array();
  103476. if (nodes) {
  103477. promises.push(_this._loadNodesAsync(nodes));
  103478. }
  103479. else {
  103480. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  103481. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  103482. }
  103483. if (_this.compileMaterials) {
  103484. promises.push(_this._compileMaterialsAsync());
  103485. }
  103486. if (_this.compileShadowGenerators) {
  103487. promises.push(_this._compileShadowGeneratorsAsync());
  103488. }
  103489. var resultPromise = Promise.all(promises).then(function () {
  103490. _this._state = BABYLON.GLTFLoaderState.READY;
  103491. _this._startAnimations();
  103492. });
  103493. resultPromise.then(function () {
  103494. _this._rootBabylonMesh.setEnabled(true);
  103495. BABYLON.Tools.SetImmediate(function () {
  103496. if (!_this._disposed) {
  103497. Promise.all(_this._completePromises).then(function () {
  103498. _this._state = BABYLON.GLTFLoaderState.COMPLETE;
  103499. _this.onCompleteObservable.notifyObservers(_this);
  103500. _this.onCompleteObservable.clear();
  103501. _this._clear();
  103502. }).catch(function (error) {
  103503. BABYLON.Tools.Error("glTF Loader: " + error.message);
  103504. _this._clear();
  103505. });
  103506. }
  103507. });
  103508. });
  103509. return resultPromise;
  103510. }).catch(function (error) {
  103511. if (!_this._disposed) {
  103512. BABYLON.Tools.Error("glTF Loader: " + error.message);
  103513. _this._clear();
  103514. throw error;
  103515. }
  103516. });
  103517. };
  103518. GLTFLoader.prototype._loadData = function (data) {
  103519. this._gltf = data.json;
  103520. this._setupData();
  103521. if (data.bin) {
  103522. var buffers = this._gltf.buffers;
  103523. if (buffers && buffers[0] && !buffers[0].uri) {
  103524. var binaryBuffer = buffers[0];
  103525. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  103526. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  103527. }
  103528. binaryBuffer._data = Promise.resolve(data.bin);
  103529. }
  103530. else {
  103531. BABYLON.Tools.Warn("Unexpected BIN chunk");
  103532. }
  103533. }
  103534. };
  103535. GLTFLoader.prototype._setupData = function () {
  103536. GLTF2._ArrayItem.Assign(this._gltf.accessors);
  103537. GLTF2._ArrayItem.Assign(this._gltf.animations);
  103538. GLTF2._ArrayItem.Assign(this._gltf.buffers);
  103539. GLTF2._ArrayItem.Assign(this._gltf.bufferViews);
  103540. GLTF2._ArrayItem.Assign(this._gltf.cameras);
  103541. GLTF2._ArrayItem.Assign(this._gltf.images);
  103542. GLTF2._ArrayItem.Assign(this._gltf.materials);
  103543. GLTF2._ArrayItem.Assign(this._gltf.meshes);
  103544. GLTF2._ArrayItem.Assign(this._gltf.nodes);
  103545. GLTF2._ArrayItem.Assign(this._gltf.samplers);
  103546. GLTF2._ArrayItem.Assign(this._gltf.scenes);
  103547. GLTF2._ArrayItem.Assign(this._gltf.skins);
  103548. GLTF2._ArrayItem.Assign(this._gltf.textures);
  103549. if (this._gltf.nodes) {
  103550. var nodeParents = {};
  103551. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  103552. var node = _a[_i];
  103553. if (node.children) {
  103554. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  103555. var index = _c[_b];
  103556. nodeParents[index] = node._index;
  103557. }
  103558. }
  103559. }
  103560. var rootNode = this._createRootNode();
  103561. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  103562. var node = _e[_d];
  103563. var parentIndex = nodeParents[node._index];
  103564. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  103565. }
  103566. }
  103567. };
  103568. GLTFLoader.prototype._loadExtensions = function () {
  103569. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  103570. var name_1 = _a[_i];
  103571. var extension = GLTFLoader._ExtensionFactories[name_1](this);
  103572. this._extensions[name_1] = extension;
  103573. this.onExtensionLoadedObservable.notifyObservers(extension);
  103574. }
  103575. this.onExtensionLoadedObservable.clear();
  103576. };
  103577. GLTFLoader.prototype._checkExtensions = function () {
  103578. if (this._gltf.extensionsRequired) {
  103579. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  103580. var name_2 = _a[_i];
  103581. var extension = this._extensions[name_2];
  103582. if (!extension || !extension.enabled) {
  103583. throw new Error("Require extension " + name_2 + " is not available");
  103584. }
  103585. }
  103586. }
  103587. };
  103588. GLTFLoader.prototype._createRootNode = function () {
  103589. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  103590. this._rootBabylonMesh.setEnabled(false);
  103591. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  103592. switch (this.coordinateSystemMode) {
  103593. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  103594. if (!this._babylonScene.useRightHandedSystem) {
  103595. rootNode.rotation = [0, 1, 0, 0];
  103596. rootNode.scale = [1, 1, -1];
  103597. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  103598. }
  103599. break;
  103600. }
  103601. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  103602. this._babylonScene.useRightHandedSystem = true;
  103603. break;
  103604. }
  103605. default: {
  103606. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  103607. }
  103608. }
  103609. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  103610. return rootNode;
  103611. };
  103612. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  103613. var promises = new Array();
  103614. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  103615. var node = nodes_1[_i];
  103616. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  103617. }
  103618. promises.push(this._loadAnimationsAsync());
  103619. return Promise.all(promises).then(function () { });
  103620. };
  103621. /** @hidden */
  103622. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  103623. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  103624. if (promise) {
  103625. return promise;
  103626. }
  103627. var promises = new Array();
  103628. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  103629. var index = _a[_i];
  103630. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  103631. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  103632. }
  103633. promises.push(this._loadAnimationsAsync());
  103634. return Promise.all(promises).then(function () { });
  103635. };
  103636. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  103637. if (node._primitiveBabylonMeshes) {
  103638. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  103639. var babylonMesh = _a[_i];
  103640. callback(babylonMesh);
  103641. }
  103642. }
  103643. else {
  103644. callback(node._babylonMesh);
  103645. }
  103646. };
  103647. GLTFLoader.prototype._getMeshes = function () {
  103648. var meshes = new Array();
  103649. // Root mesh is always first.
  103650. meshes.push(this._rootBabylonMesh);
  103651. var nodes = this._gltf.nodes;
  103652. if (nodes) {
  103653. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  103654. var node = nodes_2[_i];
  103655. if (node._babylonMesh) {
  103656. meshes.push(node._babylonMesh);
  103657. }
  103658. if (node._primitiveBabylonMeshes) {
  103659. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  103660. var babylonMesh = _b[_a];
  103661. meshes.push(babylonMesh);
  103662. }
  103663. }
  103664. }
  103665. }
  103666. return meshes;
  103667. };
  103668. GLTFLoader.prototype._getSkeletons = function () {
  103669. var skeletons = new Array();
  103670. var skins = this._gltf.skins;
  103671. if (skins) {
  103672. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  103673. var skin = skins_1[_i];
  103674. if (skin._babylonSkeleton) {
  103675. skeletons.push(skin._babylonSkeleton);
  103676. }
  103677. }
  103678. }
  103679. return skeletons;
  103680. };
  103681. GLTFLoader.prototype._getAnimationGroups = function () {
  103682. var animationGroups = new Array();
  103683. var animations = this._gltf.animations;
  103684. if (animations) {
  103685. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  103686. var animation = animations_1[_i];
  103687. if (animation._babylonAnimationGroup) {
  103688. animationGroups.push(animation._babylonAnimationGroup);
  103689. }
  103690. }
  103691. }
  103692. return animationGroups;
  103693. };
  103694. GLTFLoader.prototype._startAnimations = function () {
  103695. switch (this.animationStartMode) {
  103696. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  103697. // do nothing
  103698. break;
  103699. }
  103700. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  103701. var babylonAnimationGroups = this._getAnimationGroups();
  103702. if (babylonAnimationGroups.length !== 0) {
  103703. babylonAnimationGroups[0].start(true);
  103704. }
  103705. break;
  103706. }
  103707. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  103708. var babylonAnimationGroups = this._getAnimationGroups();
  103709. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  103710. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  103711. babylonAnimationGroup.start(true);
  103712. }
  103713. break;
  103714. }
  103715. default: {
  103716. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  103717. return;
  103718. }
  103719. }
  103720. };
  103721. /** @hidden */
  103722. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  103723. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  103724. if (promise) {
  103725. return promise;
  103726. }
  103727. if (node._babylonMesh) {
  103728. throw new Error(context + ": Invalid recursive node hierarchy");
  103729. }
  103730. var promises = new Array();
  103731. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  103732. node._babylonMesh = babylonMesh;
  103733. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  103734. node._babylonAnimationTargets.push(babylonMesh);
  103735. GLTFLoader._LoadTransform(node, babylonMesh);
  103736. if (node.mesh != undefined) {
  103737. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  103738. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  103739. }
  103740. if (node.camera != undefined) {
  103741. var camera = GLTFLoader._GetProperty(context + "/camera", this._gltf.cameras, node.camera);
  103742. this._loadCamera("#/cameras/" + camera._index, camera, babylonMesh);
  103743. }
  103744. if (node.children) {
  103745. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  103746. var index = _a[_i];
  103747. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  103748. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  103749. }
  103750. }
  103751. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  103752. return Promise.all(promises).then(function () { });
  103753. };
  103754. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  103755. var _this = this;
  103756. var promises = new Array();
  103757. var primitives = mesh.primitives;
  103758. if (!primitives || primitives.length === 0) {
  103759. throw new Error(context + ": Primitives are missing");
  103760. }
  103761. GLTF2._ArrayItem.Assign(primitives);
  103762. if (primitives.length === 1) {
  103763. var primitive = primitives[0];
  103764. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  103765. }
  103766. else {
  103767. node._primitiveBabylonMeshes = [];
  103768. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  103769. var primitive = primitives_1[_i];
  103770. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  103771. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  103772. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  103773. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  103774. }
  103775. }
  103776. if (node.skin != undefined) {
  103777. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  103778. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  103779. }
  103780. return Promise.all(promises).then(function () {
  103781. _this._forEachPrimitive(node, function (babylonMesh) {
  103782. babylonMesh._refreshBoundingInfo(true);
  103783. });
  103784. });
  103785. };
  103786. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  103787. var _this = this;
  103788. var promises = new Array();
  103789. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  103790. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  103791. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  103792. babylonGeometry.applyToMesh(babylonMesh);
  103793. });
  103794. }));
  103795. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  103796. if (primitive.material == undefined) {
  103797. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  103798. }
  103799. else {
  103800. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  103801. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  103802. babylonMesh.material = babylonMaterial;
  103803. }));
  103804. }
  103805. return Promise.all(promises).then(function () { });
  103806. };
  103807. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  103808. var _this = this;
  103809. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  103810. if (promise) {
  103811. return promise;
  103812. }
  103813. var attributes = primitive.attributes;
  103814. if (!attributes) {
  103815. throw new Error(context + ": Attributes are missing");
  103816. }
  103817. var promises = new Array();
  103818. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene);
  103819. if (primitive.indices == undefined) {
  103820. babylonMesh.isUnIndexed = true;
  103821. }
  103822. else {
  103823. var accessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  103824. promises.push(this._loadIndicesAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  103825. babylonGeometry.setIndices(data);
  103826. }));
  103827. }
  103828. var loadAttribute = function (attribute, kind, callback) {
  103829. if (attributes[attribute] == undefined) {
  103830. return;
  103831. }
  103832. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  103833. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  103834. babylonMesh._delayInfo.push(kind);
  103835. }
  103836. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  103837. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor._index, accessor, kind).then(function (babylonVertexBuffer) {
  103838. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  103839. }));
  103840. if (callback) {
  103841. callback(accessor);
  103842. }
  103843. };
  103844. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  103845. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  103846. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  103847. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  103848. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  103849. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  103850. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  103851. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  103852. if (accessor.type === "VEC4" /* VEC4 */) {
  103853. babylonMesh.hasVertexAlpha = true;
  103854. }
  103855. });
  103856. return Promise.all(promises).then(function () {
  103857. return babylonGeometry;
  103858. });
  103859. };
  103860. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  103861. if (!primitive.targets) {
  103862. return;
  103863. }
  103864. if (node._numMorphTargets == undefined) {
  103865. node._numMorphTargets = primitive.targets.length;
  103866. }
  103867. else if (primitive.targets.length !== node._numMorphTargets) {
  103868. throw new Error(context + ": Primitives do not have the same number of targets");
  103869. }
  103870. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  103871. for (var index = 0; index < primitive.targets.length; index++) {
  103872. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  103873. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  103874. // TODO: tell the target whether it has positions, normals, tangents
  103875. }
  103876. };
  103877. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  103878. if (!primitive.targets) {
  103879. return Promise.resolve();
  103880. }
  103881. var promises = new Array();
  103882. var morphTargetManager = babylonMesh.morphTargetManager;
  103883. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  103884. var babylonMorphTarget = morphTargetManager.getTarget(index);
  103885. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  103886. }
  103887. return Promise.all(promises).then(function () { });
  103888. };
  103889. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  103890. var _this = this;
  103891. var promises = new Array();
  103892. var loadAttribute = function (attribute, kind, setData) {
  103893. if (attributes[attribute] == undefined) {
  103894. return;
  103895. }
  103896. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  103897. if (!babylonVertexBuffer) {
  103898. return;
  103899. }
  103900. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  103901. promises.push(_this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  103902. setData(babylonVertexBuffer, data);
  103903. }));
  103904. };
  103905. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  103906. babylonVertexBuffer.forEach(data.length, function (value, index) {
  103907. data[index] += value;
  103908. });
  103909. babylonMorphTarget.setPositions(data);
  103910. });
  103911. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  103912. babylonVertexBuffer.forEach(data.length, function (value, index) {
  103913. data[index] += value;
  103914. });
  103915. babylonMorphTarget.setNormals(data);
  103916. });
  103917. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  103918. var dataIndex = 0;
  103919. babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) {
  103920. // Tangent data for morph targets is stored as xyz delta.
  103921. // The vertexData.tangent is stored as xyzw.
  103922. // So we need to skip every fourth vertexData.tangent.
  103923. if (((index + 1) % 4) !== 0) {
  103924. data[dataIndex++] += value;
  103925. }
  103926. });
  103927. babylonMorphTarget.setTangents(data);
  103928. });
  103929. return Promise.all(promises).then(function () { });
  103930. };
  103931. GLTFLoader._LoadTransform = function (node, babylonNode) {
  103932. var position = BABYLON.Vector3.Zero();
  103933. var rotation = BABYLON.Quaternion.Identity();
  103934. var scaling = BABYLON.Vector3.One();
  103935. if (node.matrix) {
  103936. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  103937. matrix.decompose(scaling, rotation, position);
  103938. }
  103939. else {
  103940. if (node.translation)
  103941. position = BABYLON.Vector3.FromArray(node.translation);
  103942. if (node.rotation)
  103943. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  103944. if (node.scale)
  103945. scaling = BABYLON.Vector3.FromArray(node.scale);
  103946. }
  103947. babylonNode.position = position;
  103948. babylonNode.rotationQuaternion = rotation;
  103949. babylonNode.scaling = scaling;
  103950. };
  103951. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  103952. var _this = this;
  103953. var assignSkeleton = function (skeleton) {
  103954. _this._forEachPrimitive(node, function (babylonMesh) {
  103955. babylonMesh.skeleton = skeleton;
  103956. });
  103957. // Ignore the TRS of skinned nodes.
  103958. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  103959. node._babylonMesh.parent = _this._rootBabylonMesh;
  103960. node._babylonMesh.position = BABYLON.Vector3.Zero();
  103961. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  103962. node._babylonMesh.scaling = BABYLON.Vector3.One();
  103963. };
  103964. if (skin._loaded) {
  103965. return skin._loaded.then(function () {
  103966. assignSkeleton(skin._babylonSkeleton);
  103967. });
  103968. }
  103969. var skeletonId = "skeleton" + skin._index;
  103970. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  103971. skin._babylonSkeleton = babylonSkeleton;
  103972. this._loadBones(context, skin);
  103973. assignSkeleton(babylonSkeleton);
  103974. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  103975. _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  103976. }));
  103977. };
  103978. GLTFLoader.prototype._loadBones = function (context, skin) {
  103979. var babylonBones = {};
  103980. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  103981. var index = _a[_i];
  103982. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  103983. this._loadBone(node, skin, babylonBones);
  103984. }
  103985. };
  103986. GLTFLoader.prototype._loadBone = function (node, skin, babylonBones) {
  103987. var babylonBone = babylonBones[node._index];
  103988. if (babylonBone) {
  103989. return babylonBone;
  103990. }
  103991. var babylonParentBone = null;
  103992. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  103993. babylonParentBone = this._loadBone(node._parent, skin, babylonBones);
  103994. }
  103995. var boneIndex = skin.joints.indexOf(node._index);
  103996. babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  103997. babylonBones[node._index] = babylonBone;
  103998. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  103999. node._babylonAnimationTargets.push(babylonBone);
  104000. return babylonBone;
  104001. };
  104002. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  104003. if (skin.inverseBindMatrices == undefined) {
  104004. return Promise.resolve(null);
  104005. }
  104006. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  104007. return this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor);
  104008. };
  104009. GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
  104010. for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
  104011. var babylonBone = _a[_i];
  104012. var baseMatrix = BABYLON.Matrix.Identity();
  104013. var boneIndex = babylonBone._index;
  104014. if (inverseBindMatricesData && boneIndex !== -1) {
  104015. BABYLON.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  104016. baseMatrix.invertToRef(baseMatrix);
  104017. }
  104018. var babylonParentBone = babylonBone.getParent();
  104019. if (babylonParentBone) {
  104020. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  104021. }
  104022. babylonBone.updateMatrix(baseMatrix, false, false);
  104023. babylonBone._updateDifferenceMatrix(undefined, false);
  104024. }
  104025. };
  104026. GLTFLoader.prototype._getNodeMatrix = function (node) {
  104027. return node.matrix ?
  104028. BABYLON.Matrix.FromArray(node.matrix) :
  104029. 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());
  104030. };
  104031. GLTFLoader.prototype._loadCamera = function (context, camera, babylonMesh) {
  104032. var babylonCamera = new BABYLON.FreeCamera(camera.name || "camera" + camera._index, BABYLON.Vector3.Zero(), this._babylonScene, false);
  104033. babylonCamera.parent = babylonMesh;
  104034. babylonCamera.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  104035. switch (camera.type) {
  104036. case "perspective" /* PERSPECTIVE */: {
  104037. var perspective = camera.perspective;
  104038. if (!perspective) {
  104039. throw new Error(context + ": Camera perspective properties are missing");
  104040. }
  104041. babylonCamera.fov = perspective.yfov;
  104042. babylonCamera.minZ = perspective.znear;
  104043. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  104044. break;
  104045. }
  104046. case "orthographic" /* ORTHOGRAPHIC */: {
  104047. if (!camera.orthographic) {
  104048. throw new Error(context + ": Camera orthographic properties are missing");
  104049. }
  104050. babylonCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  104051. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  104052. babylonCamera.orthoRight = camera.orthographic.xmag;
  104053. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  104054. babylonCamera.orthoTop = camera.orthographic.ymag;
  104055. babylonCamera.minZ = camera.orthographic.znear;
  104056. babylonCamera.maxZ = camera.orthographic.zfar;
  104057. break;
  104058. }
  104059. default: {
  104060. throw new Error(context + ": Invalid camera type (" + camera.type + ")");
  104061. }
  104062. }
  104063. this.onCameraLoadedObservable.notifyObservers(babylonCamera);
  104064. };
  104065. GLTFLoader.prototype._loadAnimationsAsync = function () {
  104066. var animations = this._gltf.animations;
  104067. if (!animations) {
  104068. return Promise.resolve();
  104069. }
  104070. var promises = new Array();
  104071. for (var index = 0; index < animations.length; index++) {
  104072. var animation = animations[index];
  104073. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  104074. }
  104075. return Promise.all(promises).then(function () { });
  104076. };
  104077. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  104078. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  104079. animation._babylonAnimationGroup = babylonAnimationGroup;
  104080. var promises = new Array();
  104081. GLTF2._ArrayItem.Assign(animation.channels);
  104082. GLTF2._ArrayItem.Assign(animation.samplers);
  104083. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  104084. var channel = _a[_i];
  104085. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  104086. }
  104087. return Promise.all(promises).then(function () {
  104088. babylonAnimationGroup.normalize();
  104089. });
  104090. };
  104091. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  104092. var _this = this;
  104093. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  104094. // Ignore animations that have no animation targets.
  104095. if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) ||
  104096. (channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonAnimationTargets)) {
  104097. return Promise.resolve();
  104098. }
  104099. // Ignore animations targeting TRS of skinned nodes.
  104100. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  104101. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  104102. return Promise.resolve();
  104103. }
  104104. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  104105. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  104106. var targetPath;
  104107. var animationType;
  104108. switch (channel.target.path) {
  104109. case "translation" /* TRANSLATION */: {
  104110. targetPath = "position";
  104111. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  104112. break;
  104113. }
  104114. case "rotation" /* ROTATION */: {
  104115. targetPath = "rotationQuaternion";
  104116. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  104117. break;
  104118. }
  104119. case "scale" /* SCALE */: {
  104120. targetPath = "scaling";
  104121. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  104122. break;
  104123. }
  104124. case "weights" /* WEIGHTS */: {
  104125. targetPath = "influence";
  104126. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  104127. break;
  104128. }
  104129. default: {
  104130. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  104131. }
  104132. }
  104133. var outputBufferOffset = 0;
  104134. var getNextOutputValue;
  104135. switch (targetPath) {
  104136. case "position": {
  104137. getNextOutputValue = function () {
  104138. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  104139. outputBufferOffset += 3;
  104140. return value;
  104141. };
  104142. break;
  104143. }
  104144. case "rotationQuaternion": {
  104145. getNextOutputValue = function () {
  104146. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  104147. outputBufferOffset += 4;
  104148. return value;
  104149. };
  104150. break;
  104151. }
  104152. case "scaling": {
  104153. getNextOutputValue = function () {
  104154. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  104155. outputBufferOffset += 3;
  104156. return value;
  104157. };
  104158. break;
  104159. }
  104160. case "influence": {
  104161. getNextOutputValue = function () {
  104162. var value = new Array(targetNode._numMorphTargets);
  104163. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  104164. value[i] = data.output[outputBufferOffset++];
  104165. }
  104166. return value;
  104167. };
  104168. break;
  104169. }
  104170. }
  104171. var getNextKey;
  104172. switch (data.interpolation) {
  104173. case "STEP" /* STEP */: {
  104174. getNextKey = function (frameIndex) { return ({
  104175. frame: data.input[frameIndex],
  104176. value: getNextOutputValue(),
  104177. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  104178. }); };
  104179. break;
  104180. }
  104181. case "LINEAR" /* LINEAR */: {
  104182. getNextKey = function (frameIndex) { return ({
  104183. frame: data.input[frameIndex],
  104184. value: getNextOutputValue()
  104185. }); };
  104186. break;
  104187. }
  104188. case "CUBICSPLINE" /* CUBICSPLINE */: {
  104189. getNextKey = function (frameIndex) { return ({
  104190. frame: data.input[frameIndex],
  104191. inTangent: getNextOutputValue(),
  104192. value: getNextOutputValue(),
  104193. outTangent: getNextOutputValue()
  104194. }); };
  104195. break;
  104196. }
  104197. }
  104198. var keys = new Array(data.input.length);
  104199. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  104200. keys[frameIndex] = getNextKey(frameIndex);
  104201. }
  104202. if (targetPath === "influence") {
  104203. var _loop_1 = function (targetIndex) {
  104204. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  104205. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  104206. babylonAnimation.setKeys(keys.map(function (key) { return ({
  104207. frame: key.frame,
  104208. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  104209. value: key.value[targetIndex],
  104210. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  104211. }); }));
  104212. var morphTargets = new Array();
  104213. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  104214. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  104215. morphTarget.animations.push(babylonAnimation);
  104216. morphTargets.push(morphTarget);
  104217. });
  104218. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTargets);
  104219. };
  104220. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  104221. _loop_1(targetIndex);
  104222. }
  104223. }
  104224. else {
  104225. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  104226. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  104227. babylonAnimation.setKeys(keys);
  104228. if (targetNode._babylonAnimationTargets) {
  104229. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  104230. var babylonAnimationTarget = _a[_i];
  104231. babylonAnimationTarget.animations.push(babylonAnimation);
  104232. }
  104233. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonAnimationTargets);
  104234. }
  104235. }
  104236. });
  104237. };
  104238. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  104239. if (sampler._data) {
  104240. return sampler._data;
  104241. }
  104242. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  104243. switch (interpolation) {
  104244. case "STEP" /* STEP */:
  104245. case "LINEAR" /* LINEAR */:
  104246. case "CUBICSPLINE" /* CUBICSPLINE */: {
  104247. break;
  104248. }
  104249. default: {
  104250. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  104251. }
  104252. }
  104253. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  104254. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  104255. sampler._data = Promise.all([
  104256. this._loadFloatAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor),
  104257. this._loadFloatAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor)
  104258. ]).then(function (_a) {
  104259. var inputData = _a[0], outputData = _a[1];
  104260. return {
  104261. input: inputData,
  104262. interpolation: interpolation,
  104263. output: outputData,
  104264. };
  104265. });
  104266. return sampler._data;
  104267. };
  104268. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  104269. if (buffer._data) {
  104270. return buffer._data;
  104271. }
  104272. if (!buffer.uri) {
  104273. throw new Error(context + ": Uri is missing");
  104274. }
  104275. buffer._data = this._loadUriAsync(context, buffer.uri);
  104276. return buffer._data;
  104277. };
  104278. /** @hidden */
  104279. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  104280. if (bufferView._data) {
  104281. return bufferView._data;
  104282. }
  104283. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  104284. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (data) {
  104285. try {
  104286. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  104287. }
  104288. catch (e) {
  104289. throw new Error(context + ": " + e.message);
  104290. }
  104291. });
  104292. return bufferView._data;
  104293. };
  104294. GLTFLoader.prototype._loadIndicesAccessorAsync = function (context, accessor) {
  104295. if (accessor.type !== "SCALAR" /* SCALAR */) {
  104296. throw new Error(context + ": Invalid type " + accessor.type);
  104297. }
  104298. if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ &&
  104299. accessor.componentType !== 5123 /* UNSIGNED_SHORT */ &&
  104300. accessor.componentType !== 5125 /* UNSIGNED_INT */) {
  104301. throw new Error(context + ": Invalid component type " + accessor.componentType);
  104302. }
  104303. if (accessor._data) {
  104304. return accessor._data;
  104305. }
  104306. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  104307. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  104308. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  104309. });
  104310. return accessor._data;
  104311. };
  104312. GLTFLoader.prototype._loadFloatAccessorAsync = function (context, accessor) {
  104313. // TODO: support normalized and stride
  104314. var _this = this;
  104315. if (accessor.componentType !== 5126 /* FLOAT */) {
  104316. throw new Error("Invalid component type " + accessor.componentType);
  104317. }
  104318. if (accessor._data) {
  104319. return accessor._data;
  104320. }
  104321. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  104322. var length = numComponents * accessor.count;
  104323. if (accessor.bufferView == undefined) {
  104324. accessor._data = Promise.resolve(new Float32Array(length));
  104325. }
  104326. else {
  104327. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  104328. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  104329. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  104330. });
  104331. }
  104332. if (accessor.sparse) {
  104333. var sparse_1 = accessor.sparse;
  104334. accessor._data = accessor._data.then(function (data) {
  104335. var indicesBufferView = GLTFLoader._GetProperty(context + "/sparse/indices/bufferView", _this._gltf.bufferViews, sparse_1.indices.bufferView);
  104336. var valuesBufferView = GLTFLoader._GetProperty(context + "/sparse/values/bufferView", _this._gltf.bufferViews, sparse_1.values.bufferView);
  104337. return Promise.all([
  104338. _this._loadBufferViewAsync("#/bufferViews/" + indicesBufferView._index, indicesBufferView),
  104339. _this._loadBufferViewAsync("#/bufferViews/" + valuesBufferView._index, valuesBufferView)
  104340. ]).then(function (_a) {
  104341. var indicesData = _a[0], valuesData = _a[1];
  104342. var indices = GLTFLoader._GetTypedArray(context + "/sparse/indices", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count);
  104343. var values = GLTFLoader._GetTypedArray(context + "/sparse/values", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count);
  104344. var valuesIndex = 0;
  104345. for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  104346. var dataIndex = indices[indicesIndex] * numComponents;
  104347. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  104348. data[dataIndex++] = values[valuesIndex++];
  104349. }
  104350. }
  104351. return data;
  104352. });
  104353. });
  104354. }
  104355. return accessor._data;
  104356. };
  104357. /** @hidden */
  104358. GLTFLoader.prototype._loadVertexBufferViewAsync = function (context, bufferView, kind) {
  104359. var _this = this;
  104360. if (bufferView._babylonBuffer) {
  104361. return bufferView._babylonBuffer;
  104362. }
  104363. bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(function (data) {
  104364. return new BABYLON.Buffer(_this._babylonScene.getEngine(), data, false);
  104365. });
  104366. return bufferView._babylonBuffer;
  104367. };
  104368. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  104369. var _this = this;
  104370. if (accessor._babylonVertexBuffer) {
  104371. return accessor._babylonVertexBuffer;
  104372. }
  104373. if (accessor.sparse) {
  104374. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync(context, accessor).then(function (data) {
  104375. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), data, kind, false);
  104376. });
  104377. }
  104378. else {
  104379. var bufferView_1 = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  104380. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync("#/bufferViews/" + bufferView_1._index, bufferView_1, kind).then(function (buffer) {
  104381. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  104382. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), buffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  104383. });
  104384. }
  104385. return accessor._babylonVertexBuffer;
  104386. };
  104387. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  104388. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  104389. if (!babylonMaterial) {
  104390. babylonMaterial = this._createMaterial("__gltf_default", drawMode);
  104391. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  104392. babylonMaterial.metallic = 1;
  104393. babylonMaterial.roughness = 1;
  104394. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  104395. }
  104396. return babylonMaterial;
  104397. };
  104398. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  104399. var promises = new Array();
  104400. // Ensure metallic workflow
  104401. babylonMaterial.metallic = 1;
  104402. babylonMaterial.roughness = 1;
  104403. var properties = material.pbrMetallicRoughness;
  104404. if (properties) {
  104405. if (properties.baseColorFactor) {
  104406. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  104407. babylonMaterial.alpha = properties.baseColorFactor[3];
  104408. }
  104409. else {
  104410. babylonMaterial.albedoColor = BABYLON.Color3.White();
  104411. }
  104412. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  104413. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  104414. if (properties.baseColorTexture) {
  104415. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  104416. babylonMaterial.albedoTexture = texture;
  104417. }));
  104418. }
  104419. if (properties.metallicRoughnessTexture) {
  104420. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  104421. babylonMaterial.metallicTexture = texture;
  104422. }));
  104423. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  104424. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  104425. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  104426. }
  104427. }
  104428. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  104429. return Promise.all(promises).then(function () { });
  104430. };
  104431. /** @hidden */
  104432. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  104433. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, babylonDrawMode, assign);
  104434. if (promise) {
  104435. return promise;
  104436. }
  104437. material._babylonData = material._babylonData || {};
  104438. var babylonData = material._babylonData[babylonDrawMode];
  104439. if (!babylonData) {
  104440. var promises = new Array();
  104441. var name_3 = material.name || "materialSG_" + material._index;
  104442. var babylonMaterial = this._createMaterial(name_3, babylonDrawMode);
  104443. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  104444. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  104445. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  104446. babylonData = {
  104447. material: babylonMaterial,
  104448. meshes: [],
  104449. loaded: Promise.all(promises).then(function () { })
  104450. };
  104451. material._babylonData[babylonDrawMode] = babylonData;
  104452. }
  104453. babylonData.meshes.push(babylonMesh);
  104454. assign(babylonData.material);
  104455. return babylonData.loaded;
  104456. };
  104457. /** @hidden */
  104458. GLTFLoader.prototype._createMaterial = function (name, drawMode) {
  104459. var babylonMaterial = new BABYLON.PBRMaterial(name, this._babylonScene);
  104460. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  104461. babylonMaterial.fillMode = drawMode;
  104462. babylonMaterial.enableSpecularAntiAliasing = true;
  104463. babylonMaterial.useRadianceOverAlpha = !this.transparencyAsCoverage;
  104464. babylonMaterial.useSpecularOverAlpha = !this.transparencyAsCoverage;
  104465. return babylonMaterial;
  104466. };
  104467. /** @hidden */
  104468. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  104469. var promises = new Array();
  104470. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  104471. if (material.doubleSided) {
  104472. babylonMaterial.backFaceCulling = false;
  104473. babylonMaterial.twoSidedLighting = true;
  104474. }
  104475. if (material.normalTexture) {
  104476. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  104477. babylonMaterial.bumpTexture = texture;
  104478. }));
  104479. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  104480. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  104481. if (material.normalTexture.scale != undefined) {
  104482. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  104483. }
  104484. }
  104485. if (material.occlusionTexture) {
  104486. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  104487. babylonMaterial.ambientTexture = texture;
  104488. }));
  104489. babylonMaterial.useAmbientInGrayScale = true;
  104490. if (material.occlusionTexture.strength != undefined) {
  104491. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  104492. }
  104493. }
  104494. if (material.emissiveTexture) {
  104495. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  104496. babylonMaterial.emissiveTexture = texture;
  104497. }));
  104498. }
  104499. return Promise.all(promises).then(function () { });
  104500. };
  104501. /** @hidden */
  104502. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  104503. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  104504. switch (alphaMode) {
  104505. case "OPAQUE" /* OPAQUE */: {
  104506. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  104507. break;
  104508. }
  104509. case "MASK" /* MASK */: {
  104510. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  104511. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  104512. if (babylonMaterial.albedoTexture) {
  104513. babylonMaterial.albedoTexture.hasAlpha = true;
  104514. }
  104515. break;
  104516. }
  104517. case "BLEND" /* BLEND */: {
  104518. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  104519. if (babylonMaterial.albedoTexture) {
  104520. babylonMaterial.albedoTexture.hasAlpha = true;
  104521. babylonMaterial.useAlphaFromAlbedoTexture = true;
  104522. }
  104523. break;
  104524. }
  104525. default: {
  104526. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  104527. }
  104528. }
  104529. };
  104530. /** @hidden */
  104531. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  104532. var _this = this;
  104533. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  104534. context = "#/textures/" + textureInfo.index;
  104535. var promises = new Array();
  104536. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  104537. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  104538. var deferred = new BABYLON.Deferred();
  104539. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  104540. if (!_this._disposed) {
  104541. deferred.resolve();
  104542. }
  104543. }, function (message, exception) {
  104544. if (!_this._disposed) {
  104545. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  104546. }
  104547. });
  104548. promises.push(deferred.promise);
  104549. babylonTexture.name = texture.name || "texture" + texture._index;
  104550. babylonTexture.wrapU = samplerData.wrapU;
  104551. babylonTexture.wrapV = samplerData.wrapV;
  104552. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  104553. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  104554. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  104555. babylonTexture.updateURL(objectURL);
  104556. }));
  104557. assign(babylonTexture);
  104558. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  104559. return Promise.all(promises).then(function () { });
  104560. };
  104561. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  104562. if (!sampler._data) {
  104563. sampler._data = {
  104564. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  104565. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  104566. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  104567. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  104568. };
  104569. }
  104570. ;
  104571. return sampler._data;
  104572. };
  104573. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  104574. if (image._objectURL) {
  104575. return image._objectURL;
  104576. }
  104577. var promise;
  104578. if (image.uri) {
  104579. promise = this._loadUriAsync(context, image.uri);
  104580. }
  104581. else {
  104582. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  104583. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  104584. }
  104585. image._objectURL = promise.then(function (data) {
  104586. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  104587. });
  104588. return image._objectURL;
  104589. };
  104590. /** @hidden */
  104591. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  104592. var _this = this;
  104593. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  104594. if (promise) {
  104595. return promise;
  104596. }
  104597. if (!GLTFLoader._ValidateUri(uri)) {
  104598. throw new Error(context + ": Uri '" + uri + "' is invalid");
  104599. }
  104600. if (BABYLON.Tools.IsBase64(uri)) {
  104601. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  104602. }
  104603. return this.preprocessUrlAsync(this._rootUrl + uri).then(function (url) {
  104604. return new Promise(function (resolve, reject) {
  104605. if (!_this._disposed) {
  104606. var request_1 = BABYLON.Tools.LoadFile(url, function (data) {
  104607. if (!_this._disposed) {
  104608. resolve(new Uint8Array(data));
  104609. }
  104610. }, function (event) {
  104611. if (!_this._disposed) {
  104612. try {
  104613. if (request_1 && _this._state === BABYLON.GLTFLoaderState.LOADING) {
  104614. request_1._lengthComputable = event.lengthComputable;
  104615. request_1._loaded = event.loaded;
  104616. request_1._total = event.total;
  104617. _this._onProgress();
  104618. }
  104619. }
  104620. catch (e) {
  104621. reject(e);
  104622. }
  104623. }
  104624. }, _this._babylonScene.database, true, function (request, exception) {
  104625. if (!_this._disposed) {
  104626. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  104627. }
  104628. });
  104629. _this._requests.push(request_1);
  104630. }
  104631. });
  104632. });
  104633. };
  104634. GLTFLoader.prototype._onProgress = function () {
  104635. if (!this._progressCallback) {
  104636. return;
  104637. }
  104638. var lengthComputable = true;
  104639. var loaded = 0;
  104640. var total = 0;
  104641. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  104642. var request = _a[_i];
  104643. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  104644. return;
  104645. }
  104646. lengthComputable = lengthComputable && request._lengthComputable;
  104647. loaded += request._loaded;
  104648. total += request._total;
  104649. }
  104650. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  104651. };
  104652. /** @hidden */
  104653. GLTFLoader._GetProperty = function (context, array, index) {
  104654. if (!array || index == undefined || !array[index]) {
  104655. throw new Error(context + ": Failed to find index (" + index + ")");
  104656. }
  104657. return array[index];
  104658. };
  104659. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  104660. // Set defaults if undefined
  104661. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  104662. switch (mode) {
  104663. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  104664. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  104665. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  104666. default:
  104667. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  104668. return BABYLON.Texture.WRAP_ADDRESSMODE;
  104669. }
  104670. };
  104671. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  104672. // Set defaults if undefined
  104673. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  104674. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  104675. if (magFilter === 9729 /* LINEAR */) {
  104676. switch (minFilter) {
  104677. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  104678. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  104679. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  104680. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  104681. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  104682. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  104683. default:
  104684. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  104685. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  104686. }
  104687. }
  104688. else {
  104689. if (magFilter !== 9728 /* NEAREST */) {
  104690. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  104691. }
  104692. switch (minFilter) {
  104693. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  104694. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  104695. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  104696. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  104697. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  104698. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  104699. default:
  104700. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  104701. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  104702. }
  104703. }
  104704. };
  104705. GLTFLoader._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) {
  104706. var buffer = bufferView.buffer;
  104707. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  104708. try {
  104709. switch (componentType) {
  104710. case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length);
  104711. case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length);
  104712. case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length);
  104713. case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length);
  104714. case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length);
  104715. case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length);
  104716. default: throw new Error("Invalid component type " + componentType);
  104717. }
  104718. }
  104719. catch (e) {
  104720. throw new Error(context + ": " + e);
  104721. }
  104722. };
  104723. GLTFLoader._GetNumComponents = function (context, type) {
  104724. switch (type) {
  104725. case "SCALAR": return 1;
  104726. case "VEC2": return 2;
  104727. case "VEC3": return 3;
  104728. case "VEC4": return 4;
  104729. case "MAT2": return 4;
  104730. case "MAT3": return 9;
  104731. case "MAT4": return 16;
  104732. }
  104733. throw new Error(context + ": Invalid type (" + type + ")");
  104734. };
  104735. GLTFLoader._ValidateUri = function (uri) {
  104736. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  104737. };
  104738. GLTFLoader._GetDrawMode = function (context, mode) {
  104739. if (mode == undefined) {
  104740. mode = 4 /* TRIANGLES */;
  104741. }
  104742. switch (mode) {
  104743. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  104744. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  104745. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  104746. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  104747. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  104748. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  104749. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  104750. }
  104751. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  104752. };
  104753. GLTFLoader.prototype._compileMaterialsAsync = function () {
  104754. var promises = new Array();
  104755. if (this._gltf.materials) {
  104756. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  104757. var material = _a[_i];
  104758. if (material._babylonData) {
  104759. for (var babylonDrawMode in material._babylonData) {
  104760. var babylonData = material._babylonData[babylonDrawMode];
  104761. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  104762. var babylonMesh = _c[_b];
  104763. // Ensure nonUniformScaling is set if necessary.
  104764. babylonMesh.computeWorldMatrix(true);
  104765. var babylonMaterial = babylonData.material;
  104766. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  104767. if (this.useClipPlane) {
  104768. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  104769. }
  104770. }
  104771. }
  104772. }
  104773. }
  104774. }
  104775. return Promise.all(promises).then(function () { });
  104776. };
  104777. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  104778. var promises = new Array();
  104779. var lights = this._babylonScene.lights;
  104780. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  104781. var light = lights_1[_i];
  104782. var generator = light.getShadowGenerator();
  104783. if (generator) {
  104784. promises.push(generator.forceCompilationAsync());
  104785. }
  104786. }
  104787. return Promise.all(promises).then(function () { });
  104788. };
  104789. GLTFLoader.prototype._clear = function () {
  104790. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  104791. var request = _a[_i];
  104792. request.abort();
  104793. }
  104794. this._requests.length = 0;
  104795. if (this._gltf && this._gltf.images) {
  104796. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  104797. var image = _c[_b];
  104798. if (image._objectURL) {
  104799. image._objectURL.then(function (value) {
  104800. URL.revokeObjectURL(value);
  104801. });
  104802. image._objectURL = undefined;
  104803. }
  104804. }
  104805. }
  104806. delete this._gltf;
  104807. delete this._babylonScene;
  104808. this._completePromises.length = 0;
  104809. for (var name_4 in this._extensions) {
  104810. this._extensions[name_4].dispose();
  104811. }
  104812. this._extensions = {};
  104813. delete this._rootBabylonMesh;
  104814. delete this._progressCallback;
  104815. this.onMeshLoadedObservable.clear();
  104816. this.onTextureLoadedObservable.clear();
  104817. this.onMaterialLoadedObservable.clear();
  104818. this.onCameraLoadedObservable.clear();
  104819. };
  104820. /** @hidden */
  104821. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  104822. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  104823. var name_5 = _a[_i];
  104824. var extension = this._extensions[name_5];
  104825. if (extension.enabled) {
  104826. var promise = actionAsync(extension);
  104827. if (promise) {
  104828. return promise;
  104829. }
  104830. }
  104831. }
  104832. return null;
  104833. };
  104834. GLTFLoader._ExtensionNames = new Array();
  104835. GLTFLoader._ExtensionFactories = {};
  104836. return GLTFLoader;
  104837. }());
  104838. GLTF2.GLTFLoader = GLTFLoader;
  104839. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  104840. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  104841. })(BABYLON || (BABYLON = {}));
  104842. //# sourceMappingURL=babylon.glTFLoader.js.map
  104843. var BABYLON;
  104844. (function (BABYLON) {
  104845. var GLTF2;
  104846. (function (GLTF2) {
  104847. /**
  104848. * Abstract class that can be implemented to extend existing glTF loader behavior.
  104849. */
  104850. var GLTFLoaderExtension = /** @class */ (function () {
  104851. function GLTFLoaderExtension(loader) {
  104852. this.enabled = true;
  104853. this._loader = loader;
  104854. }
  104855. GLTFLoaderExtension.prototype.dispose = function () {
  104856. delete this._loader;
  104857. };
  104858. // #region Overridable Methods
  104859. /** Override this method to modify the default behavior for loading scenes. */
  104860. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  104861. /** Override this method to modify the default behavior for loading nodes. */
  104862. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  104863. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  104864. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  104865. /** Override this method to modify the default behavior for loading materials. */
  104866. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) { return null; };
  104867. /** Override this method to modify the default behavior for loading uris. */
  104868. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  104869. // #endregion
  104870. /** Helper method called by a loader extension to load an glTF extension. */
  104871. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  104872. if (!property.extensions) {
  104873. return null;
  104874. }
  104875. var extensions = property.extensions;
  104876. var extension = extensions[this.name];
  104877. if (!extension) {
  104878. return null;
  104879. }
  104880. // Clear out the extension before executing the action to avoid recursing into the same property.
  104881. delete extensions[this.name];
  104882. try {
  104883. return actionAsync(context + "/extensions/" + this.name, extension);
  104884. }
  104885. finally {
  104886. // Restore the extension after executing the action.
  104887. extensions[this.name] = extension;
  104888. }
  104889. };
  104890. /** Helper method called by the loader to allow extensions to override loading scenes. */
  104891. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  104892. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  104893. };
  104894. /** Helper method called by the loader to allow extensions to override loading nodes. */
  104895. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  104896. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  104897. };
  104898. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  104899. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  104900. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  104901. };
  104902. /** Helper method called by the loader to allow extensions to override loading materials. */
  104903. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, babylonDrawMode, assign) {
  104904. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  104905. };
  104906. /** Helper method called by the loader to allow extensions to override loading uris. */
  104907. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  104908. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  104909. };
  104910. return GLTFLoaderExtension;
  104911. }());
  104912. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  104913. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  104914. })(BABYLON || (BABYLON = {}));
  104915. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  104916. var BABYLON;
  104917. (function (BABYLON) {
  104918. var GLTF2;
  104919. (function (GLTF2) {
  104920. var Extensions;
  104921. (function (Extensions) {
  104922. var NAME = "MSFT_lod";
  104923. /**
  104924. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod)
  104925. */
  104926. var MSFT_lod = /** @class */ (function (_super) {
  104927. __extends(MSFT_lod, _super);
  104928. function MSFT_lod() {
  104929. var _this = _super !== null && _super.apply(this, arguments) || this;
  104930. _this.name = NAME;
  104931. /**
  104932. * Maximum number of LODs to load, starting from the lowest LOD.
  104933. */
  104934. _this.maxLODsToLoad = Number.MAX_VALUE;
  104935. _this._loadingNodeLOD = null;
  104936. _this._loadNodeSignals = {};
  104937. _this._loadingMaterialLOD = null;
  104938. _this._loadMaterialSignals = {};
  104939. return _this;
  104940. }
  104941. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  104942. var _this = this;
  104943. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  104944. var firstPromise;
  104945. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader._gltf.nodes, extension.ids);
  104946. var _loop_1 = function (indexLOD) {
  104947. var nodeLOD = nodeLODs[indexLOD];
  104948. if (indexLOD !== 0) {
  104949. _this._loadingNodeLOD = nodeLOD;
  104950. if (!_this._loadNodeSignals[nodeLOD._index]) {
  104951. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  104952. }
  104953. }
  104954. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  104955. if (indexLOD !== 0) {
  104956. var previousNodeLOD = nodeLODs[indexLOD - 1];
  104957. if (previousNodeLOD._babylonMesh) {
  104958. previousNodeLOD._babylonMesh.dispose(false, true);
  104959. delete previousNodeLOD._babylonMesh;
  104960. }
  104961. }
  104962. if (indexLOD !== nodeLODs.length - 1) {
  104963. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  104964. if (_this._loadNodeSignals[nodeIndex]) {
  104965. _this._loadNodeSignals[nodeIndex].resolve();
  104966. delete _this._loadNodeSignals[nodeIndex];
  104967. }
  104968. }
  104969. });
  104970. if (indexLOD === 0) {
  104971. firstPromise = promise;
  104972. }
  104973. else {
  104974. _this._loader._completePromises.push(promise);
  104975. _this._loadingNodeLOD = null;
  104976. }
  104977. };
  104978. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  104979. _loop_1(indexLOD);
  104980. }
  104981. return firstPromise;
  104982. });
  104983. };
  104984. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  104985. var _this = this;
  104986. // Don't load material LODs if already loading a node LOD.
  104987. if (this._loadingNodeLOD) {
  104988. return null;
  104989. }
  104990. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  104991. var firstPromise;
  104992. var materialLODs = _this._getLODs(extensionContext, material, _this._loader._gltf.materials, extension.ids);
  104993. var _loop_2 = function (indexLOD) {
  104994. var materialLOD = materialLODs[indexLOD];
  104995. if (indexLOD !== 0) {
  104996. _this._loadingMaterialLOD = materialLOD;
  104997. if (!_this._loadMaterialSignals[materialLOD._index]) {
  104998. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  104999. }
  105000. }
  105001. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  105002. if (indexLOD !== 0) {
  105003. var babylonDataLOD = materialLOD._babylonData;
  105004. assign(babylonDataLOD[babylonDrawMode].material);
  105005. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  105006. if (previousBabylonDataLOD[babylonDrawMode]) {
  105007. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  105008. delete previousBabylonDataLOD[babylonDrawMode];
  105009. }
  105010. }
  105011. if (indexLOD !== materialLODs.length - 1) {
  105012. var materialIndex = materialLODs[indexLOD + 1]._index;
  105013. if (_this._loadMaterialSignals[materialIndex]) {
  105014. _this._loadMaterialSignals[materialIndex].resolve();
  105015. delete _this._loadMaterialSignals[materialIndex];
  105016. }
  105017. }
  105018. });
  105019. if (indexLOD === 0) {
  105020. firstPromise = promise;
  105021. }
  105022. else {
  105023. _this._loader._completePromises.push(promise);
  105024. _this._loadingMaterialLOD = null;
  105025. }
  105026. };
  105027. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  105028. _loop_2(indexLOD);
  105029. }
  105030. return firstPromise;
  105031. });
  105032. };
  105033. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  105034. var _this = this;
  105035. // Defer the loading of uris if loading a material or node LOD.
  105036. if (this._loadingMaterialLOD) {
  105037. var index = this._loadingMaterialLOD._index;
  105038. return this._loadMaterialSignals[index].promise.then(function () {
  105039. return _this._loader._loadUriAsync(context, uri);
  105040. });
  105041. }
  105042. else if (this._loadingNodeLOD) {
  105043. var index = this._loadingNodeLOD._index;
  105044. return this._loadNodeSignals[index].promise.then(function () {
  105045. return _this._loader._loadUriAsync(context, uri);
  105046. });
  105047. }
  105048. return null;
  105049. };
  105050. /**
  105051. * Gets an array of LOD properties from lowest to highest.
  105052. */
  105053. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  105054. if (this.maxLODsToLoad <= 0) {
  105055. throw new Error("maxLODsToLoad must be greater than zero");
  105056. }
  105057. var properties = new Array();
  105058. for (var i = ids.length - 1; i >= 0; i--) {
  105059. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  105060. if (properties.length === this.maxLODsToLoad) {
  105061. return properties;
  105062. }
  105063. }
  105064. properties.push(property);
  105065. return properties;
  105066. };
  105067. return MSFT_lod;
  105068. }(GLTF2.GLTFLoaderExtension));
  105069. Extensions.MSFT_lod = MSFT_lod;
  105070. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  105071. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  105072. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  105073. })(BABYLON || (BABYLON = {}));
  105074. //# sourceMappingURL=MSFT_lod.js.map
  105075. var BABYLON;
  105076. (function (BABYLON) {
  105077. var GLTF2;
  105078. (function (GLTF2) {
  105079. var Extensions;
  105080. (function (Extensions) {
  105081. var NAME = "MSFT_minecraftMesh";
  105082. /** @hidden */
  105083. var MSFT_minecraftMesh = /** @class */ (function (_super) {
  105084. __extends(MSFT_minecraftMesh, _super);
  105085. function MSFT_minecraftMesh(loader) {
  105086. var _this = _super.call(this, loader) || this;
  105087. _this.name = NAME;
  105088. _this._onMaterialLoaded = function (material) {
  105089. if (material.needAlphaBlending()) {
  105090. material.forceDepthWrite = true;
  105091. material.separateCullingPass = true;
  105092. }
  105093. material.backFaceCulling = material.forceDepthWrite;
  105094. material.twoSidedLighting = true;
  105095. };
  105096. var meshes = loader._gltf.meshes;
  105097. if (meshes && meshes.length) {
  105098. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  105099. var mesh = meshes_1[_i];
  105100. if (mesh && mesh.extras && mesh.extras.MSFT_minecraftMesh) {
  105101. _this._loader.onMaterialLoadedObservable.add(_this._onMaterialLoaded);
  105102. break;
  105103. }
  105104. }
  105105. }
  105106. return _this;
  105107. }
  105108. return MSFT_minecraftMesh;
  105109. }(GLTF2.GLTFLoaderExtension));
  105110. Extensions.MSFT_minecraftMesh = MSFT_minecraftMesh;
  105111. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_minecraftMesh(loader); });
  105112. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  105113. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  105114. })(BABYLON || (BABYLON = {}));
  105115. //# sourceMappingURL=MSFT_minecraftMesh.js.map
  105116. var BABYLON;
  105117. (function (BABYLON) {
  105118. var GLTF2;
  105119. (function (GLTF2) {
  105120. var Extensions;
  105121. (function (Extensions) {
  105122. var NAME = "MSFT_sRGBFactors";
  105123. /** @hidden */
  105124. var MSFT_sRGBFactors = /** @class */ (function (_super) {
  105125. __extends(MSFT_sRGBFactors, _super);
  105126. function MSFT_sRGBFactors(loader) {
  105127. var _this = _super.call(this, loader) || this;
  105128. _this.name = NAME;
  105129. _this._onMaterialLoaded = function (material) {
  105130. if (!material.albedoTexture) {
  105131. material.albedoColor.toLinearSpaceToRef(material.albedoColor);
  105132. }
  105133. if (!material.reflectivityTexture) {
  105134. material.reflectivityColor.toLinearSpaceToRef(material.reflectivityColor);
  105135. }
  105136. };
  105137. var materials = loader._gltf.materials;
  105138. if (materials && materials.length) {
  105139. for (var _i = 0, materials_1 = materials; _i < materials_1.length; _i++) {
  105140. var material = materials_1[_i];
  105141. if (material && material.extras && material.extras.MSFT_sRGBFactors) {
  105142. _this._loader.onMaterialLoadedObservable.add(_this._onMaterialLoaded);
  105143. break;
  105144. }
  105145. }
  105146. }
  105147. return _this;
  105148. }
  105149. return MSFT_sRGBFactors;
  105150. }(GLTF2.GLTFLoaderExtension));
  105151. Extensions.MSFT_sRGBFactors = MSFT_sRGBFactors;
  105152. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_sRGBFactors(loader); });
  105153. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  105154. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  105155. })(BABYLON || (BABYLON = {}));
  105156. //# sourceMappingURL=MSFT_sRGBFactors.js.map
  105157. var BABYLON;
  105158. (function (BABYLON) {
  105159. var GLTF2;
  105160. (function (GLTF2) {
  105161. var Extensions;
  105162. (function (Extensions) {
  105163. var NAME = "KHR_draco_mesh_compression";
  105164. /**
  105165. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression)
  105166. */
  105167. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  105168. __extends(KHR_draco_mesh_compression, _super);
  105169. function KHR_draco_mesh_compression(loader) {
  105170. var _this = _super.call(this, loader) || this;
  105171. _this.name = NAME;
  105172. _this._dracoCompression = null;
  105173. // Disable extension if decoder is not available.
  105174. if (!BABYLON.DracoCompression.DecoderAvailable) {
  105175. _this.enabled = false;
  105176. }
  105177. return _this;
  105178. }
  105179. KHR_draco_mesh_compression.prototype.dispose = function () {
  105180. if (this._dracoCompression) {
  105181. this._dracoCompression.dispose();
  105182. }
  105183. _super.prototype.dispose.call(this);
  105184. };
  105185. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  105186. var _this = this;
  105187. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  105188. if (primitive.mode != undefined) {
  105189. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  105190. primitive.mode !== 4 /* TRIANGLES */) {
  105191. throw new Error(context + ": Unsupported mode " + primitive.mode);
  105192. }
  105193. // TODO: handle triangle strips
  105194. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  105195. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  105196. }
  105197. }
  105198. var attributes = {};
  105199. var loadAttribute = function (name, kind) {
  105200. var uniqueId = extension.attributes[name];
  105201. if (uniqueId == undefined) {
  105202. return;
  105203. }
  105204. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  105205. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  105206. babylonMesh._delayInfo.push(kind);
  105207. }
  105208. attributes[kind] = uniqueId;
  105209. };
  105210. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  105211. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  105212. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  105213. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  105214. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  105215. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  105216. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  105217. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  105218. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  105219. if (!bufferView._dracoBabylonGeometry) {
  105220. bufferView._dracoBabylonGeometry = _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  105221. if (!_this._dracoCompression) {
  105222. _this._dracoCompression = new BABYLON.DracoCompression();
  105223. }
  105224. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  105225. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader._babylonScene);
  105226. babylonVertexData.applyToGeometry(babylonGeometry);
  105227. return babylonGeometry;
  105228. }).catch(function (error) {
  105229. throw new Error(context + ": " + error.message);
  105230. });
  105231. });
  105232. }
  105233. return bufferView._dracoBabylonGeometry;
  105234. });
  105235. };
  105236. return KHR_draco_mesh_compression;
  105237. }(GLTF2.GLTFLoaderExtension));
  105238. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  105239. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  105240. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  105241. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  105242. })(BABYLON || (BABYLON = {}));
  105243. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  105244. var BABYLON;
  105245. (function (BABYLON) {
  105246. var GLTF2;
  105247. (function (GLTF2) {
  105248. var Extensions;
  105249. (function (Extensions) {
  105250. var NAME = "KHR_materials_pbrSpecularGlossiness";
  105251. /**
  105252. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness)
  105253. */
  105254. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  105255. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  105256. function KHR_materials_pbrSpecularGlossiness() {
  105257. var _this = _super !== null && _super.apply(this, arguments) || this;
  105258. _this.name = NAME;
  105259. return _this;
  105260. }
  105261. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  105262. var _this = this;
  105263. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  105264. material._babylonData = material._babylonData || {};
  105265. var babylonData = material._babylonData[babylonDrawMode];
  105266. if (!babylonData) {
  105267. var promises = new Array();
  105268. var name_1 = material.name || "materialSG_" + material._index;
  105269. var babylonMaterial = _this._loader._createMaterial(name_1, babylonDrawMode);
  105270. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  105271. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  105272. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  105273. babylonData = {
  105274. material: babylonMaterial,
  105275. meshes: [],
  105276. loaded: Promise.all(promises).then(function () { })
  105277. };
  105278. material._babylonData[babylonDrawMode] = babylonData;
  105279. }
  105280. babylonData.meshes.push(babylonMesh);
  105281. assign(babylonData.material);
  105282. return babylonData.loaded;
  105283. });
  105284. };
  105285. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  105286. var promises = new Array();
  105287. if (properties.diffuseFactor) {
  105288. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  105289. babylonMaterial.alpha = properties.diffuseFactor[3];
  105290. }
  105291. else {
  105292. babylonMaterial.albedoColor = BABYLON.Color3.White();
  105293. }
  105294. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  105295. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  105296. if (properties.diffuseTexture) {
  105297. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  105298. babylonMaterial.albedoTexture = texture;
  105299. }));
  105300. }
  105301. if (properties.specularGlossinessTexture) {
  105302. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  105303. babylonMaterial.reflectivityTexture = texture;
  105304. }));
  105305. babylonMaterial.reflectivityTexture.hasAlpha = true;
  105306. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  105307. }
  105308. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  105309. return Promise.all(promises).then(function () { });
  105310. };
  105311. return KHR_materials_pbrSpecularGlossiness;
  105312. }(GLTF2.GLTFLoaderExtension));
  105313. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  105314. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  105315. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  105316. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  105317. })(BABYLON || (BABYLON = {}));
  105318. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  105319. var BABYLON;
  105320. (function (BABYLON) {
  105321. var GLTF2;
  105322. (function (GLTF2) {
  105323. var Extensions;
  105324. (function (Extensions) {
  105325. var NAME = "KHR_materials_unlit";
  105326. /**
  105327. * [Specification](https://github.com/donmccurdy/glTF/tree/feat-khr-materials-cmnConstant/extensions/2.0/Khronos/KHR_materials_unlit) (Experimental)
  105328. */
  105329. var KHR_materials_unlit = /** @class */ (function (_super) {
  105330. __extends(KHR_materials_unlit, _super);
  105331. function KHR_materials_unlit() {
  105332. var _this = _super !== null && _super.apply(this, arguments) || this;
  105333. _this.name = NAME;
  105334. return _this;
  105335. }
  105336. KHR_materials_unlit.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  105337. var _this = this;
  105338. return this._loadExtensionAsync(context, material, function () {
  105339. material._babylonData = material._babylonData || {};
  105340. var babylonData = material._babylonData[babylonDrawMode];
  105341. if (!babylonData) {
  105342. var name_1 = material.name || "materialUnlit_" + material._index;
  105343. var babylonMaterial = _this._loader._createMaterial(name_1, babylonDrawMode);
  105344. babylonMaterial.unlit = true;
  105345. var promise = _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  105346. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  105347. babylonData = {
  105348. material: babylonMaterial,
  105349. meshes: [],
  105350. loaded: promise
  105351. };
  105352. material._babylonData[babylonDrawMode] = babylonData;
  105353. }
  105354. babylonData.meshes.push(babylonMesh);
  105355. assign(babylonData.material);
  105356. return babylonData.loaded;
  105357. });
  105358. };
  105359. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  105360. var promises = new Array();
  105361. // Ensure metallic workflow
  105362. babylonMaterial.metallic = 1;
  105363. babylonMaterial.roughness = 1;
  105364. var properties = material.pbrMetallicRoughness;
  105365. if (properties) {
  105366. if (properties.baseColorFactor) {
  105367. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  105368. babylonMaterial.alpha = properties.baseColorFactor[3];
  105369. }
  105370. else {
  105371. babylonMaterial.albedoColor = BABYLON.Color3.White();
  105372. }
  105373. if (properties.baseColorTexture) {
  105374. promises.push(this._loader._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  105375. babylonMaterial.albedoTexture = texture;
  105376. }));
  105377. }
  105378. }
  105379. if (material.doubleSided) {
  105380. babylonMaterial.backFaceCulling = false;
  105381. babylonMaterial.twoSidedLighting = true;
  105382. }
  105383. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  105384. return Promise.all(promises).then(function () { });
  105385. };
  105386. return KHR_materials_unlit;
  105387. }(GLTF2.GLTFLoaderExtension));
  105388. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  105389. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  105390. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  105391. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  105392. })(BABYLON || (BABYLON = {}));
  105393. var BABYLON;
  105394. (function (BABYLON) {
  105395. var GLTF2;
  105396. (function (GLTF2) {
  105397. var Extensions;
  105398. (function (Extensions) {
  105399. var NAME = "KHR_lights";
  105400. var LightType;
  105401. (function (LightType) {
  105402. LightType["AMBIENT"] = "ambient";
  105403. LightType["DIRECTIONAL"] = "directional";
  105404. LightType["POINT"] = "point";
  105405. LightType["SPOT"] = "spot";
  105406. })(LightType || (LightType = {}));
  105407. /**
  105408. * [Specification](https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights) (Experimental)
  105409. */
  105410. var KHR_lights = /** @class */ (function (_super) {
  105411. __extends(KHR_lights, _super);
  105412. function KHR_lights() {
  105413. var _this = _super !== null && _super.apply(this, arguments) || this;
  105414. _this.name = NAME;
  105415. return _this;
  105416. }
  105417. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  105418. var _this = this;
  105419. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  105420. var promise = _this._loader._loadSceneAsync(extensionContext, scene);
  105421. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  105422. if (light.type !== LightType.AMBIENT) {
  105423. throw new Error(extensionContext + ": Only ambient lights are allowed on a scene");
  105424. }
  105425. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  105426. return promise;
  105427. });
  105428. };
  105429. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  105430. var _this = this;
  105431. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  105432. var promise = _this._loader._loadNodeAsync(extensionContext, node);
  105433. var babylonLight;
  105434. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  105435. var name = node._babylonMesh.name;
  105436. switch (light.type) {
  105437. case LightType.AMBIENT: {
  105438. throw new Error(extensionContext + ": Ambient lights are not allowed on a node");
  105439. }
  105440. case LightType.DIRECTIONAL: {
  105441. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  105442. break;
  105443. }
  105444. case LightType.POINT: {
  105445. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  105446. break;
  105447. }
  105448. case LightType.SPOT: {
  105449. var spotLight = light;
  105450. // TODO: support inner and outer cone angles
  105451. //const innerConeAngle = spotLight.innerConeAngle || 0;
  105452. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  105453. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  105454. break;
  105455. }
  105456. default: {
  105457. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  105458. }
  105459. }
  105460. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  105461. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  105462. babylonLight.parent = node._babylonMesh;
  105463. return promise;
  105464. });
  105465. };
  105466. Object.defineProperty(KHR_lights.prototype, "_lights", {
  105467. get: function () {
  105468. var extensions = this._loader._gltf.extensions;
  105469. if (!extensions || !extensions[this.name]) {
  105470. throw new Error("#/extensions: '" + this.name + "' not found");
  105471. }
  105472. var extension = extensions[this.name];
  105473. return extension.lights;
  105474. },
  105475. enumerable: true,
  105476. configurable: true
  105477. });
  105478. return KHR_lights;
  105479. }(GLTF2.GLTFLoaderExtension));
  105480. Extensions.KHR_lights = KHR_lights;
  105481. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  105482. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  105483. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  105484. })(BABYLON || (BABYLON = {}));
  105485. return BABYLON;
  105486. });
  105487. /***/ }),
  105488. /* 20 */
  105489. /***/ (function(module, exports, __webpack_require__) {
  105490. "use strict";
  105491. Object.defineProperty(exports, "__esModule", { value: true });
  105492. var babylonjs_1 = __webpack_require__(0);
  105493. var modelAnimation_1 = __webpack_require__(21);
  105494. var deepmerge = __webpack_require__(1);
  105495. var helper_1 = __webpack_require__(2);
  105496. var ModelState;
  105497. (function (ModelState) {
  105498. ModelState[ModelState["INIT"] = 0] = "INIT";
  105499. ModelState[ModelState["LOADING"] = 1] = "LOADING";
  105500. ModelState[ModelState["LOADED"] = 2] = "LOADED";
  105501. ModelState[ModelState["CANCELED"] = 3] = "CANCELED";
  105502. ModelState[ModelState["ERROR"] = 4] = "ERROR";
  105503. })(ModelState = exports.ModelState || (exports.ModelState = {}));
  105504. /**
  105505. * The viewer model is a container for all assets representing a sngle loaded model.
  105506. */
  105507. var ViewerModel = /** @class */ (function () {
  105508. function ViewerModel(_viewer, modelConfiguration) {
  105509. var _this = this;
  105510. this._viewer = _viewer;
  105511. /**
  105512. * the list of meshes that are a part of this model
  105513. */
  105514. this._meshes = [];
  105515. /**
  105516. * ParticleSystems connected to this model
  105517. */
  105518. this.particleSystems = [];
  105519. /**
  105520. * Skeletons defined in this model
  105521. */
  105522. this.skeletons = [];
  105523. this.onLoadedObservable = new babylonjs_1.Observable();
  105524. this.onLoadErrorObservable = new babylonjs_1.Observable();
  105525. this.onLoadProgressObservable = new babylonjs_1.Observable();
  105526. this.onAfterConfigure = new babylonjs_1.Observable();
  105527. this.state = ModelState.INIT;
  105528. this.rootMesh = new babylonjs_1.AbstractMesh("modelRootMesh", this._viewer.sceneManager.scene);
  105529. this._animations = [];
  105530. //create a copy of the configuration to make sure it doesn't change even after it is changed in the viewer
  105531. this._modelConfiguration = deepmerge(this._viewer.configuration.model || {}, modelConfiguration);
  105532. this._viewer.sceneManager.models.push(this);
  105533. this._viewer.onModelAddedObservable.notifyObservers(this);
  105534. this.onLoadedObservable.add(function () {
  105535. _this._viewer.onModelLoadedObservable.notifyObservers(_this);
  105536. _this._initAnimations();
  105537. });
  105538. }
  105539. Object.defineProperty(ViewerModel.prototype, "enabled", {
  105540. /**
  105541. * Is this model enabled?
  105542. */
  105543. get: function () {
  105544. return this.rootMesh.isEnabled();
  105545. },
  105546. /**
  105547. * Set whether this model is enabled or not.
  105548. */
  105549. set: function (enable) {
  105550. this.rootMesh.setEnabled(enable);
  105551. },
  105552. enumerable: true,
  105553. configurable: true
  105554. });
  105555. /**
  105556. * Get the viewer showing this model
  105557. */
  105558. ViewerModel.prototype.getViewer = function () {
  105559. return this._viewer;
  105560. };
  105561. /**
  105562. * Add a mesh to this model.
  105563. * Any mesh that has no parent will be provided with the root mesh as its new parent.
  105564. *
  105565. * @param mesh the new mesh to add
  105566. * @param triggerLoaded should this mesh trigger the onLoaded observable. Used when adding meshes manually.
  105567. */
  105568. ViewerModel.prototype.addMesh = function (mesh, triggerLoaded) {
  105569. if (!mesh.parent) {
  105570. mesh.parent = this.rootMesh;
  105571. }
  105572. mesh.receiveShadows = !!this.configuration.receiveShadows;
  105573. this._meshes.push(mesh);
  105574. if (triggerLoaded) {
  105575. return this.onLoadedObservable.notifyObserversWithPromise(this);
  105576. }
  105577. };
  105578. Object.defineProperty(ViewerModel.prototype, "meshes", {
  105579. /**
  105580. * get the list of meshes (excluding the root mesh)
  105581. */
  105582. get: function () {
  105583. return this._meshes;
  105584. },
  105585. enumerable: true,
  105586. configurable: true
  105587. });
  105588. Object.defineProperty(ViewerModel.prototype, "configuration", {
  105589. /**
  105590. * Get the model's configuration
  105591. */
  105592. get: function () {
  105593. return this._modelConfiguration;
  105594. },
  105595. /**
  105596. * (Re-)set the model's entire configuration
  105597. * @param newConfiguration the new configuration to replace the new one
  105598. */
  105599. set: function (newConfiguration) {
  105600. this._modelConfiguration = newConfiguration;
  105601. this._configureModel();
  105602. },
  105603. enumerable: true,
  105604. configurable: true
  105605. });
  105606. /**
  105607. * Update the current configuration with new values.
  105608. * Configuration will not be overwritten, but merged with the new configuration.
  105609. * Priority is to the new configuration
  105610. * @param newConfiguration the configuration to be merged into the current configuration;
  105611. */
  105612. ViewerModel.prototype.updateConfiguration = function (newConfiguration) {
  105613. this._modelConfiguration = deepmerge(this._modelConfiguration, newConfiguration);
  105614. this._configureModel();
  105615. };
  105616. ViewerModel.prototype._initAnimations = function () {
  105617. var _this = this;
  105618. // check if this is not a gltf loader and init the animations
  105619. if (this.skeletons.length) {
  105620. this.skeletons.forEach(function (skeleton, idx) {
  105621. var ag = new babylonjs_1.AnimationGroup("animation-" + idx, _this._viewer.sceneManager.scene);
  105622. skeleton.getAnimatables().forEach(function (a) {
  105623. if (a.animations[0]) {
  105624. ag.addTargetedAnimation(a.animations[0], a);
  105625. }
  105626. });
  105627. _this.addAnimationGroup(ag);
  105628. });
  105629. }
  105630. if (!this._modelConfiguration)
  105631. return;
  105632. if (this._modelConfiguration.animation) {
  105633. if (this._modelConfiguration.animation.playOnce) {
  105634. this._animations.forEach(function (a) {
  105635. a.playMode = modelAnimation_1.AnimationPlayMode.ONCE;
  105636. });
  105637. }
  105638. if (this._modelConfiguration.animation.autoStart && this._animations.length) {
  105639. var animationName = this._modelConfiguration.animation.autoStart === true ?
  105640. this._animations[0].name : this._modelConfiguration.animation.autoStart;
  105641. this.playAnimation(animationName);
  105642. }
  105643. }
  105644. };
  105645. /**
  105646. * Add a new animation group to this model.
  105647. * @param animationGroup the new animation group to be added
  105648. */
  105649. ViewerModel.prototype.addAnimationGroup = function (animationGroup) {
  105650. this._animations.push(new modelAnimation_1.GroupModelAnimation(animationGroup));
  105651. };
  105652. /**
  105653. * Get the ModelAnimation array
  105654. */
  105655. ViewerModel.prototype.getAnimations = function () {
  105656. return this._animations;
  105657. };
  105658. /**
  105659. * Get the animations' names. Using the names you can play a specific animation.
  105660. */
  105661. ViewerModel.prototype.getAnimationNames = function () {
  105662. return this._animations.map(function (a) { return a.name; });
  105663. };
  105664. /**
  105665. * Get an animation by the provided name. Used mainly when playing n animation.
  105666. * @param name the name of the animation to find
  105667. */
  105668. ViewerModel.prototype._getAnimationByName = function (name) {
  105669. // can't use .find, noe available on IE
  105670. var filtered = this._animations.filter(function (a) { return a.name === name; });
  105671. // what the next line means - if two animations have the same name, they will not be returned!
  105672. if (filtered.length === 1) {
  105673. return filtered[0];
  105674. }
  105675. else {
  105676. return null;
  105677. }
  105678. };
  105679. /**
  105680. * Choose an initialized animation using its name and start playing it
  105681. * @param name the name of the animation to play
  105682. * @returns The model aniamtion to be played.
  105683. */
  105684. ViewerModel.prototype.playAnimation = function (name) {
  105685. var animation = this._getAnimationByName(name);
  105686. if (animation) {
  105687. if (this.currentAnimation) {
  105688. this.currentAnimation.stop();
  105689. }
  105690. this.currentAnimation = animation;
  105691. animation.start();
  105692. return animation;
  105693. }
  105694. else {
  105695. throw new Error("animation not found - " + name);
  105696. }
  105697. };
  105698. ViewerModel.prototype._configureModel = function () {
  105699. var _this = this;
  105700. // this can be changed to the meshes that have rootMesh a parent without breaking anything.
  105701. var meshesWithNoParent = [this.rootMesh]; //this._meshes.filter(m => m.parent === this.rootMesh);
  105702. var updateMeshesWithNoParent = function (variable, value, param) {
  105703. meshesWithNoParent.forEach(function (mesh) {
  105704. if (param) {
  105705. mesh[variable][param] = value;
  105706. }
  105707. else {
  105708. mesh[variable] = value;
  105709. }
  105710. });
  105711. };
  105712. var updateXYZ = function (variable, configValues) {
  105713. if (configValues.x !== undefined) {
  105714. updateMeshesWithNoParent(variable, configValues.x, 'x');
  105715. }
  105716. if (configValues.y !== undefined) {
  105717. updateMeshesWithNoParent(variable, configValues.y, 'y');
  105718. }
  105719. if (configValues.z !== undefined) {
  105720. updateMeshesWithNoParent(variable, configValues.z, 'z');
  105721. }
  105722. if (configValues.w !== undefined) {
  105723. updateMeshesWithNoParent(variable, configValues.w, 'w');
  105724. }
  105725. };
  105726. if (this._modelConfiguration.normalize) {
  105727. var center = false;
  105728. var unitSize = false;
  105729. var parentIndex = void 0;
  105730. if (this._modelConfiguration.normalize === true) {
  105731. center = true;
  105732. unitSize = true;
  105733. }
  105734. else {
  105735. center = !!this._modelConfiguration.normalize.center;
  105736. unitSize = !!this._modelConfiguration.normalize.unitSize;
  105737. parentIndex = this._modelConfiguration.normalize.parentIndex;
  105738. }
  105739. var meshesToNormalize = [];
  105740. if (parentIndex !== undefined) {
  105741. meshesToNormalize.push(this._meshes[parentIndex]);
  105742. }
  105743. else {
  105744. meshesToNormalize = meshesWithNoParent;
  105745. }
  105746. if (unitSize) {
  105747. meshesToNormalize.forEach(function (mesh) {
  105748. mesh.normalizeToUnitCube(true);
  105749. mesh.computeWorldMatrix(true);
  105750. });
  105751. }
  105752. if (center) {
  105753. meshesToNormalize.forEach(function (mesh) {
  105754. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  105755. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  105756. var halfSizeVec = sizeVec.scale(0.5);
  105757. var center = boundingInfo.min.add(halfSizeVec);
  105758. mesh.position = center.scale(-1);
  105759. // Recompute Info.
  105760. mesh.computeWorldMatrix(true);
  105761. });
  105762. }
  105763. }
  105764. else {
  105765. //center automatically
  105766. meshesWithNoParent.forEach(function (mesh) {
  105767. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  105768. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  105769. var halfSizeVec = sizeVec.scale(0.5);
  105770. var center = boundingInfo.min.add(halfSizeVec);
  105771. mesh.position = center.scale(-1);
  105772. // Recompute Info.
  105773. mesh.computeWorldMatrix(true);
  105774. });
  105775. }
  105776. // position?
  105777. if (this._modelConfiguration.position) {
  105778. updateXYZ('position', this._modelConfiguration.position);
  105779. }
  105780. if (this._modelConfiguration.rotation) {
  105781. //quaternion?
  105782. if (this._modelConfiguration.rotation.w) {
  105783. meshesWithNoParent.forEach(function (mesh) {
  105784. if (!mesh.rotationQuaternion) {
  105785. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  105786. }
  105787. });
  105788. updateXYZ('rotationQuaternion', this._modelConfiguration.rotation);
  105789. }
  105790. else {
  105791. updateXYZ('rotation', this._modelConfiguration.rotation);
  105792. }
  105793. }
  105794. if (this._modelConfiguration.rotationOffsetAxis) {
  105795. var rotationAxis_1 = new babylonjs_1.Vector3(0, 0, 0).copyFrom(this._modelConfiguration.rotationOffsetAxis);
  105796. meshesWithNoParent.forEach(function (m) {
  105797. if (_this._modelConfiguration.rotationOffsetAngle) {
  105798. m.rotate(rotationAxis_1, _this._modelConfiguration.rotationOffsetAngle);
  105799. }
  105800. });
  105801. }
  105802. if (this._modelConfiguration.scaling) {
  105803. updateXYZ('scaling', this._modelConfiguration.scaling);
  105804. }
  105805. if (this._modelConfiguration.castShadow) {
  105806. this._meshes.forEach(function (mesh) {
  105807. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  105808. });
  105809. }
  105810. var meshes = this.rootMesh.getChildMeshes(false);
  105811. meshes.filter(function (m) { return m.material; }).forEach(function (mesh) {
  105812. _this._applyModelMaterialConfiguration(mesh.material);
  105813. });
  105814. this.onAfterConfigure.notifyObservers(this);
  105815. };
  105816. /**
  105817. * Apply a material configuration to a material
  105818. * @param material Material to apply configuration to
  105819. */
  105820. ViewerModel.prototype._applyModelMaterialConfiguration = function (material) {
  105821. if (!this._modelConfiguration.material)
  105822. return;
  105823. helper_1.extendClassWithConfig(material, this._modelConfiguration.material);
  105824. if (material instanceof BABYLON.PBRMaterial) {
  105825. if (this._modelConfiguration.material.directIntensity !== undefined) {
  105826. material.directIntensity = this._modelConfiguration.material.directIntensity;
  105827. }
  105828. if (this._modelConfiguration.material.emissiveIntensity !== undefined) {
  105829. material.emissiveIntensity = this._modelConfiguration.material.emissiveIntensity;
  105830. }
  105831. if (this._modelConfiguration.material.environmentIntensity !== undefined) {
  105832. material.environmentIntensity = this._modelConfiguration.material.environmentIntensity;
  105833. }
  105834. if (this._modelConfiguration.material.directEnabled !== undefined) {
  105835. material.disableLighting = !this._modelConfiguration.material.directEnabled;
  105836. }
  105837. if (this._viewer.sceneManager.mainColor) {
  105838. material.reflectionColor = this._viewer.sceneManager.mainColor;
  105839. }
  105840. }
  105841. else if (material instanceof BABYLON.MultiMaterial) {
  105842. for (var i = 0; i < material.subMaterials.length; i++) {
  105843. var subMaterial = material.subMaterials[i];
  105844. if (subMaterial) {
  105845. this._applyModelMaterialConfiguration(subMaterial);
  105846. }
  105847. }
  105848. }
  105849. };
  105850. /**
  105851. * Will remove this model from the viewer (but NOT dispose it).
  105852. */
  105853. ViewerModel.prototype.remove = function () {
  105854. this._viewer.sceneManager.models.splice(this._viewer.sceneManager.models.indexOf(this), 1);
  105855. // hide it
  105856. this.rootMesh.isVisible = false;
  105857. this._viewer.onModelRemovedObservable.notifyObservers(this);
  105858. };
  105859. /**
  105860. * Dispose this model, including all of its associated assets.
  105861. */
  105862. ViewerModel.prototype.dispose = function () {
  105863. this.remove();
  105864. this.onAfterConfigure.clear();
  105865. this.onLoadedObservable.clear();
  105866. this.onLoadErrorObservable.clear();
  105867. this.onLoadProgressObservable.clear();
  105868. if (this.loader && this.loader.name === "gltf") {
  105869. this.loader.dispose();
  105870. }
  105871. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  105872. this.particleSystems.length = 0;
  105873. this.skeletons.forEach(function (s) { return s.dispose(); });
  105874. this.skeletons.length = 0;
  105875. this._animations.forEach(function (ag) { return ag.dispose(); });
  105876. this._animations.length = 0;
  105877. this._meshes.forEach(function (m) { return m.dispose(); });
  105878. this._meshes.length = 0;
  105879. this.rootMesh.dispose();
  105880. };
  105881. return ViewerModel;
  105882. }());
  105883. exports.ViewerModel = ViewerModel;
  105884. /***/ }),
  105885. /* 21 */
  105886. /***/ (function(module, exports, __webpack_require__) {
  105887. "use strict";
  105888. Object.defineProperty(exports, "__esModule", { value: true });
  105889. /**
  105890. * Animation play mode enum - is the animation looping or playing once
  105891. */
  105892. var AnimationPlayMode;
  105893. (function (AnimationPlayMode) {
  105894. AnimationPlayMode[AnimationPlayMode["ONCE"] = 0] = "ONCE";
  105895. AnimationPlayMode[AnimationPlayMode["LOOP"] = 1] = "LOOP";
  105896. })(AnimationPlayMode = exports.AnimationPlayMode || (exports.AnimationPlayMode = {}));
  105897. /**
  105898. * An enum representing the current state of an animation object
  105899. */
  105900. var AnimationState;
  105901. (function (AnimationState) {
  105902. AnimationState[AnimationState["INIT"] = 0] = "INIT";
  105903. AnimationState[AnimationState["PLAYING"] = 1] = "PLAYING";
  105904. AnimationState[AnimationState["PAUSED"] = 2] = "PAUSED";
  105905. AnimationState[AnimationState["STOPPED"] = 3] = "STOPPED";
  105906. AnimationState[AnimationState["ENDED"] = 4] = "ENDED";
  105907. })(AnimationState = exports.AnimationState || (exports.AnimationState = {}));
  105908. /**
  105909. * The GroupModelAnimation is an implementation of the IModelAnimation interface using BABYLON's
  105910. * native GroupAnimation class.
  105911. */
  105912. var GroupModelAnimation = /** @class */ (function () {
  105913. /**
  105914. * Create a new GroupModelAnimation object using an AnimationGroup object
  105915. * @param _animationGroup The aniamtion group to base the class on
  105916. */
  105917. function GroupModelAnimation(_animationGroup) {
  105918. var _this = this;
  105919. this._animationGroup = _animationGroup;
  105920. this._state = AnimationState.INIT;
  105921. this._playMode = AnimationPlayMode.LOOP;
  105922. this._animationGroup.onAnimationEndObservable.add(function () {
  105923. _this.stop();
  105924. _this._state = AnimationState.ENDED;
  105925. });
  105926. }
  105927. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  105928. /**
  105929. * Get the animation's name
  105930. */
  105931. get: function () {
  105932. return this._animationGroup.name;
  105933. },
  105934. enumerable: true,
  105935. configurable: true
  105936. });
  105937. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  105938. /**
  105939. * Get the current animation's state
  105940. */
  105941. get: function () {
  105942. return this._state;
  105943. },
  105944. enumerable: true,
  105945. configurable: true
  105946. });
  105947. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  105948. /**
  105949. * Gets the speed ratio to use for all animations
  105950. */
  105951. get: function () {
  105952. return this._animationGroup.speedRatio;
  105953. },
  105954. /**
  105955. * Sets the speed ratio to use for all animations
  105956. */
  105957. set: function (value) {
  105958. this._animationGroup.speedRatio = value;
  105959. },
  105960. enumerable: true,
  105961. configurable: true
  105962. });
  105963. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  105964. /**
  105965. * Get the max numbers of frame available in the animation group
  105966. *
  105967. * In correlation to an arry, this would be ".length"
  105968. */
  105969. get: function () {
  105970. var animationFrames = this._animationGroup.targetedAnimations.map(function (ta) {
  105971. var keys = ta.animation.getKeys();
  105972. return keys[keys.length - 1].frame;
  105973. });
  105974. return Math.max.apply(null, animationFrames);
  105975. },
  105976. enumerable: true,
  105977. configurable: true
  105978. });
  105979. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  105980. /**
  105981. * Get the current frame playing right now.
  105982. * This can be used to poll the frame currently playing (and, for exmaple, display a progress bar with the data)
  105983. *
  105984. * In correlation to an array, this would be the current index
  105985. */
  105986. get: function () {
  105987. // get the first currentFrame found
  105988. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  105989. var animatable = this._animationGroup.animatables[i];
  105990. var animations = animatable.getAnimations();
  105991. if (!animations || !animations.length) {
  105992. continue;
  105993. }
  105994. for (var idx = 0; idx < animations.length; ++idx) {
  105995. if (animations[idx].currentFrame) {
  105996. return animations[idx].currentFrame;
  105997. }
  105998. }
  105999. }
  106000. return 0;
  106001. },
  106002. enumerable: true,
  106003. configurable: true
  106004. });
  106005. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  106006. /**
  106007. * Get the FPS value of this animation
  106008. */
  106009. get: function () {
  106010. // get the first currentFrame found
  106011. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  106012. var animatable = this._animationGroup.animatables[i];
  106013. var animations = animatable.getAnimations();
  106014. if (!animations || !animations.length) {
  106015. continue;
  106016. }
  106017. for (var idx = 0; idx < animations.length; ++idx) {
  106018. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  106019. return animations[idx].animation.framePerSecond;
  106020. }
  106021. }
  106022. }
  106023. return 0;
  106024. },
  106025. enumerable: true,
  106026. configurable: true
  106027. });
  106028. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  106029. /**
  106030. * What is the animation'S play mode (looping or played once)
  106031. */
  106032. get: function () {
  106033. return this._playMode;
  106034. },
  106035. /**
  106036. * Set the play mode.
  106037. * If the animation is played, it will continue playing at least once more, depending on the new play mode set.
  106038. * If the animation is not set, the will be initialized and will wait for the user to start playing it.
  106039. */
  106040. set: function (value) {
  106041. if (value === this._playMode) {
  106042. return;
  106043. }
  106044. this._playMode = value;
  106045. if (this.state === AnimationState.PLAYING) {
  106046. this._animationGroup.play(this._playMode === AnimationPlayMode.LOOP);
  106047. }
  106048. else {
  106049. this._animationGroup.reset();
  106050. this._state = AnimationState.INIT;
  106051. }
  106052. },
  106053. enumerable: true,
  106054. configurable: true
  106055. });
  106056. /**
  106057. * Reset the animation group
  106058. */
  106059. GroupModelAnimation.prototype.reset = function () {
  106060. this._animationGroup.reset();
  106061. };
  106062. /**
  106063. * Restart the animation group
  106064. */
  106065. GroupModelAnimation.prototype.restart = function () {
  106066. this._animationGroup.restart();
  106067. };
  106068. /**
  106069. *
  106070. * @param frameNumber Go to a specific frame in the animation
  106071. */
  106072. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  106073. // this._animationGroup.goToFrame(frameNumber);
  106074. this._animationGroup['_animatables'].forEach(function (a) {
  106075. a.goToFrame(frameNumber);
  106076. });
  106077. };
  106078. /**
  106079. * Start playing the animation.
  106080. */
  106081. GroupModelAnimation.prototype.start = function () {
  106082. this._animationGroup.start(this.playMode === AnimationPlayMode.LOOP, this.speedRatio);
  106083. if (this._animationGroup.isStarted) {
  106084. this._state = AnimationState.PLAYING;
  106085. }
  106086. };
  106087. /**
  106088. * Pause the animation
  106089. */
  106090. GroupModelAnimation.prototype.pause = function () {
  106091. this._animationGroup.pause();
  106092. this._state = AnimationState.PAUSED;
  106093. };
  106094. /**
  106095. * Stop the animation.
  106096. * This will fail silently if the animation group is already stopped.
  106097. */
  106098. GroupModelAnimation.prototype.stop = function () {
  106099. this._animationGroup.stop();
  106100. if (!this._animationGroup.isStarted) {
  106101. this._state = AnimationState.STOPPED;
  106102. }
  106103. };
  106104. /**
  106105. * Dispose this animation object.
  106106. */
  106107. GroupModelAnimation.prototype.dispose = function () {
  106108. this._animationGroup.dispose();
  106109. };
  106110. return GroupModelAnimation;
  106111. }());
  106112. exports.GroupModelAnimation = GroupModelAnimation;
  106113. /***/ }),
  106114. /* 22 */
  106115. /***/ (function(module, exports, __webpack_require__) {
  106116. module.exports = __webpack_require__(5);
  106117. /***/ }),
  106118. /* 23 */
  106119. /***/ (function(module, exports) {
  106120. var g;
  106121. // This works in non-strict mode
  106122. g = (function() {
  106123. return this;
  106124. })();
  106125. try {
  106126. // This works if eval is allowed (see CSP)
  106127. g = g || Function("return this")() || (1,eval)("this");
  106128. } catch(e) {
  106129. // This works if the window reference is available
  106130. if(typeof window === "object")
  106131. g = window;
  106132. }
  106133. // g can still be undefined, but nothing to do about it...
  106134. // We return undefined, instead of nothing here, so it's
  106135. // easier to handle this case. if(!global) { ...}
  106136. module.exports = g;
  106137. /***/ }),
  106138. /* 24 */
  106139. /***/ (function(module, exports) {
  106140. if(typeof CANNON === 'undefined') {var e = new Error("Cannot find module \"CANNON\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  106141. module.exports = CANNON;
  106142. /***/ }),
  106143. /* 25 */
  106144. /***/ (function(module, exports) {
  106145. if(typeof OIMO === 'undefined') {var e = new Error("Cannot find module \"OIMO\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  106146. module.exports = OIMO;
  106147. /***/ }),
  106148. /* 26 */
  106149. /***/ (function(module, exports) {
  106150. if(typeof earcut === 'undefined') {var e = new Error("Cannot find module \"earcut\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  106151. module.exports = earcut;
  106152. /***/ }),
  106153. /* 27 */
  106154. /***/ (function(module, exports, __webpack_require__) {
  106155. "use strict";
  106156. Object.defineProperty(exports, "__esModule", { value: true });
  106157. var babylonjs_1 = __webpack_require__(0);
  106158. var helper_1 = __webpack_require__(2);
  106159. var viewerLabs_1 = __webpack_require__(28);
  106160. var SceneManager = /** @class */ (function () {
  106161. function SceneManager(_viewer) {
  106162. var _this = this;
  106163. this._viewer = _viewer;
  106164. this._mainColor = babylonjs_1.Color3.White();
  106165. this._white = babylonjs_1.Color3.White();
  106166. this._piplines = {};
  106167. this._processShadows = true;
  106168. this.models = [];
  106169. this.onCameraConfiguredObservable = new babylonjs_1.Observable();
  106170. this.onLightsConfiguredObservable = new babylonjs_1.Observable();
  106171. this.onModelsConfiguredObservable = new babylonjs_1.Observable();
  106172. this.onSceneConfiguredObservable = new babylonjs_1.Observable();
  106173. this.onSceneInitObservable = new babylonjs_1.Observable();
  106174. this.onSceneOptimizerConfiguredObservable = new babylonjs_1.Observable();
  106175. this.onEnvironmentConfiguredObservable = new babylonjs_1.Observable();
  106176. this._viewer.onEngineInitObservable.add(function () {
  106177. _this._handleHardwareLimitations();
  106178. });
  106179. this.labs = new viewerLabs_1.ViewerLabs(this);
  106180. }
  106181. Object.defineProperty(SceneManager.prototype, "isHdrSupported", {
  106182. /**
  106183. * Returns a boolean representing HDR support
  106184. */
  106185. get: function () {
  106186. return this._hdrSupport;
  106187. },
  106188. enumerable: true,
  106189. configurable: true
  106190. });
  106191. Object.defineProperty(SceneManager.prototype, "mainColor", {
  106192. /**
  106193. * Return the main color defined in the configuration.
  106194. */
  106195. get: function () {
  106196. return this._mainColor;
  106197. },
  106198. enumerable: true,
  106199. configurable: true
  106200. });
  106201. Object.defineProperty(SceneManager.prototype, "processShadows", {
  106202. /**
  106203. * The flag defining whether shadows are rendered constantly or once.
  106204. */
  106205. get: function () {
  106206. return this._processShadows;
  106207. },
  106208. /**
  106209. * Should shadows be rendered every frame, or only once and stop.
  106210. * This can be used to optimize a scene.
  106211. *
  106212. * Not that the shadows will NOT disapear but will remain in place.
  106213. * @param process if true shadows will be updated once every frame. if false they will stop being updated.
  106214. */
  106215. set: function (process) {
  106216. var refreshType = process ? babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME : babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  106217. for (var _i = 0, _a = this.scene.lights; _i < _a.length; _i++) {
  106218. var light = _a[_i];
  106219. var generator = light.getShadowGenerator();
  106220. if (generator) {
  106221. var shadowMap = generator.getShadowMap();
  106222. if (shadowMap) {
  106223. shadowMap.refreshRate = refreshType;
  106224. }
  106225. }
  106226. }
  106227. this._processShadows = process;
  106228. },
  106229. enumerable: true,
  106230. configurable: true
  106231. });
  106232. /**
  106233. * Sets the engine flags to unlock all babylon features.
  106234. * Can also be configured using the scene.flags configuration object
  106235. */
  106236. SceneManager.prototype.unlockBabylonFeatures = function () {
  106237. this.scene.shadowsEnabled = true;
  106238. this.scene.particlesEnabled = true;
  106239. this.scene.postProcessesEnabled = true;
  106240. this.scene.collisionsEnabled = true;
  106241. this.scene.lightsEnabled = true;
  106242. this.scene.texturesEnabled = true;
  106243. this.scene.lensFlaresEnabled = true;
  106244. this.scene.proceduralTexturesEnabled = true;
  106245. this.scene.renderTargetsEnabled = true;
  106246. this.scene.spritesEnabled = true;
  106247. this.scene.skeletonsEnabled = true;
  106248. this.scene.audioEnabled = true;
  106249. };
  106250. /**
  106251. * initialize the environment for a specific model.
  106252. * Per default it will use the viewer's configuration.
  106253. * @param model the model to use to configure the environment.
  106254. * @returns a Promise that will resolve when the configuration is done.
  106255. */
  106256. SceneManager.prototype._initEnvironment = function (model) {
  106257. this._configureEnvironment(this._viewer.configuration.skybox, this._viewer.configuration.ground, model);
  106258. return Promise.resolve(this.scene);
  106259. };
  106260. /**
  106261. * initialize the scene. Calling this function again will dispose the old scene, if exists.
  106262. */
  106263. SceneManager.prototype.initScene = function (sceneConfiguration, optimizerConfiguration) {
  106264. if (sceneConfiguration === void 0) { sceneConfiguration = {}; }
  106265. // if the scen exists, dispose it.
  106266. if (this.scene) {
  106267. this.scene.dispose();
  106268. }
  106269. // create a new scene
  106270. this.scene = new babylonjs_1.Scene(this._viewer.engine);
  106271. // TODO - is this needed, now that Babylon is integrated?
  106272. // set a default PBR material
  106273. if (!sceneConfiguration.defaultMaterial) {
  106274. var defaultMaterial = new BABYLON.PBRMaterial('defaultMaterial', this.scene);
  106275. defaultMaterial.reflectivityColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  106276. defaultMaterial.microSurface = 0.6;
  106277. if (this.scene.defaultMaterial) {
  106278. this.scene.defaultMaterial.dispose();
  106279. }
  106280. this.scene.defaultMaterial = defaultMaterial;
  106281. }
  106282. this.scene.animationPropertiesOverride = new babylonjs_1.AnimationPropertiesOverride();
  106283. this.scene.animationPropertiesOverride.enableBlending = true;
  106284. babylonjs_1.Animation.AllowMatricesInterpolation = true;
  106285. this._mainColor = babylonjs_1.Color3.White();
  106286. if (sceneConfiguration.glow) {
  106287. var options = {
  106288. mainTextureFixedSize: 512
  106289. };
  106290. if (typeof sceneConfiguration.glow === 'object') {
  106291. options = sceneConfiguration.glow;
  106292. }
  106293. var gl = new BABYLON.GlowLayer("glow", this.scene, options);
  106294. }
  106295. return this.onSceneInitObservable.notifyObserversWithPromise(this.scene);
  106296. };
  106297. SceneManager.prototype.clearScene = function (clearModels, clearLights) {
  106298. if (clearModels === void 0) { clearModels = true; }
  106299. if (clearLights === void 0) { clearLights = false; }
  106300. if (clearModels) {
  106301. this.models.forEach(function (m) { return m.dispose(); });
  106302. this.models.length = 0;
  106303. }
  106304. if (clearLights) {
  106305. this.scene.lights.forEach(function (l) { return l.dispose(); });
  106306. }
  106307. };
  106308. /**
  106309. * This will update the scene's configuration, including camera, lights, environment.
  106310. * @param newConfiguration the delta that should be configured. This includes only the changes
  106311. * @param globalConfiguration The global configuration object, after the new configuration was merged into it
  106312. */
  106313. SceneManager.prototype.updateConfiguration = function (newConfiguration, globalConfiguration, model) {
  106314. var _this = this;
  106315. // update scene configuration
  106316. if (newConfiguration.scene) {
  106317. this._configureScene(newConfiguration.scene);
  106318. }
  106319. // optimizer
  106320. if (newConfiguration.optimizer) {
  106321. this._configureOptimizer(newConfiguration.optimizer);
  106322. }
  106323. // configure model
  106324. if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  106325. this._configureModel(newConfiguration.model);
  106326. }
  106327. // lights
  106328. this._configureLights(newConfiguration.lights, model);
  106329. // environment
  106330. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  106331. this._configureEnvironment(newConfiguration.skybox, newConfiguration.ground, model);
  106332. }
  106333. // camera
  106334. this._configureCamera(newConfiguration.camera, model);
  106335. if (newConfiguration.lab) {
  106336. if (newConfiguration.lab.environmentAssetsRootURL) {
  106337. this.labs.environmentAssetsRootURL = newConfiguration.lab.environmentAssetsRootURL;
  106338. }
  106339. if (newConfiguration.lab.environmentMap) {
  106340. var rot_1 = newConfiguration.lab.environmentMap.rotationY;
  106341. this.labs.loadEnvironment(newConfiguration.lab.environmentMap.texture, function () {
  106342. _this.labs.applyEnvironmentMapConfiguration(rot_1);
  106343. });
  106344. if (!newConfiguration.lab.environmentMap.texture && newConfiguration.lab.environmentMap.rotationY) {
  106345. this.labs.applyEnvironmentMapConfiguration(newConfiguration.lab.environmentMap.rotationY);
  106346. }
  106347. }
  106348. // rendering piplines
  106349. if (newConfiguration.lab.renderingPipelines) {
  106350. Object.keys(newConfiguration.lab.renderingPipelines).forEach((function (name) {
  106351. // disabled
  106352. if (!newConfiguration.lab.renderingPipelines[name]) {
  106353. if (_this._piplines[name]) {
  106354. _this._piplines[name].dispose();
  106355. delete _this._piplines[name];
  106356. }
  106357. }
  106358. else {
  106359. if (!_this._piplines[name]) {
  106360. var cameras = [_this.camera];
  106361. var ratio = newConfiguration.lab.renderingPipelines[name].ratio || 0.5;
  106362. switch (name) {
  106363. case 'default':
  106364. _this._piplines[name] = new babylonjs_1.DefaultRenderingPipeline('defaultPipeline', _this._hdrSupport, _this.scene, cameras);
  106365. break;
  106366. case 'standard':
  106367. _this._piplines[name] = new babylonjs_1.StandardRenderingPipeline('standardPipline', _this.scene, ratio, undefined, cameras);
  106368. break;
  106369. case 'ssao':
  106370. _this._piplines[name] = new babylonjs_1.SSAORenderingPipeline('ssao', _this.scene, ratio, cameras);
  106371. break;
  106372. case 'ssao2':
  106373. _this._piplines[name] = new babylonjs_1.SSAO2RenderingPipeline('ssao', _this.scene, ratio, cameras);
  106374. break;
  106375. }
  106376. }
  106377. // make sure it was generated
  106378. if (_this._piplines[name] && typeof newConfiguration.lab.renderingPipelines[name] !== 'boolean') {
  106379. helper_1.extendClassWithConfig(_this._piplines[name], newConfiguration.lab.renderingPipelines[name]);
  106380. }
  106381. }
  106382. }));
  106383. }
  106384. }
  106385. };
  106386. /**
  106387. * internally configure the scene using the provided configuration.
  106388. * The scene will not be recreated, but just updated.
  106389. * @param sceneConfig the (new) scene configuration
  106390. */
  106391. SceneManager.prototype._configureScene = function (sceneConfig) {
  106392. // sanity check!
  106393. if (!this.scene) {
  106394. return;
  106395. }
  106396. var cc = sceneConfig.clearColor || { r: 0.9, g: 0.9, b: 0.9, a: 1.0 };
  106397. var oldcc = this.scene.clearColor;
  106398. if (cc.r !== undefined) {
  106399. oldcc.r = cc.r;
  106400. }
  106401. if (cc.g !== undefined) {
  106402. oldcc.g = cc.g;
  106403. }
  106404. if (cc.b !== undefined) {
  106405. oldcc.b = cc.b;
  106406. }
  106407. if (cc.a !== undefined) {
  106408. oldcc.a = cc.a;
  106409. }
  106410. // image processing configuration - optional.
  106411. if (sceneConfig.imageProcessingConfiguration) {
  106412. helper_1.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  106413. }
  106414. //animation properties override
  106415. if (sceneConfig.animationPropertiesOverride) {
  106416. helper_1.extendClassWithConfig(this.scene.animationPropertiesOverride, sceneConfig.animationPropertiesOverride);
  106417. }
  106418. if (sceneConfig.environmentTexture) {
  106419. if (!(this.scene.environmentTexture && this.scene.environmentTexture.url === sceneConfig.environmentTexture)) {
  106420. if (this.scene.environmentTexture && this.scene.environmentTexture.dispose) {
  106421. this.scene.environmentTexture.dispose();
  106422. }
  106423. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  106424. this.scene.environmentTexture = environmentTexture;
  106425. }
  106426. }
  106427. if (sceneConfig.debug) {
  106428. this.scene.debugLayer.show();
  106429. }
  106430. else {
  106431. if (this.scene.debugLayer.isVisible()) {
  106432. this.scene.debugLayer.hide();
  106433. }
  106434. }
  106435. if (sceneConfig.disableHdr) {
  106436. this._handleHardwareLimitations(false);
  106437. }
  106438. else {
  106439. this._handleHardwareLimitations(true);
  106440. }
  106441. this._viewer.renderInBackground = !!sceneConfig.renderInBackground;
  106442. if (this.camera && sceneConfig.disableCameraControl) {
  106443. this.camera.detachControl(this._viewer.canvas);
  106444. }
  106445. else if (this.camera && sceneConfig.disableCameraControl === false) {
  106446. this.camera.attachControl(this._viewer.canvas);
  106447. }
  106448. // process mainColor changes:
  106449. if (sceneConfig.mainColor) {
  106450. this._mainColor = this._mainColor || babylonjs_1.Color3.White();
  106451. var mc = sceneConfig.mainColor;
  106452. if (mc.r !== undefined) {
  106453. this._mainColor.r = mc.r;
  106454. }
  106455. if (mc.g !== undefined) {
  106456. this._mainColor.g = mc.g;
  106457. }
  106458. if (mc.b !== undefined) {
  106459. this._mainColor.b = mc.b;
  106460. }
  106461. /*this._mainColor.toLinearSpaceToRef(this._mainColor);
  106462. let exposure = Math.pow(2.0, -((globalConfiguration.camera && globalConfiguration.camera.exposure) || 0.75)) * Math.PI;
  106463. this._mainColor.scaleToRef(1 / exposure, this._mainColor);
  106464. let environmentTint = (globalConfiguration.lab && globalConfiguration.lab.environmentMap && globalConfiguration.lab.environmentMap.tintLevel) || 0;
  106465. this._mainColor = Color3.Lerp(this._white, this._mainColor, environmentTint);*/
  106466. }
  106467. if (sceneConfig.defaultMaterial) {
  106468. var conf = sceneConfig.defaultMaterial;
  106469. if ((conf.materialType === 'standard' && this.scene.defaultMaterial.getClassName() !== 'StandardMaterial') ||
  106470. (conf.materialType === 'pbr' && this.scene.defaultMaterial.getClassName() !== 'PBRMaterial')) {
  106471. this.scene.defaultMaterial.dispose();
  106472. if (conf.materialType === 'standard') {
  106473. this.scene.defaultMaterial = new babylonjs_1.StandardMaterial("defaultMaterial", this.scene);
  106474. }
  106475. else {
  106476. this.scene.defaultMaterial = new babylonjs_1.PBRMaterial("defaultMaterial", this.scene);
  106477. }
  106478. }
  106479. helper_1.extendClassWithConfig(this.scene.defaultMaterial, conf);
  106480. }
  106481. if (sceneConfig.flags) {
  106482. helper_1.extendClassWithConfig(this.scene, sceneConfig.flags);
  106483. }
  106484. this.onSceneConfiguredObservable.notifyObservers({
  106485. sceneManager: this,
  106486. object: this.scene,
  106487. newConfiguration: sceneConfig
  106488. });
  106489. };
  106490. /**
  106491. * Configure the scene optimizer.
  106492. * The existing scene optimizer will be disposed and a new one will be created.
  106493. * @param optimizerConfig the (new) optimizer configuration
  106494. */
  106495. SceneManager.prototype._configureOptimizer = function (optimizerConfig) {
  106496. if (typeof optimizerConfig === 'boolean') {
  106497. if (this.sceneOptimizer) {
  106498. this.sceneOptimizer.stop();
  106499. this.sceneOptimizer.dispose();
  106500. delete this.sceneOptimizer;
  106501. }
  106502. if (optimizerConfig) {
  106503. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  106504. this.sceneOptimizer.start();
  106505. }
  106506. }
  106507. else {
  106508. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  106509. // check for degradation
  106510. if (optimizerConfig.degradation) {
  106511. switch (optimizerConfig.degradation) {
  106512. case "low":
  106513. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  106514. break;
  106515. case "moderate":
  106516. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  106517. break;
  106518. case "hight":
  106519. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  106520. break;
  106521. }
  106522. }
  106523. if (this.sceneOptimizer) {
  106524. this.sceneOptimizer.stop();
  106525. this.sceneOptimizer.dispose();
  106526. }
  106527. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  106528. this.sceneOptimizer.start();
  106529. }
  106530. this.onSceneOptimizerConfiguredObservable.notifyObservers({
  106531. sceneManager: this,
  106532. object: this.sceneOptimizer,
  106533. newConfiguration: optimizerConfig
  106534. });
  106535. };
  106536. /**
  106537. * configure all models using the configuration.
  106538. * @param modelConfiguration the configuration to use to reconfigure the models
  106539. */
  106540. SceneManager.prototype._configureModel = function (modelConfiguration) {
  106541. this.models.forEach(function (model) {
  106542. model.updateConfiguration(modelConfiguration);
  106543. });
  106544. this.onModelsConfiguredObservable.notifyObservers({
  106545. sceneManager: this,
  106546. object: this.models,
  106547. newConfiguration: modelConfiguration
  106548. });
  106549. };
  106550. /**
  106551. * (Re) configure the camera. The camera will only be created once and from this point will only be reconfigured.
  106552. * @param cameraConfig the new camera configuration
  106553. * @param model optionally use the model to configure the camera.
  106554. */
  106555. SceneManager.prototype._configureCamera = function (cameraConfig, model) {
  106556. var _this = this;
  106557. if (cameraConfig === void 0) { cameraConfig = {}; }
  106558. var focusMeshes = model ? model.meshes : this.scene.meshes;
  106559. if (!this.scene.activeCamera) {
  106560. var attachControl = true;
  106561. if (this._viewer.configuration.scene && this._viewer.configuration.scene.disableCameraControl) {
  106562. attachControl = false;
  106563. }
  106564. this.scene.createDefaultCamera(true, true, attachControl);
  106565. this.camera = this.scene.activeCamera;
  106566. this.camera.setTarget(babylonjs_1.Vector3.Zero());
  106567. }
  106568. if (cameraConfig.position) {
  106569. var newPosition = this.camera.position.clone();
  106570. helper_1.extendClassWithConfig(newPosition, cameraConfig.position);
  106571. this.camera.setPosition(newPosition);
  106572. }
  106573. if (cameraConfig.target) {
  106574. var newTarget = this.camera.target.clone();
  106575. helper_1.extendClassWithConfig(newTarget, cameraConfig.target);
  106576. this.camera.setTarget(newTarget);
  106577. }
  106578. else if (model && !cameraConfig.disableAutoFocus) {
  106579. var boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  106580. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  106581. var halfSizeVec = sizeVec.scale(0.5);
  106582. var center = boundingInfo.min.add(halfSizeVec);
  106583. this.camera.setTarget(center);
  106584. }
  106585. if (cameraConfig.rotation) {
  106586. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  106587. }
  106588. if (cameraConfig.behaviors) {
  106589. for (var name_1 in cameraConfig.behaviors) {
  106590. this._setCameraBehavior(cameraConfig.behaviors[name_1], focusMeshes);
  106591. }
  106592. }
  106593. ;
  106594. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  106595. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  106596. });
  106597. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  106598. var sceneDiagonalLenght = sceneDiagonal.length();
  106599. if (isFinite(sceneDiagonalLenght))
  106600. this.camera.upperRadiusLimit = sceneDiagonalLenght * 4;
  106601. helper_1.extendClassWithConfig(this.camera, cameraConfig);
  106602. this.onCameraConfiguredObservable.notifyObservers({
  106603. sceneManager: this,
  106604. object: this.camera,
  106605. newConfiguration: cameraConfig,
  106606. model: model
  106607. });
  106608. };
  106609. SceneManager.prototype._configureEnvironment = function (skyboxConifguration, groundConfiguration, model) {
  106610. if (!skyboxConifguration && !groundConfiguration) {
  106611. if (this.environmentHelper) {
  106612. this.environmentHelper.dispose();
  106613. delete this.environmentHelper;
  106614. }
  106615. ;
  106616. return Promise.resolve(this.scene);
  106617. }
  106618. var options = {
  106619. createGround: !!groundConfiguration,
  106620. createSkybox: !!skyboxConifguration,
  106621. setupImageProcessing: false,
  106622. };
  106623. if (model) {
  106624. var boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  106625. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  106626. var halfSizeVec = sizeVec.scale(0.5);
  106627. var center = boundingInfo.min.add(halfSizeVec);
  106628. options.groundYBias = -center.y;
  106629. }
  106630. if (groundConfiguration) {
  106631. var groundConfig_1 = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  106632. var groundSize = groundConfig_1.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  106633. if (groundSize) {
  106634. options.groundSize = groundSize;
  106635. }
  106636. options.enableGroundShadow = groundConfig_1 === true || groundConfig_1.receiveShadows;
  106637. if (groundConfig_1.shadowLevel !== undefined) {
  106638. options.groundShadowLevel = groundConfig_1.shadowLevel;
  106639. }
  106640. options.enableGroundMirror = !!groundConfig_1.mirror;
  106641. if (groundConfig_1.texture) {
  106642. options.groundTexture = groundConfig_1.texture;
  106643. }
  106644. if (groundConfig_1.color) {
  106645. options.groundColor = new babylonjs_1.Color3(groundConfig_1.color.r, groundConfig_1.color.g, groundConfig_1.color.b);
  106646. }
  106647. if (groundConfig_1.opacity !== undefined) {
  106648. options.groundOpacity = groundConfig_1.opacity;
  106649. }
  106650. if (groundConfig_1.mirror) {
  106651. options.enableGroundMirror = true;
  106652. // to prevent undefines
  106653. if (typeof groundConfig_1.mirror === "object") {
  106654. if (groundConfig_1.mirror.amount !== undefined)
  106655. options.groundMirrorAmount = groundConfig_1.mirror.amount;
  106656. if (groundConfig_1.mirror.sizeRatio !== undefined)
  106657. options.groundMirrorSizeRatio = groundConfig_1.mirror.sizeRatio;
  106658. if (groundConfig_1.mirror.blurKernel !== undefined)
  106659. options.groundMirrorBlurKernel = groundConfig_1.mirror.blurKernel;
  106660. if (groundConfig_1.mirror.fresnelWeight !== undefined)
  106661. options.groundMirrorFresnelWeight = groundConfig_1.mirror.fresnelWeight;
  106662. if (groundConfig_1.mirror.fallOffDistance !== undefined)
  106663. options.groundMirrorFallOffDistance = groundConfig_1.mirror.fallOffDistance;
  106664. if (this._defaultPipelineTextureType !== undefined)
  106665. options.groundMirrorTextureType = this._defaultPipelineTextureType;
  106666. }
  106667. }
  106668. }
  106669. var postInitSkyboxMaterial = false;
  106670. if (skyboxConifguration) {
  106671. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  106672. if (conf.material && conf.material.imageProcessingConfiguration) {
  106673. options.setupImageProcessing = false; // will be configured later manually.
  106674. }
  106675. var skyboxSize = conf.scale;
  106676. if (skyboxSize) {
  106677. options.skyboxSize = skyboxSize;
  106678. }
  106679. options.sizeAuto = !options.skyboxSize;
  106680. if (conf.color) {
  106681. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  106682. }
  106683. if (conf.cubeTexture && conf.cubeTexture.url) {
  106684. if (typeof conf.cubeTexture.url === "string") {
  106685. options.skyboxTexture = conf.cubeTexture.url;
  106686. }
  106687. else {
  106688. // init later!
  106689. postInitSkyboxMaterial = true;
  106690. }
  106691. }
  106692. if (conf.material && conf.material.imageProcessingConfiguration) {
  106693. postInitSkyboxMaterial = true;
  106694. }
  106695. }
  106696. options.setupImageProcessing = false; // TMP
  106697. if (!this.environmentHelper) {
  106698. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  106699. }
  106700. else {
  106701. // there might be a new scene! we need to dispose.
  106702. // get the scene used by the envHelper
  106703. var scene = this.environmentHelper.rootMesh.getScene();
  106704. // is it a different scene? Oh no!
  106705. if (scene !== this.scene) {
  106706. this.environmentHelper.dispose();
  106707. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  106708. }
  106709. else {
  106710. this.environmentHelper.updateOptions(options);
  106711. }
  106712. }
  106713. this.environmentHelper.setMainColor(this._mainColor || babylonjs_1.Color3.White());
  106714. if (this.environmentHelper.rootMesh && this._viewer.configuration.scene && this._viewer.configuration.scene.environmentRotationY !== undefined) {
  106715. this.environmentHelper.rootMesh.rotation.y = this._viewer.configuration.scene.environmentRotationY;
  106716. }
  106717. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  106718. if (this.environmentHelper.groundMaterial && groundConfig && groundConfig.material) {
  106719. if (!this.environmentHelper.groundMaterial._perceptualColor) {
  106720. this.environmentHelper.groundMaterial._perceptualColor = babylonjs_1.Color3.Black();
  106721. }
  106722. this.environmentHelper.groundMaterial._perceptualColor.copyFrom(this.mainColor);
  106723. // to be configured using the configuration object
  106724. /*this.environmentHelper.groundMaterial.primaryColorHighlightLevel = groundConfig.material.highlightLevel;
  106725. this.environmentHelper.groundMaterial.primaryColorShadowLevel = groundConfig.material.shadowLevel;
  106726. this.environmentHelper.groundMaterial.enableNoise = true;
  106727. if (this.environmentHelper.groundMaterial.diffuseTexture) {
  106728. this.environmentHelper.groundMaterial.diffuseTexture.gammaSpace = true;
  106729. }
  106730. this.environmentHelper.groundMaterial.useRGBColor = false;
  106731. this.environmentHelper.groundMaterial.maxSimultaneousLights = 1;*/
  106732. helper_1.extendClassWithConfig(this.environmentHelper.groundMaterial, groundConfig.material);
  106733. if (this.environmentHelper.groundMirror) {
  106734. var mirrorClearColor = this.environmentHelper.groundMaterial._perceptualColor.toLinearSpace();
  106735. //let exposure = Math.pow(2.0, -this.configuration.camera.exposure) * Math.PI;
  106736. //mirrorClearColor.scaleToRef(1 / exposure, mirrorClearColor);
  106737. // TODO use highlight if required
  106738. this.environmentHelper.groundMirror.clearColor.r = babylonjs_1.Scalar.Clamp(mirrorClearColor.r);
  106739. this.environmentHelper.groundMirror.clearColor.g = babylonjs_1.Scalar.Clamp(mirrorClearColor.g);
  106740. this.environmentHelper.groundMirror.clearColor.b = babylonjs_1.Scalar.Clamp(mirrorClearColor.b);
  106741. this.environmentHelper.groundMirror.clearColor.a = 1;
  106742. /*if (this.Scene.DisableReflection) {
  106743. this.environmentHelper.groundMaterial.reflectionTexture = null;
  106744. }*/
  106745. }
  106746. }
  106747. if (postInitSkyboxMaterial) {
  106748. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  106749. if (skyboxMaterial) {
  106750. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material) {
  106751. helper_1.extendClassWithConfig(skyboxMaterial, skyboxConifguration.material);
  106752. }
  106753. }
  106754. }
  106755. this.onEnvironmentConfiguredObservable.notifyObservers({
  106756. sceneManager: this,
  106757. object: this.environmentHelper,
  106758. newConfiguration: {
  106759. skybox: skyboxConifguration,
  106760. ground: groundConfiguration
  106761. },
  106762. model: model
  106763. });
  106764. };
  106765. /**
  106766. * configure the lights.
  106767. *
  106768. * @param lightsConfiguration the (new) light(s) configuration
  106769. * @param model optionally use the model to configure the camera.
  106770. */
  106771. SceneManager.prototype._configureLights = function (lightsConfiguration, model) {
  106772. var _this = this;
  106773. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  106774. // sanity check!
  106775. if (!Object.keys(lightsConfiguration).length) {
  106776. if (!this.scene.lights.length)
  106777. this.scene.createDefaultLight(true);
  106778. return;
  106779. }
  106780. ;
  106781. var lightsAvailable = this.scene.lights.map(function (light) { return light.name; });
  106782. // compare to the global (!) configuration object and dispose unneeded:
  106783. var lightsToConfigure = Object.keys(this._viewer.configuration.lights || []);
  106784. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  106785. lightsAvailable.forEach(function (lName) {
  106786. if (lightsToConfigure.indexOf(lName) === -1) {
  106787. _this.scene.getLightByName(lName).dispose();
  106788. }
  106789. });
  106790. }
  106791. Object.keys(lightsConfiguration).forEach(function (name, idx) {
  106792. var lightConfig = { type: 0 };
  106793. if (typeof lightsConfiguration[name] === 'object') {
  106794. lightConfig = lightsConfiguration[name];
  106795. }
  106796. lightConfig.name = name;
  106797. var light;
  106798. // light is not already available
  106799. if (lightsAvailable.indexOf(name) === -1) {
  106800. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  106801. if (!constructor)
  106802. return;
  106803. light = constructor();
  106804. }
  106805. else {
  106806. // available? get it from the scene
  106807. light = _this.scene.getLightByName(name);
  106808. lightsAvailable = lightsAvailable.filter(function (ln) { return ln !== name; });
  106809. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  106810. light.dispose();
  106811. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  106812. if (!constructor)
  106813. return;
  106814. light = constructor();
  106815. }
  106816. }
  106817. // if config set the light to false, dispose it.
  106818. if (lightsConfiguration[name] === false) {
  106819. light.dispose();
  106820. return;
  106821. }
  106822. //enabled
  106823. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  106824. light.setEnabled(enabled);
  106825. helper_1.extendClassWithConfig(light, lightConfig);
  106826. //position. Some lights don't support shadows
  106827. if (light instanceof babylonjs_1.ShadowLight) {
  106828. // set default values
  106829. light.shadowMinZ = light.shadowMinZ || 0.1;
  106830. light.shadowMaxZ = Math.min(20, light.shadowMaxZ || 20); //large far clips reduce shadow depth precision
  106831. if (lightConfig.target) {
  106832. if (light.setDirectionToTarget) {
  106833. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  106834. light.setDirectionToTarget(target);
  106835. }
  106836. }
  106837. else if (lightConfig.direction) {
  106838. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  106839. light.direction = direction;
  106840. }
  106841. var isShadowEnabled = false;
  106842. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  106843. light.shadowFrustumSize = lightConfig.shadowFrustumSize || 2;
  106844. isShadowEnabled = true;
  106845. }
  106846. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  106847. var spotLight = light;
  106848. if (lightConfig.spotAngle !== undefined) {
  106849. spotLight.angle = lightConfig.spotAngle * Math.PI / 180;
  106850. }
  106851. if (spotLight.angle && lightConfig.shadowFieldOfView) {
  106852. spotLight.shadowAngleScale = lightConfig.shadowFieldOfView / spotLight.angle;
  106853. }
  106854. isShadowEnabled = true;
  106855. }
  106856. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  106857. if (lightConfig.shadowFieldOfView) {
  106858. light.shadowAngle = lightConfig.shadowFieldOfView * Math.PI / 180;
  106859. }
  106860. isShadowEnabled = true;
  106861. }
  106862. var shadowGenerator = light.getShadowGenerator();
  106863. if (isShadowEnabled && lightConfig.shadowEnabled && _this._maxShadows) {
  106864. var bufferSize = lightConfig.shadowBufferSize || 256;
  106865. if (!shadowGenerator) {
  106866. shadowGenerator = new babylonjs_1.ShadowGenerator(bufferSize, light);
  106867. // TODO blur kernel definition
  106868. }
  106869. // add the focues meshes to the shadow list
  106870. _this._updateShadowRenderList(shadowGenerator, model);
  106871. var blurKernel = _this.getBlurKernel(light, bufferSize);
  106872. //shadowGenerator.useBlurCloseExponentialShadowMap = true;
  106873. //shadowGenerator.useKernelBlur = true;
  106874. //shadowGenerator.blurScale = 1.0;
  106875. shadowGenerator.bias = _this._shadowGeneratorBias;
  106876. shadowGenerator.blurKernel = blurKernel;
  106877. //shadowGenerator.depthScale = 50 * (light.shadowMaxZ - light.shadowMinZ);
  106878. //override defaults
  106879. helper_1.extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  106880. }
  106881. else if (shadowGenerator) {
  106882. shadowGenerator.dispose();
  106883. }
  106884. }
  106885. });
  106886. // render priority
  106887. var globalLightsConfiguration = this._viewer.configuration.lights || {};
  106888. Object.keys(globalLightsConfiguration).sort().forEach(function (name, idx) {
  106889. var configuration = globalLightsConfiguration[name];
  106890. var light = _this.scene.getLightByName(name);
  106891. // sanity check
  106892. if (!light)
  106893. return;
  106894. light.renderPriority = -idx;
  106895. });
  106896. this.onLightsConfiguredObservable.notifyObservers({
  106897. sceneManager: this,
  106898. object: this.scene.lights,
  106899. newConfiguration: lightsConfiguration,
  106900. model: model
  106901. });
  106902. };
  106903. SceneManager.prototype._updateShadowRenderList = function (shadowGenerator, model, resetList) {
  106904. var focusMeshes = model ? model.meshes : this.scene.meshes;
  106905. // add the focues meshes to the shadow list
  106906. var shadownMap = shadowGenerator.getShadowMap();
  106907. if (!shadownMap)
  106908. return;
  106909. if (resetList && shadownMap.renderList) {
  106910. shadownMap.renderList.length = 0;
  106911. }
  106912. else {
  106913. shadownMap.renderList = [];
  106914. }
  106915. for (var index = 0; index < focusMeshes.length; index++) {
  106916. var mesh = focusMeshes[index];
  106917. if (babylonjs_1.Tags.MatchesQuery(mesh, 'castShadow') && shadownMap.renderList.indexOf(mesh) === -1) {
  106918. shadownMap.renderList.push(mesh);
  106919. }
  106920. }
  106921. };
  106922. SceneManager.prototype._updateGroundMirrorRenderList = function (model, resetList) {
  106923. if (this.environmentHelper.groundMirror && this.environmentHelper.groundMirror.renderList) {
  106924. var focusMeshes = model ? model.meshes : this.scene.meshes;
  106925. var renderList = this.environmentHelper.groundMirror.renderList;
  106926. if (resetList) {
  106927. renderList.length = 0;
  106928. }
  106929. for (var index = 0; index < focusMeshes.length; index++) {
  106930. var mesh = focusMeshes[index];
  106931. if (renderList.indexOf(mesh) === -1) {
  106932. renderList.push(mesh);
  106933. }
  106934. }
  106935. }
  106936. };
  106937. /**
  106938. * Gets the shadow map blur kernel according to the light configuration.
  106939. * @param light The light used to generate the shadows
  106940. * @param bufferSize The size of the shadow map
  106941. * @return the kernel blur size
  106942. */
  106943. SceneManager.prototype.getBlurKernel = function (light, bufferSize) {
  106944. var normalizedBlurKernel = 0.05; // TODO Should come from the config.
  106945. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  106946. normalizedBlurKernel = normalizedBlurKernel / light.shadowFrustumSize;
  106947. }
  106948. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  106949. normalizedBlurKernel = normalizedBlurKernel / light.shadowAngle;
  106950. }
  106951. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  106952. normalizedBlurKernel = normalizedBlurKernel / (light.angle * light.shadowAngleScale);
  106953. }
  106954. var minimumBlurKernel = 5 / (bufferSize / 256); //magic number that aims to keep away sawtooth shadows
  106955. var blurKernel = Math.max(bufferSize * normalizedBlurKernel, minimumBlurKernel);
  106956. return blurKernel;
  106957. };
  106958. /**
  106959. * Alters render settings to reduce features based on hardware feature limitations
  106960. * @param enableHDR Allows the viewer to run in HDR mode.
  106961. */
  106962. SceneManager.prototype._handleHardwareLimitations = function (enableHDR) {
  106963. if (enableHDR === void 0) { enableHDR = true; }
  106964. //flip rendering settings switches based on hardware support
  106965. var maxVaryingRows = this._viewer.engine.getCaps().maxVaryingVectors;
  106966. var maxFragmentSamplers = this._viewer.engine.getCaps().maxTexturesImageUnits;
  106967. //shadows are disabled if there's not enough varyings for a single shadow
  106968. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  106969. this._maxShadows = 0;
  106970. }
  106971. else {
  106972. this._maxShadows = 3;
  106973. }
  106974. //can we render to any >= 16-bit targets (required for HDR)
  106975. var caps = this._viewer.engine.getCaps();
  106976. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  106977. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  106978. this._hdrSupport = enableHDR && !!(linearFloatTargets || linearHalfFloatTargets);
  106979. if (linearHalfFloatTargets) {
  106980. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  106981. this._shadowGeneratorBias = 0.002;
  106982. }
  106983. else if (linearFloatTargets) {
  106984. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  106985. this._shadowGeneratorBias = 0.001;
  106986. }
  106987. else {
  106988. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  106989. this._shadowGeneratorBias = 0.001;
  106990. }
  106991. this._defaultPipelineTextureType = this._hdrSupport ? this._defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  106992. };
  106993. /**
  106994. * Dispoe the entire viewer including the scene and the engine
  106995. */
  106996. SceneManager.prototype.dispose = function () {
  106997. // this.onCameraConfiguredObservable.clear();
  106998. this.onEnvironmentConfiguredObservable.clear();
  106999. this.onLightsConfiguredObservable.clear();
  107000. this.onModelsConfiguredObservable.clear();
  107001. this.onSceneConfiguredObservable.clear();
  107002. this.onSceneInitObservable.clear();
  107003. this.onSceneOptimizerConfiguredObservable.clear();
  107004. if (this.sceneOptimizer) {
  107005. this.sceneOptimizer.stop();
  107006. this.sceneOptimizer.dispose();
  107007. }
  107008. if (this.environmentHelper) {
  107009. this.environmentHelper.dispose();
  107010. }
  107011. this.models.forEach(function (model) {
  107012. model.dispose();
  107013. });
  107014. this.models.length = 0;
  107015. this.scene.dispose();
  107016. };
  107017. SceneManager.prototype._setCameraBehavior = function (behaviorConfig, payload) {
  107018. var behavior;
  107019. var type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  107020. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  107021. // constructing behavior
  107022. switch (type) {
  107023. case 0 /* AUTOROTATION */:
  107024. this.camera.useAutoRotationBehavior = true;
  107025. behavior = this.camera.autoRotationBehavior;
  107026. break;
  107027. case 1 /* BOUNCING */:
  107028. this.camera.useBouncingBehavior = true;
  107029. behavior = this.camera.bouncingBehavior;
  107030. break;
  107031. case 2 /* FRAMING */:
  107032. this.camera.useFramingBehavior = true;
  107033. behavior = this.camera.framingBehavior;
  107034. break;
  107035. default:
  107036. behavior = null;
  107037. break;
  107038. }
  107039. if (behavior) {
  107040. if (typeof behaviorConfig === "object") {
  107041. helper_1.extendClassWithConfig(behavior, behaviorConfig);
  107042. }
  107043. }
  107044. // post attach configuration. Some functionalities require the attached camera.
  107045. switch (type) {
  107046. case 0 /* AUTOROTATION */:
  107047. break;
  107048. case 1 /* BOUNCING */:
  107049. break;
  107050. case 2 /* FRAMING */:
  107051. if (config.zoomOnBoundingInfo) {
  107052. //payload is an array of meshes
  107053. var meshes = payload;
  107054. var bounding = meshes[0].getHierarchyBoundingVectors();
  107055. behavior.zoomOnBoundingInfo(bounding.min, bounding.max);
  107056. }
  107057. break;
  107058. }
  107059. };
  107060. return SceneManager;
  107061. }());
  107062. exports.SceneManager = SceneManager;
  107063. /***/ }),
  107064. /* 28 */
  107065. /***/ (function(module, exports, __webpack_require__) {
  107066. "use strict";
  107067. Object.defineProperty(exports, "__esModule", { value: true });
  107068. var environmentSerializer_1 = __webpack_require__(29);
  107069. var babylonjs_1 = __webpack_require__(0);
  107070. var texture_1 = __webpack_require__(10);
  107071. var ViewerLabs = /** @class */ (function () {
  107072. function ViewerLabs(_sceneManager) {
  107073. this._sceneManager = _sceneManager;
  107074. this.environment = {
  107075. //irradiance
  107076. irradiancePolynomialCoefficients: {
  107077. x: new BABYLON.Vector3(0, 0, 0),
  107078. y: new BABYLON.Vector3(0, 0, 0),
  107079. z: new BABYLON.Vector3(0, 0, 0),
  107080. xx: new BABYLON.Vector3(0, 0, 0),
  107081. yy: new BABYLON.Vector3(0, 0, 0),
  107082. zz: new BABYLON.Vector3(0, 0, 0),
  107083. yz: new BABYLON.Vector3(0, 0, 0),
  107084. zx: new BABYLON.Vector3(0, 0, 0),
  107085. xy: new BABYLON.Vector3(0, 0, 0)
  107086. },
  107087. textureIntensityScale: 1.0
  107088. };
  107089. }
  107090. ViewerLabs.prototype.loadEnvironment = function (data, onSuccess, onProgress, onError) {
  107091. var _this = this;
  107092. //@! todo: should loadEnvironment cancel any currently loading environments?
  107093. if (data instanceof ArrayBuffer) {
  107094. this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(data);
  107095. if (onSuccess)
  107096. onSuccess(this.environment);
  107097. }
  107098. else if (typeof data === 'string') {
  107099. var url = this.getEnvironmentAssetUrl(data);
  107100. this._sceneManager.scene._loadFile(url, function (arrayBuffer) {
  107101. _this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(arrayBuffer);
  107102. if (onSuccess)
  107103. onSuccess(_this.environment);
  107104. }, function (progressEvent) { if (onProgress)
  107105. onProgress(progressEvent.loaded, progressEvent.total); }, false, true, function (r, e) {
  107106. if (onError) {
  107107. onError(e);
  107108. }
  107109. });
  107110. }
  107111. else {
  107112. //data assumed to be PBREnvironment object
  107113. this.environment = data;
  107114. if (onSuccess)
  107115. onSuccess(data);
  107116. }
  107117. };
  107118. /**
  107119. * Applies an `EnvironmentMapConfiguration` to the scene
  107120. * @param environmentMapConfiguration Environment map configuration to apply
  107121. */
  107122. ViewerLabs.prototype.applyEnvironmentMapConfiguration = function (rotationY) {
  107123. if (!this.environment)
  107124. return;
  107125. //set orientation
  107126. var rotatquatRotationionY = babylonjs_1.Quaternion.RotationAxis(BABYLON.Axis.Y, rotationY || 0);
  107127. // Add env texture to the scene.
  107128. if (this.environment.specularTexture) {
  107129. // IE crashes when disposing the old texture and setting a new one
  107130. if (!this._sceneManager.scene.environmentTexture) {
  107131. this._sceneManager.scene.environmentTexture = texture_1.TextureUtils.GetBabylonCubeTexture(this._sceneManager.scene, this.environment.specularTexture, false, true);
  107132. }
  107133. if (this._sceneManager.scene.environmentTexture) {
  107134. this._sceneManager.scene.environmentTexture.level = this.environment.textureIntensityScale;
  107135. this._sceneManager.scene.environmentTexture.invertZ = true;
  107136. this._sceneManager.scene.environmentTexture.lodLevelInAlpha = true;
  107137. var poly = this._sceneManager.scene.environmentTexture.sphericalPolynomial || new BABYLON.SphericalPolynomial();
  107138. poly.x = this.environment.irradiancePolynomialCoefficients.x;
  107139. poly.y = this.environment.irradiancePolynomialCoefficients.y;
  107140. poly.z = this.environment.irradiancePolynomialCoefficients.z;
  107141. poly.xx = this.environment.irradiancePolynomialCoefficients.xx;
  107142. poly.xy = this.environment.irradiancePolynomialCoefficients.xy;
  107143. poly.yy = this.environment.irradiancePolynomialCoefficients.yy;
  107144. poly.yz = this.environment.irradiancePolynomialCoefficients.yz;
  107145. poly.zx = this.environment.irradiancePolynomialCoefficients.zx;
  107146. poly.zz = this.environment.irradiancePolynomialCoefficients.zz;
  107147. this._sceneManager.scene.environmentTexture.sphericalPolynomial = poly;
  107148. //set orientation
  107149. BABYLON.Matrix.FromQuaternionToRef(rotatquatRotationionY, this._sceneManager.scene.environmentTexture.getReflectionTextureMatrix());
  107150. }
  107151. }
  107152. };
  107153. /**
  107154. * Get an environment asset url by using the configuration if the path is not absolute.
  107155. * @param url Asset url
  107156. * @returns The Asset url using the `environmentAssetsRootURL` if the url is not an absolute path.
  107157. */
  107158. ViewerLabs.prototype.getEnvironmentAssetUrl = function (url) {
  107159. var returnUrl = url;
  107160. if (url && url.toLowerCase().indexOf("//") === -1) {
  107161. if (!this.environmentAssetsRootURL) {
  107162. babylonjs_1.Tools.Warn("Please, specify the root url of your assets before loading the configuration (labs.environmentAssetsRootURL) or disable the background through the viewer options.");
  107163. return url;
  107164. }
  107165. returnUrl = this.environmentAssetsRootURL + returnUrl;
  107166. }
  107167. return returnUrl;
  107168. };
  107169. return ViewerLabs;
  107170. }());
  107171. exports.ViewerLabs = ViewerLabs;
  107172. /***/ }),
  107173. /* 29 */
  107174. /***/ (function(module, exports, __webpack_require__) {
  107175. "use strict";
  107176. Object.defineProperty(exports, "__esModule", { value: true });
  107177. var babylonjs_1 = __webpack_require__(0);
  107178. var texture_1 = __webpack_require__(10);
  107179. /**
  107180. * A static class proving methods to aid parsing Spectre environment files
  107181. */
  107182. var EnvironmentDeserializer = /** @class */ (function () {
  107183. function EnvironmentDeserializer() {
  107184. }
  107185. /**
  107186. * Parses an arraybuffer into a new PBREnvironment object
  107187. * @param arrayBuffer The arraybuffer of the Spectre environment file
  107188. * @return a PBREnvironment object
  107189. */
  107190. EnvironmentDeserializer.Parse = function (arrayBuffer) {
  107191. var environment = {
  107192. //irradiance
  107193. irradiancePolynomialCoefficients: {
  107194. x: new babylonjs_1.Vector3(0, 0, 0),
  107195. y: new babylonjs_1.Vector3(0, 0, 0),
  107196. z: new babylonjs_1.Vector3(0, 0, 0),
  107197. xx: new babylonjs_1.Vector3(0, 0, 0),
  107198. yy: new babylonjs_1.Vector3(0, 0, 0),
  107199. zz: new babylonjs_1.Vector3(0, 0, 0),
  107200. yz: new babylonjs_1.Vector3(0, 0, 0),
  107201. zx: new babylonjs_1.Vector3(0, 0, 0),
  107202. xy: new babylonjs_1.Vector3(0, 0, 0)
  107203. },
  107204. //specular
  107205. textureIntensityScale: 1.0,
  107206. };
  107207. //read .env
  107208. var littleEndian = false;
  107209. var magicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  107210. var dataView = new DataView(arrayBuffer);
  107211. var pos = 0;
  107212. for (var i = 0; i < magicBytes.length; i++) {
  107213. if (dataView.getUint8(pos++) !== magicBytes[i]) {
  107214. babylonjs_1.Tools.Error('Not a Spectre environment map');
  107215. }
  107216. }
  107217. var version = dataView.getUint16(pos, littleEndian);
  107218. pos += 2;
  107219. if (version !== 1) {
  107220. babylonjs_1.Tools.Warn('Unsupported Spectre environment map version "' + version + '"');
  107221. }
  107222. //read json descriptor - collect characters up to null terminator
  107223. var descriptorString = '';
  107224. var charCode = 0x00;
  107225. while ((charCode = dataView.getUint8(pos++))) {
  107226. descriptorString += String.fromCharCode(charCode);
  107227. }
  107228. var descriptor = JSON.parse(descriptorString);
  107229. var payloadPos = pos;
  107230. //irradiance
  107231. switch (descriptor.irradiance.type) {
  107232. case 'irradiance_sh_coefficients_9':
  107233. //irradiance
  107234. var harmonics = descriptor.irradiance;
  107235. EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance(harmonics);
  107236. //harmonics now represent radiance
  107237. EnvironmentDeserializer._ConvertSHToSP(harmonics, environment.irradiancePolynomialCoefficients);
  107238. break;
  107239. default:
  107240. babylonjs_1.Tools.Error('Unhandled MapType descriptor.irradiance.type (' + descriptor.irradiance.type + ')');
  107241. }
  107242. //specular
  107243. switch (descriptor.specular.type) {
  107244. case 'cubemap_faces':
  107245. var specularDescriptor = descriptor.specular;
  107246. var specularTexture = environment.specularTexture = new texture_1.TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */);
  107247. environment.textureIntensityScale = specularDescriptor.multiplier != null ? specularDescriptor.multiplier : 1.0;
  107248. var mipmaps = specularDescriptor.mipmaps;
  107249. var imageType = specularDescriptor.imageType;
  107250. for (var l = 0; l < mipmaps.length; l++) {
  107251. var faceRanges = mipmaps[l];
  107252. specularTexture.source[l] = [];
  107253. for (var i = 0; i < 6; i++) {
  107254. var range = faceRanges[i];
  107255. var bytes = new Uint8Array(arrayBuffer, payloadPos + range.pos, range.length);
  107256. switch (imageType) {
  107257. case 'png':
  107258. //construct image element from bytes
  107259. var image = new Image();
  107260. var src = URL.createObjectURL(new Blob([bytes], { type: 'image/png' }));
  107261. image.src = src;
  107262. specularTexture.source[l][i] = image;
  107263. break;
  107264. default:
  107265. babylonjs_1.Tools.Error('Unhandled ImageType descriptor.specular.imageType (' + imageType + ')');
  107266. }
  107267. }
  107268. }
  107269. break;
  107270. default:
  107271. babylonjs_1.Tools.Error('Unhandled MapType descriptor.specular.type (' + descriptor.specular.type + ')');
  107272. }
  107273. return environment;
  107274. };
  107275. /**
  107276. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  107277. * L = (1/pi) * E * rho
  107278. *
  107279. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  107280. * @param harmonics Spherical harmonic coefficients (9)
  107281. */
  107282. EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  107283. EnvironmentDeserializer._ScaleSH(harmonics, 1 / Math.PI);
  107284. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  107285. // (The pixel shader must apply albedo after texture fetches, etc).
  107286. };
  107287. /**
  107288. * Convert spherical harmonics to spherical polynomial coefficients
  107289. * @param harmonics Spherical harmonic coefficients (9)
  107290. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  107291. */
  107292. EnvironmentDeserializer._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  107293. var rPi = 1 / Math.PI;
  107294. //x
  107295. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  107296. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  107297. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  107298. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  107299. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  107300. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  107301. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  107302. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  107303. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  107304. //xx
  107305. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  107306. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  107307. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  107308. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  107309. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  107310. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  107311. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  107312. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  107313. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  107314. //yz
  107315. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  107316. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  107317. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  107318. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  107319. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  107320. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  107321. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  107322. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  107323. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  107324. };
  107325. /**
  107326. * Multiplies harmonic coefficients in place
  107327. * @param harmonics Spherical harmonic coefficients (9)
  107328. * @param scaleFactor Value to multiply by
  107329. */
  107330. EnvironmentDeserializer._ScaleSH = function (harmonics, scaleFactor) {
  107331. harmonics.l00[0] *= scaleFactor;
  107332. harmonics.l00[1] *= scaleFactor;
  107333. harmonics.l00[2] *= scaleFactor;
  107334. harmonics.l1_1[0] *= scaleFactor;
  107335. harmonics.l1_1[1] *= scaleFactor;
  107336. harmonics.l1_1[2] *= scaleFactor;
  107337. harmonics.l10[0] *= scaleFactor;
  107338. harmonics.l10[1] *= scaleFactor;
  107339. harmonics.l10[2] *= scaleFactor;
  107340. harmonics.l11[0] *= scaleFactor;
  107341. harmonics.l11[1] *= scaleFactor;
  107342. harmonics.l11[2] *= scaleFactor;
  107343. harmonics.l2_2[0] *= scaleFactor;
  107344. harmonics.l2_2[1] *= scaleFactor;
  107345. harmonics.l2_2[2] *= scaleFactor;
  107346. harmonics.l2_1[0] *= scaleFactor;
  107347. harmonics.l2_1[1] *= scaleFactor;
  107348. harmonics.l2_1[2] *= scaleFactor;
  107349. harmonics.l20[0] *= scaleFactor;
  107350. harmonics.l20[1] *= scaleFactor;
  107351. harmonics.l20[2] *= scaleFactor;
  107352. harmonics.l21[0] *= scaleFactor;
  107353. harmonics.l21[1] *= scaleFactor;
  107354. harmonics.l21[2] *= scaleFactor;
  107355. harmonics.l22[0] *= scaleFactor;
  107356. harmonics.l22[1] *= scaleFactor;
  107357. harmonics.l22[2] *= scaleFactor;
  107358. };
  107359. return EnvironmentDeserializer;
  107360. }());
  107361. exports.EnvironmentDeserializer = EnvironmentDeserializer;
  107362. /***/ }),
  107363. /* 30 */
  107364. /***/ (function(module, exports, __webpack_require__) {
  107365. "use strict";
  107366. Object.defineProperty(exports, "__esModule", { value: true });
  107367. var babylonjs_1 = __webpack_require__(0);
  107368. var helper_1 = __webpack_require__(2);
  107369. var deepmerge = __webpack_require__(1);
  107370. /**
  107371. * The template manager, a member of the viewer class, will manage the viewer's templates and generate the HTML.
  107372. * The template manager managers a single viewer and can be seen as the collection of all sub-templates of the viewer.
  107373. */
  107374. var TemplateManager = /** @class */ (function () {
  107375. function TemplateManager(containerElement) {
  107376. this.containerElement = containerElement;
  107377. this.templates = {};
  107378. this.onTemplateInit = new babylonjs_1.Observable();
  107379. this.onTemplateLoaded = new babylonjs_1.Observable();
  107380. this.onTemplateStateChange = new babylonjs_1.Observable();
  107381. this.onAllLoaded = new babylonjs_1.Observable();
  107382. this.onEventTriggered = new babylonjs_1.Observable();
  107383. this.eventManager = new eventManager_1.EventManager(this);
  107384. }
  107385. /**
  107386. * Initialize the template(s) for the viewer. Called bay the Viewer class
  107387. * @param templates the templates to be used to initialize the main template
  107388. */
  107389. TemplateManager.prototype.initTemplate = function (templates) {
  107390. var _this = this;
  107391. var internalInit = function (dependencyMap, name, parentTemplate) {
  107392. //init template
  107393. var template = _this.templates[name];
  107394. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  107395. return internalInit(dependencyMap[childName], childName, template);
  107396. });
  107397. // register the observers
  107398. //template.onLoaded.add(() => {
  107399. var addToParent = function () {
  107400. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  107401. template.appendTo(containingElement);
  107402. _this._checkLoadedState();
  107403. };
  107404. if (parentTemplate && !parentTemplate.parent) {
  107405. parentTemplate.onAppended.add(function () {
  107406. addToParent();
  107407. });
  107408. }
  107409. else {
  107410. addToParent();
  107411. }
  107412. //});
  107413. return template;
  107414. };
  107415. //build the html tree
  107416. return this._buildHTMLTree(templates).then(function (htmlTree) {
  107417. if (_this.templates['main']) {
  107418. internalInit(htmlTree, 'main');
  107419. }
  107420. else {
  107421. _this._checkLoadedState();
  107422. }
  107423. return;
  107424. });
  107425. };
  107426. /**
  107427. *
  107428. * This function will create a simple map with child-dependencies of the template html tree.
  107429. * It will compile each template, check if its children exist in the configuration and will add them if they do.
  107430. * It is expected that the main template will be called main!
  107431. *
  107432. * @param templates
  107433. */
  107434. TemplateManager.prototype._buildHTMLTree = function (templates) {
  107435. var _this = this;
  107436. var promises = Object.keys(templates).map(function (name) {
  107437. // if the template was overridden
  107438. if (!templates[name])
  107439. return Promise.resolve(false);
  107440. // else - we have a template, let's do our job!
  107441. var template = new Template(name, templates[name]);
  107442. template.onLoaded.add(function () {
  107443. _this.onTemplateLoaded.notifyObservers(template);
  107444. });
  107445. template.onStateChange.add(function () {
  107446. _this.onTemplateStateChange.notifyObservers(template);
  107447. });
  107448. _this.onTemplateInit.notifyObservers(template);
  107449. // make sure the global onEventTriggered is called as well
  107450. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  107451. _this.templates[name] = template;
  107452. return template.initPromise;
  107453. });
  107454. return Promise.all(promises).then(function () {
  107455. var templateStructure = {};
  107456. // now iterate through all templates and check for children:
  107457. var buildTree = function (parentObject, name) {
  107458. _this.templates[name].isInHtmlTree = true;
  107459. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  107460. childNodes.forEach(function (element) {
  107461. parentObject[element] = {};
  107462. buildTree(parentObject[element], element);
  107463. });
  107464. };
  107465. if (_this.templates['main']) {
  107466. buildTree(templateStructure, "main");
  107467. }
  107468. return templateStructure;
  107469. });
  107470. };
  107471. /**
  107472. * Get the canvas in the template tree.
  107473. * There must be one and only one canvas inthe template.
  107474. */
  107475. TemplateManager.prototype.getCanvas = function () {
  107476. return this.containerElement.querySelector('canvas');
  107477. };
  107478. /**
  107479. * Get a specific template from the template tree
  107480. * @param name the name of the template to load
  107481. */
  107482. TemplateManager.prototype.getTemplate = function (name) {
  107483. return this.templates[name];
  107484. };
  107485. TemplateManager.prototype._checkLoadedState = function () {
  107486. var _this = this;
  107487. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  107488. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  107489. });
  107490. if (done) {
  107491. this.onAllLoaded.notifyObservers(this);
  107492. }
  107493. };
  107494. /**
  107495. * Dispose the template manager
  107496. */
  107497. TemplateManager.prototype.dispose = function () {
  107498. var _this = this;
  107499. // dispose all templates
  107500. Object.keys(this.templates).forEach(function (template) {
  107501. _this.templates[template].dispose();
  107502. });
  107503. this.templates = {};
  107504. this.eventManager.dispose();
  107505. this.onTemplateInit.clear();
  107506. this.onAllLoaded.clear();
  107507. this.onEventTriggered.clear();
  107508. this.onTemplateLoaded.clear();
  107509. this.onTemplateStateChange.clear();
  107510. };
  107511. return TemplateManager;
  107512. }());
  107513. exports.TemplateManager = TemplateManager;
  107514. var Handlebars = __webpack_require__(31);
  107515. var eventManager_1 = __webpack_require__(32);
  107516. // register a new helper. modified https://stackoverflow.com/questions/9838925/is-there-any-method-to-iterate-a-map-with-handlebars-js
  107517. Handlebars.registerHelper('eachInMap', function (map, block) {
  107518. var out = '';
  107519. Object.keys(map).map(function (prop) {
  107520. var data = map[prop];
  107521. if (typeof data === 'object') {
  107522. data.id = data.id || prop;
  107523. out += block.fn(data);
  107524. }
  107525. else {
  107526. out += block.fn({ id: prop, value: data });
  107527. }
  107528. });
  107529. return out;
  107530. });
  107531. /**
  107532. * This class represents a single template in the viewer's template tree.
  107533. * An example for a template is a single canvas, an overlay (containing sub-templates) or the navigation bar.
  107534. * A template is injected using the template manager in the correct position.
  107535. * The template is rendered using Handlebars and can use Handlebars' features (such as parameter injection)
  107536. *
  107537. * For further information please refer to the documentation page, https://doc.babylonjs.com
  107538. */
  107539. var Template = /** @class */ (function () {
  107540. function Template(name, _configuration) {
  107541. var _this = this;
  107542. this.name = name;
  107543. this._configuration = _configuration;
  107544. this.onLoaded = new babylonjs_1.Observable();
  107545. this.onAppended = new babylonjs_1.Observable();
  107546. this.onStateChange = new babylonjs_1.Observable();
  107547. this.onEventTriggered = new babylonjs_1.Observable();
  107548. this.loadRequests = [];
  107549. this.isLoaded = false;
  107550. this.isShown = false;
  107551. this.isInHtmlTree = false;
  107552. var htmlContentPromise = this._getTemplateAsHtml(_configuration);
  107553. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  107554. if (htmlTemplate) {
  107555. _this._htmlTemplate = htmlTemplate;
  107556. var compiledTemplate = Handlebars.compile(htmlTemplate);
  107557. var config = _this._configuration.params || {};
  107558. _this._rawHtml = compiledTemplate(config);
  107559. try {
  107560. _this._fragment = document.createRange().createContextualFragment(_this._rawHtml);
  107561. }
  107562. catch (e) {
  107563. var test = document.createElement(_this.name);
  107564. test.innerHTML = _this._rawHtml;
  107565. _this._fragment = test;
  107566. }
  107567. _this.isLoaded = true;
  107568. _this.isShown = true;
  107569. _this.onLoaded.notifyObservers(_this);
  107570. }
  107571. return _this;
  107572. });
  107573. }
  107574. /**
  107575. * Some templates have parameters (like background color for example).
  107576. * The parameters are provided to Handlebars which in turn generates the template.
  107577. * This function will update the template with the new parameters
  107578. *
  107579. * @param params the new template parameters
  107580. */
  107581. Template.prototype.updateParams = function (params, append) {
  107582. if (append === void 0) { append = true; }
  107583. if (append) {
  107584. this._configuration.params = deepmerge(this._configuration.params, params);
  107585. }
  107586. else {
  107587. this._configuration.params = params;
  107588. }
  107589. // update the template
  107590. if (this.isLoaded) {
  107591. // this.dispose();
  107592. }
  107593. var compiledTemplate = Handlebars.compile(this._htmlTemplate);
  107594. var config = this._configuration.params || {};
  107595. this._rawHtml = compiledTemplate(config);
  107596. try {
  107597. this._fragment = document.createRange().createContextualFragment(this._rawHtml);
  107598. }
  107599. catch (e) {
  107600. var test = document.createElement(this.name);
  107601. test.innerHTML = this._rawHtml;
  107602. this._fragment = test;
  107603. }
  107604. if (this.parent) {
  107605. this.appendTo(this.parent, true);
  107606. }
  107607. };
  107608. Object.defineProperty(Template.prototype, "configuration", {
  107609. /**
  107610. * Get the template'S configuration
  107611. */
  107612. get: function () {
  107613. return this._configuration;
  107614. },
  107615. enumerable: true,
  107616. configurable: true
  107617. });
  107618. /**
  107619. * A template can be a parent element for other templates or HTML elements.
  107620. * This function will deliver all child HTML elements of this template.
  107621. */
  107622. Template.prototype.getChildElements = function () {
  107623. var childrenArray = [];
  107624. //Edge and IE don't support frage,ent.children
  107625. var children = this._fragment && this._fragment.children;
  107626. if (!this._fragment) {
  107627. var fragment = this.parent.querySelector(this.name);
  107628. if (fragment) {
  107629. children = fragment.querySelectorAll('*');
  107630. }
  107631. }
  107632. if (!children) {
  107633. // casting to HTMLCollection, as both NodeListOf and HTMLCollection have 'item()' and 'length'.
  107634. children = this._fragment.querySelectorAll('*');
  107635. }
  107636. for (var i = 0; i < children.length; ++i) {
  107637. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  107638. }
  107639. return childrenArray;
  107640. };
  107641. /**
  107642. * Appending the template to a parent HTML element.
  107643. * If a parent is already set and you wish to replace the old HTML with new one, forceRemove should be true.
  107644. * @param parent the parent to which the template is added
  107645. * @param forceRemove if the parent already exists, shoud the template be removed from it?
  107646. */
  107647. Template.prototype.appendTo = function (parent, forceRemove) {
  107648. var _this = this;
  107649. if (this.parent) {
  107650. if (forceRemove && this._addedFragment) {
  107651. /*let fragement = this.parent.querySelector(this.name)
  107652. if (fragement)
  107653. this.parent.removeChild(fragement);*/
  107654. this.parent.innerHTML = '';
  107655. }
  107656. else {
  107657. return;
  107658. }
  107659. }
  107660. this.parent = parent;
  107661. if (this._configuration.id) {
  107662. this.parent.id = this._configuration.id;
  107663. }
  107664. if (this._fragment) {
  107665. this.parent.appendChild(this._fragment);
  107666. this._addedFragment = this._fragment;
  107667. }
  107668. else {
  107669. this.parent.insertAdjacentHTML("beforeend", this._rawHtml);
  107670. }
  107671. // appended only one frame after.
  107672. setTimeout(function () {
  107673. _this._registerEvents();
  107674. _this.onAppended.notifyObservers(_this);
  107675. });
  107676. };
  107677. /**
  107678. * Show the template using the provided visibilityFunction, or natively using display: flex.
  107679. * The provided function returns a promise that should be fullfilled when the element is shown.
  107680. * Since it is a promise async operations are more than possible.
  107681. * See the default viewer for an opacity example.
  107682. * @param visibilityFunction The function to execute to show the template.
  107683. */
  107684. Template.prototype.show = function (visibilityFunction) {
  107685. var _this = this;
  107686. if (this._isHiding)
  107687. return Promise.resolve(this);
  107688. return Promise.resolve().then(function () {
  107689. _this._isShowing = true;
  107690. if (visibilityFunction) {
  107691. return visibilityFunction(_this);
  107692. }
  107693. else {
  107694. // flex? box? should this be configurable easier than the visibilityFunction?
  107695. _this.parent.style.display = 'flex';
  107696. // support old browsers with no flex:
  107697. if (_this.parent.style.display !== 'flex') {
  107698. _this.parent.style.display = '';
  107699. }
  107700. return _this;
  107701. }
  107702. }).then(function () {
  107703. _this.isShown = true;
  107704. _this._isShowing = false;
  107705. _this.onStateChange.notifyObservers(_this);
  107706. return _this;
  107707. });
  107708. };
  107709. /**
  107710. * Hide the template using the provided visibilityFunction, or natively using display: none.
  107711. * The provided function returns a promise that should be fullfilled when the element is hidden.
  107712. * Since it is a promise async operations are more than possible.
  107713. * See the default viewer for an opacity example.
  107714. * @param visibilityFunction The function to execute to show the template.
  107715. */
  107716. Template.prototype.hide = function (visibilityFunction) {
  107717. var _this = this;
  107718. if (this._isShowing)
  107719. return Promise.resolve(this);
  107720. return Promise.resolve().then(function () {
  107721. _this._isHiding = true;
  107722. if (visibilityFunction) {
  107723. return visibilityFunction(_this);
  107724. }
  107725. else {
  107726. // flex? box? should this be configurable easier than the visibilityFunction?
  107727. _this.parent.style.display = 'none';
  107728. return _this;
  107729. }
  107730. }).then(function () {
  107731. _this.isShown = false;
  107732. _this._isHiding = false;
  107733. _this.onStateChange.notifyObservers(_this);
  107734. return _this;
  107735. });
  107736. };
  107737. /**
  107738. * Dispose this template
  107739. */
  107740. Template.prototype.dispose = function () {
  107741. this.onAppended.clear();
  107742. this.onEventTriggered.clear();
  107743. this.onLoaded.clear();
  107744. this.onStateChange.clear();
  107745. this.isLoaded = false;
  107746. // remove from parent
  107747. try {
  107748. this.parent.removeChild(this._fragment);
  107749. }
  107750. catch (e) {
  107751. //noop
  107752. }
  107753. this.loadRequests.forEach(function (request) {
  107754. request.abort();
  107755. });
  107756. if (this._registeredEvents) {
  107757. this._registeredEvents.forEach(function (evt) {
  107758. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  107759. });
  107760. }
  107761. delete this._fragment;
  107762. };
  107763. Template.prototype._getTemplateAsHtml = function (templateConfig) {
  107764. var _this = this;
  107765. if (!templateConfig) {
  107766. return Promise.reject('No templateConfig provided');
  107767. }
  107768. else if (templateConfig.html !== undefined) {
  107769. return Promise.resolve(templateConfig.html);
  107770. }
  107771. else {
  107772. var location_1 = this._getTemplateLocation(templateConfig);
  107773. if (helper_1.isUrl(location_1)) {
  107774. return new Promise(function (resolve, reject) {
  107775. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  107776. resolve(data);
  107777. }, undefined, undefined, false, function (request, error) {
  107778. reject(error);
  107779. });
  107780. _this.loadRequests.push(fileRequest);
  107781. });
  107782. }
  107783. else {
  107784. location_1 = location_1.replace('#', '');
  107785. var element = document.getElementById(location_1);
  107786. if (element) {
  107787. return Promise.resolve(element.innerHTML);
  107788. }
  107789. else {
  107790. return Promise.reject('Template ID not found');
  107791. }
  107792. }
  107793. }
  107794. };
  107795. Template.prototype._registerEvents = function () {
  107796. var _this = this;
  107797. this._registeredEvents = this._registeredEvents || [];
  107798. if (this._registeredEvents.length) {
  107799. // first remove the registered events
  107800. this._registeredEvents.forEach(function (evt) {
  107801. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  107802. });
  107803. }
  107804. if (this._configuration.events) {
  107805. var _loop_1 = function (eventName) {
  107806. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  107807. var functionToFire_1 = function (selector, event) {
  107808. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  107809. };
  107810. // if boolean, set the parent as the event listener
  107811. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  107812. var binding = functionToFire_1.bind(this_1, '#' + this_1.parent.id);
  107813. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, '#' + this_1.parent.id), false);
  107814. this_1._registeredEvents.push({
  107815. htmlElement: this_1.parent,
  107816. eventName: eventName,
  107817. function: binding
  107818. });
  107819. }
  107820. else if (typeof this_1._configuration.events[eventName] === 'object') {
  107821. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  107822. // strict null checl is working incorrectly, must override:
  107823. var event_1 = this_1._configuration.events[eventName] || {};
  107824. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  107825. if (selector && selector.indexOf('#') !== 0) {
  107826. selector = '#' + selector;
  107827. }
  107828. var htmlElement = _this.parent.querySelector(selector);
  107829. if (htmlElement) {
  107830. var binding = functionToFire_1.bind(_this, selector);
  107831. htmlElement.addEventListener(eventName, binding, false);
  107832. _this._registeredEvents.push({
  107833. htmlElement: htmlElement,
  107834. eventName: eventName,
  107835. function: binding
  107836. });
  107837. }
  107838. });
  107839. }
  107840. }
  107841. };
  107842. var this_1 = this;
  107843. for (var eventName in this._configuration.events) {
  107844. _loop_1(eventName);
  107845. }
  107846. }
  107847. };
  107848. Template.prototype._getTemplateLocation = function (templateConfig) {
  107849. if (!templateConfig || typeof templateConfig === 'string') {
  107850. return templateConfig;
  107851. }
  107852. else {
  107853. return templateConfig.location;
  107854. }
  107855. };
  107856. return Template;
  107857. }());
  107858. exports.Template = Template;
  107859. /***/ }),
  107860. /* 31 */
  107861. /***/ (function(module, exports, __webpack_require__) {
  107862. /**!
  107863. @license
  107864. handlebars v4.0.11
  107865. Copyright (C) 2011-2017 by Yehuda Katz
  107866. Permission is hereby granted, free of charge, to any person obtaining a copy
  107867. of this software and associated documentation files (the "Software"), to deal
  107868. in the Software without restriction, including without limitation the rights
  107869. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  107870. copies of the Software, and to permit persons to whom the Software is
  107871. furnished to do so, subject to the following conditions:
  107872. The above copyright notice and this permission notice shall be included in
  107873. all copies or substantial portions of the Software.
  107874. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  107875. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  107876. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  107877. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  107878. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  107879. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  107880. THE SOFTWARE.
  107881. */
  107882. !function(a,b){ true?module.exports=b():"function"==typeof define&&define.amd?define([],b):"object"==typeof exports?exports.Handlebars=b():a.Handlebars=b()}(this,function(){return function(a){function b(d){if(c[d])return c[d].exports;var e=c[d]={exports:{},id:d,loaded:!1};return a[d].call(e.exports,e,e.exports,b),e.loaded=!0,e.exports}var c={};return b.m=a,b.c=c,b.p="",b(0)}([function(a,b,c){"use strict";function d(){var a=r();return a.compile=function(b,c){return k.compile(b,c,a)},a.precompile=function(b,c){return k.precompile(b,c,a)},a.AST=i["default"],a.Compiler=k.Compiler,a.JavaScriptCompiler=m["default"],a.Parser=j.parser,a.parse=j.parse,a}var e=c(1)["default"];b.__esModule=!0;var f=c(2),g=e(f),h=c(35),i=e(h),j=c(36),k=c(41),l=c(42),m=e(l),n=c(39),o=e(n),p=c(34),q=e(p),r=g["default"].create,s=d();s.create=d,q["default"](s),s.Visitor=o["default"],s["default"]=s,b["default"]=s,a.exports=b["default"]},function(a,b){"use strict";b["default"]=function(a){return a&&a.__esModule?a:{"default":a}},b.__esModule=!0},function(a,b,c){"use strict";function d(){var a=new h.HandlebarsEnvironment;return n.extend(a,h),a.SafeString=j["default"],a.Exception=l["default"],a.Utils=n,a.escapeExpression=n.escapeExpression,a.VM=p,a.template=function(b){return p.template(b,a)},a}var e=c(3)["default"],f=c(1)["default"];b.__esModule=!0;var g=c(4),h=e(g),i=c(21),j=f(i),k=c(6),l=f(k),m=c(5),n=e(m),o=c(22),p=e(o),q=c(34),r=f(q),s=d();s.create=d,r["default"](s),s["default"]=s,b["default"]=s,a.exports=b["default"]},function(a,b){"use strict";b["default"]=function(a){if(a&&a.__esModule)return a;var b={};if(null!=a)for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&(b[c]=a[c]);return b["default"]=a,b},b.__esModule=!0},function(a,b,c){"use strict";function d(a,b,c){this.helpers=a||{},this.partials=b||{},this.decorators=c||{},i.registerDefaultHelpers(this),j.registerDefaultDecorators(this)}var e=c(1)["default"];b.__esModule=!0,b.HandlebarsEnvironment=d;var f=c(5),g=c(6),h=e(g),i=c(10),j=c(18),k=c(20),l=e(k),m="4.0.11";b.VERSION=m;var n=7;b.COMPILER_REVISION=n;var o={1:"<= 1.0.rc.2",2:"== 1.0.0-rc.3",3:"== 1.0.0-rc.4",4:"== 1.x.x",5:"== 2.0.0-alpha.x",6:">= 2.0.0-beta.1",7:">= 4.0.0"};b.REVISION_CHANGES=o;var p="[object Object]";d.prototype={constructor:d,logger:l["default"],log:l["default"].log,registerHelper:function(a,b){if(f.toString.call(a)===p){if(b)throw new h["default"]("Arg not supported with multiple helpers");f.extend(this.helpers,a)}else this.helpers[a]=b},unregisterHelper:function(a){delete this.helpers[a]},registerPartial:function(a,b){if(f.toString.call(a)===p)f.extend(this.partials,a);else{if("undefined"==typeof b)throw new h["default"]('Attempting to register a partial called "'+a+'" as undefined');this.partials[a]=b}},unregisterPartial:function(a){delete this.partials[a]},registerDecorator:function(a,b){if(f.toString.call(a)===p){if(b)throw new h["default"]("Arg not supported with multiple decorators");f.extend(this.decorators,a)}else this.decorators[a]=b},unregisterDecorator:function(a){delete this.decorators[a]}};var q=l["default"].log;b.log=q,b.createFrame=f.createFrame,b.logger=l["default"]},function(a,b){"use strict";function c(a){return k[a]}function d(a){for(var b=1;b<arguments.length;b++)for(var c in arguments[b])Object.prototype.hasOwnProperty.call(arguments[b],c)&&(a[c]=arguments[b][c]);return a}function e(a,b){for(var c=0,d=a.length;c<d;c++)if(a[c]===b)return c;return-1}function f(a){if("string"!=typeof a){if(a&&a.toHTML)return a.toHTML();if(null==a)return"";if(!a)return a+"";a=""+a}return m.test(a)?a.replace(l,c):a}function g(a){return!a&&0!==a||!(!p(a)||0!==a.length)}function h(a){var b=d({},a);return b._parent=a,b}function i(a,b){return a.path=b,a}function j(a,b){return(a?a+".":"")+b}b.__esModule=!0,b.extend=d,b.indexOf=e,b.escapeExpression=f,b.isEmpty=g,b.createFrame=h,b.blockParams=i,b.appendContextPath=j;var k={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;","=":"&#x3D;"},l=/[&<>"'`=]/g,m=/[&<>"'`=]/,n=Object.prototype.toString;b.toString=n;var o=function(a){return"function"==typeof a};o(/x/)&&(b.isFunction=o=function(a){return"function"==typeof a&&"[object Function]"===n.call(a)}),b.isFunction=o;var p=Array.isArray||function(a){return!(!a||"object"!=typeof a)&&"[object Array]"===n.call(a)};b.isArray=p},function(a,b,c){"use strict";function d(a,b){var c=b&&b.loc,g=void 0,h=void 0;c&&(g=c.start.line,h=c.start.column,a+=" - "+g+":"+h);for(var i=Error.prototype.constructor.call(this,a),j=0;j<f.length;j++)this[f[j]]=i[f[j]];Error.captureStackTrace&&Error.captureStackTrace(this,d);try{c&&(this.lineNumber=g,e?Object.defineProperty(this,"column",{value:h,enumerable:!0}):this.column=h)}catch(k){}}var e=c(7)["default"];b.__esModule=!0;var f=["description","fileName","lineNumber","message","name","number","stack"];d.prototype=new Error,b["default"]=d,a.exports=b["default"]},function(a,b,c){a.exports={"default":c(8),__esModule:!0}},function(a,b,c){var d=c(9);a.exports=function(a,b,c){return d.setDesc(a,b,c)}},function(a,b){var c=Object;a.exports={create:c.create,getProto:c.getPrototypeOf,isEnum:{}.propertyIsEnumerable,getDesc:c.getOwnPropertyDescriptor,setDesc:c.defineProperty,setDescs:c.defineProperties,getKeys:c.keys,getNames:c.getOwnPropertyNames,getSymbols:c.getOwnPropertySymbols,each:[].forEach}},function(a,b,c){"use strict";function d(a){g["default"](a),i["default"](a),k["default"](a),m["default"](a),o["default"](a),q["default"](a),s["default"](a)}var e=c(1)["default"];b.__esModule=!0,b.registerDefaultHelpers=d;var f=c(11),g=e(f),h=c(12),i=e(h),j=c(13),k=e(j),l=c(14),m=e(l),n=c(15),o=e(n),p=c(16),q=e(p),r=c(17),s=e(r)},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerHelper("blockHelperMissing",function(b,c){var e=c.inverse,f=c.fn;if(b===!0)return f(this);if(b===!1||null==b)return e(this);if(d.isArray(b))return b.length>0?(c.ids&&(c.ids=[c.name]),a.helpers.each(b,c)):e(this);if(c.data&&c.ids){var g=d.createFrame(c.data);g.contextPath=d.appendContextPath(c.data.contextPath,c.name),c={data:g}}return f(b,c)})},a.exports=b["default"]},function(a,b,c){"use strict";var d=c(1)["default"];b.__esModule=!0;var e=c(5),f=c(6),g=d(f);b["default"]=function(a){a.registerHelper("each",function(a,b){function c(b,c,f){j&&(j.key=b,j.index=c,j.first=0===c,j.last=!!f,k&&(j.contextPath=k+b)),i+=d(a[b],{data:j,blockParams:e.blockParams([a[b],b],[k+b,null])})}if(!b)throw new g["default"]("Must pass iterator to #each");var d=b.fn,f=b.inverse,h=0,i="",j=void 0,k=void 0;if(b.data&&b.ids&&(k=e.appendContextPath(b.data.contextPath,b.ids[0])+"."),e.isFunction(a)&&(a=a.call(this)),b.data&&(j=e.createFrame(b.data)),a&&"object"==typeof a)if(e.isArray(a))for(var l=a.length;h<l;h++)h in a&&c(h,h,h===a.length-1);else{var m=void 0;for(var n in a)a.hasOwnProperty(n)&&(void 0!==m&&c(m,h-1),m=n,h++);void 0!==m&&c(m,h-1,!0)}return 0===h&&(i=f(this)),i})},a.exports=b["default"]},function(a,b,c){"use strict";var d=c(1)["default"];b.__esModule=!0;var e=c(6),f=d(e);b["default"]=function(a){a.registerHelper("helperMissing",function(){if(1!==arguments.length)throw new f["default"]('Missing helper: "'+arguments[arguments.length-1].name+'"')})},a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerHelper("if",function(a,b){return d.isFunction(a)&&(a=a.call(this)),!b.hash.includeZero&&!a||d.isEmpty(a)?b.inverse(this):b.fn(this)}),a.registerHelper("unless",function(b,c){return a.helpers["if"].call(this,b,{fn:c.inverse,inverse:c.fn,hash:c.hash})})},a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,b["default"]=function(a){a.registerHelper("log",function(){for(var b=[void 0],c=arguments[arguments.length-1],d=0;d<arguments.length-1;d++)b.push(arguments[d]);var e=1;null!=c.hash.level?e=c.hash.level:c.data&&null!=c.data.level&&(e=c.data.level),b[0]=e,a.log.apply(a,b)})},a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,b["default"]=function(a){a.registerHelper("lookup",function(a,b){return a&&a[b]})},a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerHelper("with",function(a,b){d.isFunction(a)&&(a=a.call(this));var c=b.fn;if(d.isEmpty(a))return b.inverse(this);var e=b.data;return b.data&&b.ids&&(e=d.createFrame(b.data),e.contextPath=d.appendContextPath(b.data.contextPath,b.ids[0])),c(a,{data:e,blockParams:d.blockParams([a],[e&&e.contextPath])})})},a.exports=b["default"]},function(a,b,c){"use strict";function d(a){g["default"](a)}var e=c(1)["default"];b.__esModule=!0,b.registerDefaultDecorators=d;var f=c(19),g=e(f)},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerDecorator("inline",function(a,b,c,e){var f=a;return b.partials||(b.partials={},f=function(e,f){var g=c.partials;c.partials=d.extend({},g,b.partials);var h=a(e,f);return c.partials=g,h}),b.partials[e.args[0]]=e.fn,f})},a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5),e={methodMap:["debug","info","warn","error"],level:"info",lookupLevel:function(a){if("string"==typeof a){var b=d.indexOf(e.methodMap,a.toLowerCase());a=b>=0?b:parseInt(a,10)}return a},log:function(a){if(a=e.lookupLevel(a),"undefined"!=typeof console&&e.lookupLevel(e.level)<=a){var b=e.methodMap[a];console[b]||(b="log");for(var c=arguments.length,d=Array(c>1?c-1:0),f=1;f<c;f++)d[f-1]=arguments[f];console[b].apply(console,d)}}};b["default"]=e,a.exports=b["default"]},function(a,b){"use strict";function c(a){this.string=a}b.__esModule=!0,c.prototype.toString=c.prototype.toHTML=function(){return""+this.string},b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(a){var b=a&&a[0]||1,c=s.COMPILER_REVISION;if(b!==c){if(b<c){var d=s.REVISION_CHANGES[c],e=s.REVISION_CHANGES[b];throw new r["default"]("Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version ("+d+") or downgrade your runtime to an older version ("+e+").")}throw new r["default"]("Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version ("+a[1]+").")}}function e(a,b){function c(c,d,e){e.hash&&(d=p.extend({},d,e.hash),e.ids&&(e.ids[0]=!0)),c=b.VM.resolvePartial.call(this,c,d,e);var f=b.VM.invokePartial.call(this,c,d,e);if(null==f&&b.compile&&(e.partials[e.name]=b.compile(c,a.compilerOptions,b),f=e.partials[e.name](d,e)),null!=f){if(e.indent){for(var g=f.split("\n"),h=0,i=g.length;h<i&&(g[h]||h+1!==i);h++)g[h]=e.indent+g[h];f=g.join("\n")}return f}throw new r["default"]("The partial "+e.name+" could not be compiled when running in runtime-only mode")}function d(b){function c(b){return""+a.main(e,b,e.helpers,e.partials,g,i,h)}var f=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],g=f.data;d._setup(f),!f.partial&&a.useData&&(g=j(b,g));var h=void 0,i=a.useBlockParams?[]:void 0;return a.useDepths&&(h=f.depths?b!=f.depths[0]?[b].concat(f.depths):f.depths:[b]),(c=k(a.main,c,e,f.depths||[],g,i))(b,f)}if(!b)throw new r["default"]("No environment passed to template");if(!a||!a.main)throw new r["default"]("Unknown template object: "+typeof a);a.main.decorator=a.main_d,b.VM.checkRevision(a.compiler);var e={strict:function(a,b){if(!(b in a))throw new r["default"]('"'+b+'" not defined in '+a);return a[b]},lookup:function(a,b){for(var c=a.length,d=0;d<c;d++)if(a[d]&&null!=a[d][b])return a[d][b]},lambda:function(a,b){return"function"==typeof a?a.call(b):a},escapeExpression:p.escapeExpression,invokePartial:c,fn:function(b){var c=a[b];return c.decorator=a[b+"_d"],c},programs:[],program:function(a,b,c,d,e){var g=this.programs[a],h=this.fn(a);return b||e||d||c?g=f(this,a,h,b,c,d,e):g||(g=this.programs[a]=f(this,a,h)),g},data:function(a,b){for(;a&&b--;)a=a._parent;return a},merge:function(a,b){var c=a||b;return a&&b&&a!==b&&(c=p.extend({},b,a)),c},nullContext:l({}),noop:b.VM.noop,compilerInfo:a.compiler};return d.isTop=!0,d._setup=function(c){c.partial?(e.helpers=c.helpers,e.partials=c.partials,e.decorators=c.decorators):(e.helpers=e.merge(c.helpers,b.helpers),a.usePartial&&(e.partials=e.merge(c.partials,b.partials)),(a.usePartial||a.useDecorators)&&(e.decorators=e.merge(c.decorators,b.decorators)))},d._child=function(b,c,d,g){if(a.useBlockParams&&!d)throw new r["default"]("must pass block params");if(a.useDepths&&!g)throw new r["default"]("must pass parent depths");return f(e,b,a[b],c,0,d,g)},d}function f(a,b,c,d,e,f,g){function h(b){var e=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],h=g;return!g||b==g[0]||b===a.nullContext&&null===g[0]||(h=[b].concat(g)),c(a,b,a.helpers,a.partials,e.data||d,f&&[e.blockParams].concat(f),h)}return h=k(c,h,a,g,d,f),h.program=b,h.depth=g?g.length:0,h.blockParams=e||0,h}function g(a,b,c){return a?a.call||c.name||(c.name=a,a=c.partials[a]):a="@partial-block"===c.name?c.data["partial-block"]:c.partials[c.name],a}function h(a,b,c){var d=c.data&&c.data["partial-block"];c.partial=!0,c.ids&&(c.data.contextPath=c.ids[0]||c.data.contextPath);var e=void 0;if(c.fn&&c.fn!==i&&!function(){c.data=s.createFrame(c.data);var a=c.fn;e=c.data["partial-block"]=function(b){var c=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];return c.data=s.createFrame(c.data),c.data["partial-block"]=d,a(b,c)},a.partials&&(c.partials=p.extend({},c.partials,a.partials))}(),void 0===a&&e&&(a=e),void 0===a)throw new r["default"]("The partial "+c.name+" could not be found");if(a instanceof Function)return a(b,c)}function i(){return""}function j(a,b){return b&&"root"in b||(b=b?s.createFrame(b):{},b.root=a),b}function k(a,b,c,d,e,f){if(a.decorator){var g={};b=a.decorator(b,g,c,d&&d[0],e,f,d),p.extend(b,g)}return b}var l=c(23)["default"],m=c(3)["default"],n=c(1)["default"];b.__esModule=!0,b.checkRevision=d,b.template=e,b.wrapProgram=f,b.resolvePartial=g,b.invokePartial=h,b.noop=i;var o=c(5),p=m(o),q=c(6),r=n(q),s=c(4)},function(a,b,c){a.exports={"default":c(24),__esModule:!0}},function(a,b,c){c(25),a.exports=c(30).Object.seal},function(a,b,c){var d=c(26);c(27)("seal",function(a){return function(b){return a&&d(b)?a(b):b}})},function(a,b){a.exports=function(a){return"object"==typeof a?null!==a:"function"==typeof a}},function(a,b,c){var d=c(28),e=c(30),f=c(33);a.exports=function(a,b){var c=(e.Object||{})[a]||Object[a],g={};g[a]=b(c),d(d.S+d.F*f(function(){c(1)}),"Object",g)}},function(a,b,c){var d=c(29),e=c(30),f=c(31),g="prototype",h=function(a,b,c){var i,j,k,l=a&h.F,m=a&h.G,n=a&h.S,o=a&h.P,p=a&h.B,q=a&h.W,r=m?e:e[b]||(e[b]={}),s=m?d:n?d[b]:(d[b]||{})[g];m&&(c=b);for(i in c)j=!l&&s&&i in s,j&&i in r||(k=j?s[i]:c[i],r[i]=m&&"function"!=typeof s[i]?c[i]:p&&j?f(k,d):q&&s[i]==k?function(a){var b=function(b){return this instanceof a?new a(b):a(b)};return b[g]=a[g],b}(k):o&&"function"==typeof k?f(Function.call,k):k,o&&((r[g]||(r[g]={}))[i]=k))};h.F=1,h.G=2,h.S=4,h.P=8,h.B=16,h.W=32,a.exports=h},function(a,b){var c=a.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=c)},function(a,b){var c=a.exports={version:"1.2.6"};"number"==typeof __e&&(__e=c)},function(a,b,c){var d=c(32);a.exports=function(a,b,c){if(d(a),void 0===b)return a;switch(c){case 1:return function(c){return a.call(b,c)};case 2:return function(c,d){return a.call(b,c,d)};case 3:return function(c,d,e){return a.call(b,c,d,e)}}return function(){return a.apply(b,arguments)}}},function(a,b){a.exports=function(a){if("function"!=typeof a)throw TypeError(a+" is not a function!");return a}},function(a,b){a.exports=function(a){try{return!!a()}catch(b){return!0}}},function(a,b){(function(c){"use strict";b.__esModule=!0,b["default"]=function(a){var b="undefined"!=typeof c?c:window,d=b.Handlebars;a.noConflict=function(){return b.Handlebars===a&&(b.Handlebars=d),a}},a.exports=b["default"]}).call(b,function(){return this}())},function(a,b){"use strict";b.__esModule=!0;var c={helpers:{helperExpression:function(a){return"SubExpression"===a.type||("MustacheStatement"===a.type||"BlockStatement"===a.type)&&!!(a.params&&a.params.length||a.hash)},scopedId:function(a){return/^\.|this\b/.test(a.original)},simpleId:function(a){return 1===a.parts.length&&!c.helpers.scopedId(a)&&!a.depth}}};b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b){if("Program"===a.type)return a;h["default"].yy=n,n.locInfo=function(a){return new n.SourceLocation(b&&b.srcName,a)};var c=new j["default"](b);return c.accept(h["default"].parse(a))}var e=c(1)["default"],f=c(3)["default"];b.__esModule=!0,b.parse=d;var g=c(37),h=e(g),i=c(38),j=e(i),k=c(40),l=f(k),m=c(5);b.parser=h["default"];var n={};m.extend(n,l)},function(a,b){"use strict";b.__esModule=!0;var c=function(){function a(){this.yy={}}var b={trace:function(){},yy:{},symbols_:{error:2,root:3,program:4,EOF:5,program_repetition0:6,statement:7,mustache:8,block:9,rawBlock:10,partial:11,partialBlock:12,content:13,COMMENT:14,CONTENT:15,openRawBlock:16,rawBlock_repetition_plus0:17,END_RAW_BLOCK:18,OPEN_RAW_BLOCK:19,helperName:20,openRawBlock_repetition0:21,openRawBlock_option0:22,CLOSE_RAW_BLOCK:23,openBlock:24,block_option0:25,closeBlock:26,openInverse:27,block_option1:28,OPEN_BLOCK:29,openBlock_repetition0:30,openBlock_option0:31,openBlock_option1:32,CLOSE:33,OPEN_INVERSE:34,openInverse_repetition0:35,openInverse_option0:36,openInverse_option1:37,openInverseChain:38,OPEN_INVERSE_CHAIN:39,openInverseChain_repetition0:40,openInverseChain_option0:41,openInverseChain_option1:42,inverseAndProgram:43,INVERSE:44,inverseChain:45,inverseChain_option0:46,OPEN_ENDBLOCK:47,OPEN:48,mustache_repetition0:49,mustache_option0:50,OPEN_UNESCAPED:51,mustache_repetition1:52,mustache_option1:53,CLOSE_UNESCAPED:54,OPEN_PARTIAL:55,partialName:56,partial_repetition0:57,partial_option0:58,openPartialBlock:59,OPEN_PARTIAL_BLOCK:60,openPartialBlock_repetition0:61,openPartialBlock_option0:62,param:63,sexpr:64,OPEN_SEXPR:65,sexpr_repetition0:66,sexpr_option0:67,CLOSE_SEXPR:68,hash:69,hash_repetition_plus0:70,hashSegment:71,ID:72,EQUALS:73,blockParams:74,OPEN_BLOCK_PARAMS:75,blockParams_repetition_plus0:76,CLOSE_BLOCK_PARAMS:77,path:78,dataName:79,STRING:80,NUMBER:81,BOOLEAN:82,UNDEFINED:83,NULL:84,DATA:85,pathSegments:86,SEP:87,$accept:0,$end:1},terminals_:{2:"error",5:"EOF",14:"COMMENT",15:"CONTENT",18:"END_RAW_BLOCK",19:"OPEN_RAW_BLOCK",23:"CLOSE_RAW_BLOCK",29:"OPEN_BLOCK",33:"CLOSE",34:"OPEN_INVERSE",39:"OPEN_INVERSE_CHAIN",44:"INVERSE",47:"OPEN_ENDBLOCK",48:"OPEN",51:"OPEN_UNESCAPED",54:"CLOSE_UNESCAPED",55:"OPEN_PARTIAL",60:"OPEN_PARTIAL_BLOCK",65:"OPEN_SEXPR",68:"CLOSE_SEXPR",72:"ID",73:"EQUALS",75:"OPEN_BLOCK_PARAMS",77:"CLOSE_BLOCK_PARAMS",80:"STRING",81:"NUMBER",82:"BOOLEAN",83:"UNDEFINED",84:"NULL",85:"DATA",87:"SEP"},productions_:[0,[3,2],[4,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[13,1],[10,3],[16,5],[9,4],[9,4],[24,6],[27,6],[38,6],[43,2],[45,3],[45,1],[26,3],[8,5],[8,5],[11,5],[12,3],[59,5],[63,1],[63,1],[64,5],[69,1],[71,3],[74,3],[20,1],[20,1],[20,1],[20,1],[20,1],[20,1],[20,1],[56,1],[56,1],[79,2],[78,1],[86,3],[86,1],[6,0],[6,2],[17,1],[17,2],[21,0],[21,2],[22,0],[22,1],[25,0],[25,1],[28,0],[28,1],[30,0],[30,2],[31,0],[31,1],[32,0],[32,1],[35,0],[35,2],[36,0],[36,1],[37,0],[37,1],[40,0],[40,2],[41,0],[41,1],[42,0],[42,1],[46,0],[46,1],[49,0],[49,2],[50,0],[50,1],[52,0],[52,2],[53,0],[53,1],[57,0],[57,2],[58,0],[58,1],[61,0],[61,2],[62,0],[62,1],[66,0],[66,2],[67,0],[67,1],[70,1],[70,2],[76,1],[76,2]],performAction:function(a,b,c,d,e,f,g){var h=f.length-1;switch(e){case 1:return f[h-1];case 2:this.$=d.prepareProgram(f[h]);break;case 3:this.$=f[h];break;case 4:this.$=f[h];break;case 5:this.$=f[h];break;case 6:this.$=f[h];break;case 7:this.$=f[h];break;case 8:this.$=f[h];break;case 9:this.$={type:"CommentStatement",value:d.stripComment(f[h]),strip:d.stripFlags(f[h],f[h]),loc:d.locInfo(this._$)};break;case 10:this.$={type:"ContentStatement",original:f[h],value:f[h],loc:d.locInfo(this._$)};break;case 11:this.$=d.prepareRawBlock(f[h-2],f[h-1],f[h],this._$);break;case 12:this.$={path:f[h-3],params:f[h-2],hash:f[h-1]};break;case 13:this.$=d.prepareBlock(f[h-3],f[h-2],f[h-1],f[h],!1,this._$);break;case 14:this.$=d.prepareBlock(f[h-3],f[h-2],f[h-1],f[h],!0,this._$);break;case 15:this.$={open:f[h-5],path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 16:this.$={path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 17:this.$={path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 18:this.$={strip:d.stripFlags(f[h-1],f[h-1]),program:f[h]};break;case 19:var i=d.prepareBlock(f[h-2],f[h-1],f[h],f[h],!1,this._$),j=d.prepareProgram([i],f[h-1].loc);j.chained=!0,this.$={strip:f[h-2].strip,program:j,chain:!0};break;case 20:this.$=f[h];break;case 21:this.$={path:f[h-1],strip:d.stripFlags(f[h-2],f[h])};break;case 22:this.$=d.prepareMustache(f[h-3],f[h-2],f[h-1],f[h-4],d.stripFlags(f[h-4],f[h]),this._$);break;case 23:this.$=d.prepareMustache(f[h-3],f[h-2],f[h-1],f[h-4],d.stripFlags(f[h-4],f[h]),this._$);break;case 24:this.$={type:"PartialStatement",name:f[h-3],params:f[h-2],hash:f[h-1],indent:"",strip:d.stripFlags(f[h-4],f[h]),loc:d.locInfo(this._$)};break;case 25:this.$=d.preparePartialBlock(f[h-2],f[h-1],f[h],this._$);break;case 26:this.$={path:f[h-3],params:f[h-2],hash:f[h-1],strip:d.stripFlags(f[h-4],f[h])};break;case 27:this.$=f[h];break;case 28:this.$=f[h];break;case 29:this.$={type:"SubExpression",path:f[h-3],params:f[h-2],hash:f[h-1],loc:d.locInfo(this._$)};break;case 30:this.$={type:"Hash",pairs:f[h],loc:d.locInfo(this._$)};break;case 31:this.$={type:"HashPair",key:d.id(f[h-2]),value:f[h],loc:d.locInfo(this._$)};break;case 32:this.$=d.id(f[h-1]);break;case 33:this.$=f[h];break;case 34:this.$=f[h];break;case 35:this.$={type:"StringLiteral",value:f[h],original:f[h],loc:d.locInfo(this._$)};break;case 36:this.$={type:"NumberLiteral",value:Number(f[h]),original:Number(f[h]),loc:d.locInfo(this._$)};break;case 37:this.$={type:"BooleanLiteral",value:"true"===f[h],original:"true"===f[h],loc:d.locInfo(this._$)};break;case 38:this.$={type:"UndefinedLiteral",original:void 0,value:void 0,loc:d.locInfo(this._$)};break;case 39:this.$={type:"NullLiteral",original:null,value:null,loc:d.locInfo(this._$)};break;case 40:this.$=f[h];break;case 41:this.$=f[h];break;case 42:this.$=d.preparePath(!0,f[h],this._$);break;case 43:this.$=d.preparePath(!1,f[h],this._$);break;case 44:f[h-2].push({part:d.id(f[h]),original:f[h],separator:f[h-1]}),this.$=f[h-2];break;case 45:this.$=[{part:d.id(f[h]),original:f[h]}];break;case 46:this.$=[];break;case 47:f[h-1].push(f[h]);break;case 48:this.$=[f[h]];break;case 49:f[h-1].push(f[h]);break;case 50:this.$=[];break;case 51:f[h-1].push(f[h]);break;case 58:this.$=[];break;case 59:f[h-1].push(f[h]);break;case 64:this.$=[];break;case 65:f[h-1].push(f[h]);break;case 70:this.$=[];break;case 71:f[h-1].push(f[h]);break;case 78:this.$=[];break;case 79:f[h-1].push(f[h]);break;case 82:this.$=[];break;case 83:f[h-1].push(f[h]);break;case 86:this.$=[];break;case 87:f[h-1].push(f[h]);break;case 90:this.$=[];break;case 91:f[h-1].push(f[h]);break;case 94:this.$=[];break;case 95:f[h-1].push(f[h]);break;case 98:this.$=[f[h]];break;case 99:f[h-1].push(f[h]);break;case 100:this.$=[f[h]];break;case 101:f[h-1].push(f[h])}},table:[{3:1,4:2,5:[2,46],6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{1:[3]},{5:[1,4]},{5:[2,2],7:5,8:6,9:7,10:8,11:9,12:10,13:11,14:[1,12],15:[1,20],16:17,19:[1,23],24:15,27:16,29:[1,21],34:[1,22],39:[2,2],44:[2,2],47:[2,2],48:[1,13],51:[1,14],55:[1,18],59:19,60:[1,24]},{1:[2,1]},{5:[2,47],14:[2,47],15:[2,47],19:[2,47],29:[2,47],34:[2,47],39:[2,47],44:[2,47],47:[2,47],48:[2,47],51:[2,47],55:[2,47],60:[2,47]},{5:[2,3],14:[2,3],15:[2,3],19:[2,3],29:[2,3],34:[2,3],39:[2,3],44:[2,3],47:[2,3],48:[2,3],51:[2,3],55:[2,3],60:[2,3]},{5:[2,4],14:[2,4],15:[2,4],19:[2,4],29:[2,4],34:[2,4],39:[2,4],44:[2,4],47:[2,4],48:[2,4],51:[2,4],55:[2,4],60:[2,4]},{5:[2,5],14:[2,5],15:[2,5],19:[2,5],29:[2,5],34:[2,5],39:[2,5],44:[2,5],47:[2,5],48:[2,5],51:[2,5],55:[2,5],60:[2,5]},{5:[2,6],14:[2,6],15:[2,6],19:[2,6],29:[2,6],34:[2,6],39:[2,6],44:[2,6],47:[2,6],48:[2,6],51:[2,6],55:[2,6],60:[2,6]},{5:[2,7],14:[2,7],15:[2,7],19:[2,7],29:[2,7],34:[2,7],39:[2,7],44:[2,7],47:[2,7],48:[2,7],51:[2,7],55:[2,7],60:[2,7]},{5:[2,8],14:[2,8],15:[2,8],19:[2,8],29:[2,8],34:[2,8],39:[2,8],44:[2,8],47:[2,8],48:[2,8],51:[2,8],55:[2,8],60:[2,8]},{5:[2,9],14:[2,9],15:[2,9],19:[2,9],29:[2,9],34:[2,9],39:[2,9],44:[2,9],47:[2,9],48:[2,9],51:[2,9],55:[2,9],60:[2,9]},{20:25,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:36,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:37,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],39:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{4:38,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{13:40,15:[1,20],17:39},{20:42,56:41,64:43,65:[1,44],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:45,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{5:[2,10],14:[2,10],15:[2,10],18:[2,10],19:[2,10],29:[2,10],34:[2,10],39:[2,10],44:[2,10],47:[2,10],48:[2,10],51:[2,10],55:[2,10],60:[2,10]},{20:46,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:47,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:48,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:42,56:49,64:43,65:[1,44],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[2,78],49:50,65:[2,78],72:[2,78],80:[2,78],81:[2,78],82:[2,78],83:[2,78],84:[2,78],85:[2,78]},{23:[2,33],33:[2,33],54:[2,33],65:[2,33],68:[2,33],72:[2,33],75:[2,33],80:[2,33],81:[2,33],82:[2,33],83:[2,33],84:[2,33],85:[2,33]},{23:[2,34],33:[2,34],54:[2,34],65:[2,34],68:[2,34],72:[2,34],75:[2,34],80:[2,34],81:[2,34],82:[2,34],83:[2,34],84:[2,34],85:[2,34]},{23:[2,35],33:[2,35],54:[2,35],65:[2,35],68:[2,35],72:[2,35],75:[2,35],80:[2,35],81:[2,35],82:[2,35],83:[2,35],84:[2,35],85:[2,35]},{23:[2,36],33:[2,36],54:[2,36],65:[2,36],68:[2,36],72:[2,36],75:[2,36],80:[2,36],81:[2,36],82:[2,36],83:[2,36],84:[2,36],85:[2,36]},{23:[2,37],33:[2,37],54:[2,37],65:[2,37],68:[2,37],72:[2,37],75:[2,37],80:[2,37],81:[2,37],82:[2,37],83:[2,37],84:[2,37],85:[2,37]},{23:[2,38],33:[2,38],54:[2,38],65:[2,38],68:[2,38],72:[2,38],75:[2,38],80:[2,38],81:[2,38],82:[2,38],83:[2,38],84:[2,38],85:[2,38]},{23:[2,39],33:[2,39],54:[2,39],65:[2,39],68:[2,39],72:[2,39],75:[2,39],80:[2,39],81:[2,39],82:[2,39],83:[2,39],84:[2,39],85:[2,39]},{23:[2,43],33:[2,43],54:[2,43],65:[2,43],68:[2,43],72:[2,43],75:[2,43],80:[2,43],81:[2,43],82:[2,43],83:[2,43],84:[2,43],85:[2,43],87:[1,51]},{72:[1,35],86:52},{23:[2,45],33:[2,45],54:[2,45],65:[2,45],68:[2,45],72:[2,45],75:[2,45],80:[2,45],81:[2,45],82:[2,45],83:[2,45],84:[2,45],85:[2,45],87:[2,45]},{52:53,54:[2,82],65:[2,82],72:[2,82],80:[2,82],81:[2,82],82:[2,82],83:[2,82],84:[2,82],85:[2,82]},{25:54,38:56,39:[1,58],43:57,44:[1,59],45:55,47:[2,54]},{28:60,43:61,44:[1,59],47:[2,56]},{13:63,15:[1,20],18:[1,62]},{15:[2,48],18:[2,48]},{33:[2,86],57:64,65:[2,86],72:[2,86],80:[2,86],81:[2,86],82:[2,86],83:[2,86],84:[2,86],85:[2,86]},{33:[2,40],65:[2,40],72:[2,40],80:[2,40],81:[2,40],82:[2,40],83:[2,40],84:[2,40],85:[2,40]},{33:[2,41],65:[2,41],72:[2,41],80:[2,41],81:[2,41],82:[2,41],83:[2,41],84:[2,41],85:[2,41]},{20:65,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{26:66,47:[1,67]},{30:68,33:[2,58],65:[2,58],72:[2,58],75:[2,58],80:[2,58],81:[2,58],82:[2,58],83:[2,58],84:[2,58],85:[2,58]},{33:[2,64],35:69,65:[2,64],72:[2,64],75:[2,64],80:[2,64],81:[2,64],82:[2,64],83:[2,64],84:[2,64],85:[2,64]},{21:70,23:[2,50],65:[2,50],72:[2,50],80:[2,50],81:[2,50],82:[2,50],83:[2,50],84:[2,50],85:[2,50]},{33:[2,90],61:71,65:[2,90],72:[2,90],80:[2,90],81:[2,90],82:[2,90],83:[2,90],84:[2,90],85:[2,90]},{20:75,33:[2,80],50:72,63:73,64:76,65:[1,44],69:74,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{72:[1,80]},{23:[2,42],33:[2,42],54:[2,42],65:[2,42],68:[2,42],72:[2,42],75:[2,42],80:[2,42],81:[2,42],82:[2,42],83:[2,42],84:[2,42],85:[2,42],87:[1,51]},{20:75,53:81,54:[2,84],63:82,64:76,65:[1,44],69:83,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{26:84,47:[1,67]},{47:[2,55]},{4:85,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],39:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{47:[2,20]},{20:86,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:87,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{26:88,47:[1,67]},{47:[2,57]},{5:[2,11],14:[2,11],15:[2,11],19:[2,11],29:[2,11],34:[2,11],39:[2,11],44:[2,11],47:[2,11],48:[2,11],51:[2,11],55:[2,11],60:[2,11]},{15:[2,49],18:[2,49]},{20:75,33:[2,88],58:89,63:90,64:76,65:[1,44],69:91,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{65:[2,94],66:92,68:[2,94],72:[2,94],80:[2,94],81:[2,94],82:[2,94],83:[2,94],84:[2,94],85:[2,94]},{5:[2,25],14:[2,25],15:[2,25],19:[2,25],29:[2,25],34:[2,25],39:[2,25],44:[2,25],47:[2,25],48:[2,25],51:[2,25],55:[2,25],60:[2,25]},{20:93,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,31:94,33:[2,60],63:95,64:76,65:[1,44],69:96,70:77,71:78,72:[1,79],75:[2,60],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,33:[2,66],36:97,63:98,64:76,65:[1,44],69:99,70:77,71:78,72:[1,79],75:[2,66],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,22:100,23:[2,52],63:101,64:76,65:[1,44],69:102,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:75,33:[2,92],62:103,63:104,64:76,65:[1,44],69:105,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[1,106]},{33:[2,79],65:[2,79],72:[2,79],80:[2,79],81:[2,79],82:[2,79],83:[2,79],84:[2,79],85:[2,79]},{33:[2,81]},{23:[2,27],33:[2,27],54:[2,27],65:[2,27],68:[2,27],72:[2,27],75:[2,27],80:[2,27],81:[2,27],82:[2,27],83:[2,27],84:[2,27],85:[2,27]},{23:[2,28],33:[2,28],54:[2,28],65:[2,28],68:[2,28],72:[2,28],75:[2,28],80:[2,28],81:[2,28],82:[2,28],83:[2,28],84:[2,28],85:[2,28]},{23:[2,30],33:[2,30],54:[2,30],68:[2,30],71:107,72:[1,108],75:[2,30]},{23:[2,98],33:[2,98],54:[2,98],68:[2,98],72:[2,98],75:[2,98]},{23:[2,45],33:[2,45],54:[2,45],65:[2,45],68:[2,45],72:[2,45],73:[1,109],75:[2,45],80:[2,45],81:[2,45],82:[2,45],83:[2,45],84:[2,45],85:[2,45],87:[2,45]},{23:[2,44],33:[2,44],54:[2,44],65:[2,44],68:[2,44],72:[2,44],75:[2,44],80:[2,44],81:[2,44],82:[2,44],83:[2,44],84:[2,44],85:[2,44],87:[2,44]},{54:[1,110]},{54:[2,83],65:[2,83],72:[2,83],80:[2,83],81:[2,83],82:[2,83],83:[2,83],84:[2,83],85:[2,83]},{54:[2,85]},{5:[2,13],14:[2,13],15:[2,13],19:[2,13],29:[2,13],34:[2,13],39:[2,13],44:[2,13],47:[2,13],48:[2,13],51:[2,13],55:[2,13],60:[2,13]},{38:56,39:[1,58],43:57,44:[1,59],45:112,46:111,47:[2,76]},{33:[2,70],40:113,65:[2,70],72:[2,70],75:[2,70],80:[2,70],81:[2,70],82:[2,70],83:[2,70],84:[2,70],85:[2,70]},{47:[2,18]},{5:[2,14],14:[2,14],15:[2,14],19:[2,14],29:[2,14],34:[2,14],39:[2,14],44:[2,14],47:[2,14],48:[2,14],51:[2,14],55:[2,14],60:[2,14]},{33:[1,114]},{33:[2,87],65:[2,87],72:[2,87],80:[2,87],81:[2,87],82:[2,87],83:[2,87],84:[2,87],
  107883. 85:[2,87]},{33:[2,89]},{20:75,63:116,64:76,65:[1,44],67:115,68:[2,96],69:117,70:77,71:78,72:[1,79],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[1,118]},{32:119,33:[2,62],74:120,75:[1,121]},{33:[2,59],65:[2,59],72:[2,59],75:[2,59],80:[2,59],81:[2,59],82:[2,59],83:[2,59],84:[2,59],85:[2,59]},{33:[2,61],75:[2,61]},{33:[2,68],37:122,74:123,75:[1,121]},{33:[2,65],65:[2,65],72:[2,65],75:[2,65],80:[2,65],81:[2,65],82:[2,65],83:[2,65],84:[2,65],85:[2,65]},{33:[2,67],75:[2,67]},{23:[1,124]},{23:[2,51],65:[2,51],72:[2,51],80:[2,51],81:[2,51],82:[2,51],83:[2,51],84:[2,51],85:[2,51]},{23:[2,53]},{33:[1,125]},{33:[2,91],65:[2,91],72:[2,91],80:[2,91],81:[2,91],82:[2,91],83:[2,91],84:[2,91],85:[2,91]},{33:[2,93]},{5:[2,22],14:[2,22],15:[2,22],19:[2,22],29:[2,22],34:[2,22],39:[2,22],44:[2,22],47:[2,22],48:[2,22],51:[2,22],55:[2,22],60:[2,22]},{23:[2,99],33:[2,99],54:[2,99],68:[2,99],72:[2,99],75:[2,99]},{73:[1,109]},{20:75,63:126,64:76,65:[1,44],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{5:[2,23],14:[2,23],15:[2,23],19:[2,23],29:[2,23],34:[2,23],39:[2,23],44:[2,23],47:[2,23],48:[2,23],51:[2,23],55:[2,23],60:[2,23]},{47:[2,19]},{47:[2,77]},{20:75,33:[2,72],41:127,63:128,64:76,65:[1,44],69:129,70:77,71:78,72:[1,79],75:[2,72],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{5:[2,24],14:[2,24],15:[2,24],19:[2,24],29:[2,24],34:[2,24],39:[2,24],44:[2,24],47:[2,24],48:[2,24],51:[2,24],55:[2,24],60:[2,24]},{68:[1,130]},{65:[2,95],68:[2,95],72:[2,95],80:[2,95],81:[2,95],82:[2,95],83:[2,95],84:[2,95],85:[2,95]},{68:[2,97]},{5:[2,21],14:[2,21],15:[2,21],19:[2,21],29:[2,21],34:[2,21],39:[2,21],44:[2,21],47:[2,21],48:[2,21],51:[2,21],55:[2,21],60:[2,21]},{33:[1,131]},{33:[2,63]},{72:[1,133],76:132},{33:[1,134]},{33:[2,69]},{15:[2,12]},{14:[2,26],15:[2,26],19:[2,26],29:[2,26],34:[2,26],47:[2,26],48:[2,26],51:[2,26],55:[2,26],60:[2,26]},{23:[2,31],33:[2,31],54:[2,31],68:[2,31],72:[2,31],75:[2,31]},{33:[2,74],42:135,74:136,75:[1,121]},{33:[2,71],65:[2,71],72:[2,71],75:[2,71],80:[2,71],81:[2,71],82:[2,71],83:[2,71],84:[2,71],85:[2,71]},{33:[2,73],75:[2,73]},{23:[2,29],33:[2,29],54:[2,29],65:[2,29],68:[2,29],72:[2,29],75:[2,29],80:[2,29],81:[2,29],82:[2,29],83:[2,29],84:[2,29],85:[2,29]},{14:[2,15],15:[2,15],19:[2,15],29:[2,15],34:[2,15],39:[2,15],44:[2,15],47:[2,15],48:[2,15],51:[2,15],55:[2,15],60:[2,15]},{72:[1,138],77:[1,137]},{72:[2,100],77:[2,100]},{14:[2,16],15:[2,16],19:[2,16],29:[2,16],34:[2,16],44:[2,16],47:[2,16],48:[2,16],51:[2,16],55:[2,16],60:[2,16]},{33:[1,139]},{33:[2,75]},{33:[2,32]},{72:[2,101],77:[2,101]},{14:[2,17],15:[2,17],19:[2,17],29:[2,17],34:[2,17],39:[2,17],44:[2,17],47:[2,17],48:[2,17],51:[2,17],55:[2,17],60:[2,17]}],defaultActions:{4:[2,1],55:[2,55],57:[2,20],61:[2,57],74:[2,81],83:[2,85],87:[2,18],91:[2,89],102:[2,53],105:[2,93],111:[2,19],112:[2,77],117:[2,97],120:[2,63],123:[2,69],124:[2,12],136:[2,75],137:[2,32]},parseError:function(a,b){throw new Error(a)},parse:function(a){function b(){var a;return a=c.lexer.lex()||1,"number"!=typeof a&&(a=c.symbols_[a]||a),a}var c=this,d=[0],e=[null],f=[],g=this.table,h="",i=0,j=0,k=0;this.lexer.setInput(a),this.lexer.yy=this.yy,this.yy.lexer=this.lexer,this.yy.parser=this,"undefined"==typeof this.lexer.yylloc&&(this.lexer.yylloc={});var l=this.lexer.yylloc;f.push(l);var m=this.lexer.options&&this.lexer.options.ranges;"function"==typeof this.yy.parseError&&(this.parseError=this.yy.parseError);for(var n,o,p,q,r,s,t,u,v,w={};;){if(p=d[d.length-1],this.defaultActions[p]?q=this.defaultActions[p]:(null!==n&&"undefined"!=typeof n||(n=b()),q=g[p]&&g[p][n]),"undefined"==typeof q||!q.length||!q[0]){var x="";if(!k){v=[];for(s in g[p])this.terminals_[s]&&s>2&&v.push("'"+this.terminals_[s]+"'");x=this.lexer.showPosition?"Parse error on line "+(i+1)+":\n"+this.lexer.showPosition()+"\nExpecting "+v.join(", ")+", got '"+(this.terminals_[n]||n)+"'":"Parse error on line "+(i+1)+": Unexpected "+(1==n?"end of input":"'"+(this.terminals_[n]||n)+"'"),this.parseError(x,{text:this.lexer.match,token:this.terminals_[n]||n,line:this.lexer.yylineno,loc:l,expected:v})}}if(q[0]instanceof Array&&q.length>1)throw new Error("Parse Error: multiple actions possible at state: "+p+", token: "+n);switch(q[0]){case 1:d.push(n),e.push(this.lexer.yytext),f.push(this.lexer.yylloc),d.push(q[1]),n=null,o?(n=o,o=null):(j=this.lexer.yyleng,h=this.lexer.yytext,i=this.lexer.yylineno,l=this.lexer.yylloc,k>0&&k--);break;case 2:if(t=this.productions_[q[1]][1],w.$=e[e.length-t],w._$={first_line:f[f.length-(t||1)].first_line,last_line:f[f.length-1].last_line,first_column:f[f.length-(t||1)].first_column,last_column:f[f.length-1].last_column},m&&(w._$.range=[f[f.length-(t||1)].range[0],f[f.length-1].range[1]]),r=this.performAction.call(w,h,j,i,this.yy,q[1],e,f),"undefined"!=typeof r)return r;t&&(d=d.slice(0,-1*t*2),e=e.slice(0,-1*t),f=f.slice(0,-1*t)),d.push(this.productions_[q[1]][0]),e.push(w.$),f.push(w._$),u=g[d[d.length-2]][d[d.length-1]],d.push(u);break;case 3:return!0}}return!0}},c=function(){var a={EOF:1,parseError:function(a,b){if(!this.yy.parser)throw new Error(a);this.yy.parser.parseError(a,b)},setInput:function(a){return this._input=a,this._more=this._less=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var a=this._input[0];this.yytext+=a,this.yyleng++,this.offset++,this.match+=a,this.matched+=a;var b=a.match(/(?:\r\n?|\n).*/g);return b?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),a},unput:function(a){var b=a.length,c=a.split(/(?:\r\n?|\n)/g);this._input=a+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-b-1),this.offset-=b;var d=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),c.length-1&&(this.yylineno-=c.length-1);var e=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:c?(c.length===d.length?this.yylloc.first_column:0)+d[d.length-c.length].length-c[0].length:this.yylloc.first_column-b},this.options.ranges&&(this.yylloc.range=[e[0],e[0]+this.yyleng-b]),this},more:function(){return this._more=!0,this},less:function(a){this.unput(this.match.slice(a))},pastInput:function(){var a=this.matched.substr(0,this.matched.length-this.match.length);return(a.length>20?"...":"")+a.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var a=this.match;return a.length<20&&(a+=this._input.substr(0,20-a.length)),(a.substr(0,20)+(a.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var a=this.pastInput(),b=new Array(a.length+1).join("-");return a+this.upcomingInput()+"\n"+b+"^"},next:function(){if(this.done)return this.EOF;this._input||(this.done=!0);var a,b,c,d,e;this._more||(this.yytext="",this.match="");for(var f=this._currentRules(),g=0;g<f.length&&(c=this._input.match(this.rules[f[g]]),!c||b&&!(c[0].length>b[0].length)||(b=c,d=g,this.options.flex));g++);return b?(e=b[0].match(/(?:\r\n?|\n).*/g),e&&(this.yylineno+=e.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:e?e[e.length-1].length-e[e.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+b[0].length},this.yytext+=b[0],this.match+=b[0],this.matches=b,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._input=this._input.slice(b[0].length),this.matched+=b[0],a=this.performAction.call(this,this.yy,this,f[d],this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),a?a:void 0):""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){var a=this.next();return"undefined"!=typeof a?a:this.lex()},begin:function(a){this.conditionStack.push(a)},popState:function(){return this.conditionStack.pop()},_currentRules:function(){return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules},topState:function(){return this.conditionStack[this.conditionStack.length-2]},pushState:function(a){this.begin(a)}};return a.options={},a.performAction=function(a,b,c,d){function e(a,c){return b.yytext=b.yytext.substr(a,b.yyleng-c)}switch(c){case 0:if("\\\\"===b.yytext.slice(-2)?(e(0,1),this.begin("mu")):"\\"===b.yytext.slice(-1)?(e(0,1),this.begin("emu")):this.begin("mu"),b.yytext)return 15;break;case 1:return 15;case 2:return this.popState(),15;case 3:return this.begin("raw"),15;case 4:return this.popState(),"raw"===this.conditionStack[this.conditionStack.length-1]?15:(b.yytext=b.yytext.substr(5,b.yyleng-9),"END_RAW_BLOCK");case 5:return 15;case 6:return this.popState(),14;case 7:return 65;case 8:return 68;case 9:return 19;case 10:return this.popState(),this.begin("raw"),23;case 11:return 55;case 12:return 60;case 13:return 29;case 14:return 47;case 15:return this.popState(),44;case 16:return this.popState(),44;case 17:return 34;case 18:return 39;case 19:return 51;case 20:return 48;case 21:this.unput(b.yytext),this.popState(),this.begin("com");break;case 22:return this.popState(),14;case 23:return 48;case 24:return 73;case 25:return 72;case 26:return 72;case 27:return 87;case 28:break;case 29:return this.popState(),54;case 30:return this.popState(),33;case 31:return b.yytext=e(1,2).replace(/\\"/g,'"'),80;case 32:return b.yytext=e(1,2).replace(/\\'/g,"'"),80;case 33:return 85;case 34:return 82;case 35:return 82;case 36:return 83;case 37:return 84;case 38:return 81;case 39:return 75;case 40:return 77;case 41:return 72;case 42:return b.yytext=b.yytext.replace(/\\([\\\]])/g,"$1"),72;case 43:return"INVALID";case 44:return 5}},a.rules=[/^(?:[^\x00]*?(?=(\{\{)))/,/^(?:[^\x00]+)/,/^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/,/^(?:\{\{\{\{(?=[^\/]))/,/^(?:\{\{\{\{\/[^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=[=}\s\/.])\}\}\}\})/,/^(?:[^\x00]*?(?=(\{\{\{\{)))/,/^(?:[\s\S]*?--(~)?\}\})/,/^(?:\()/,/^(?:\))/,/^(?:\{\{\{\{)/,/^(?:\}\}\}\})/,/^(?:\{\{(~)?>)/,/^(?:\{\{(~)?#>)/,/^(?:\{\{(~)?#\*?)/,/^(?:\{\{(~)?\/)/,/^(?:\{\{(~)?\^\s*(~)?\}\})/,/^(?:\{\{(~)?\s*else\s*(~)?\}\})/,/^(?:\{\{(~)?\^)/,/^(?:\{\{(~)?\s*else\b)/,/^(?:\{\{(~)?\{)/,/^(?:\{\{(~)?&)/,/^(?:\{\{(~)?!--)/,/^(?:\{\{(~)?![\s\S]*?\}\})/,/^(?:\{\{(~)?\*?)/,/^(?:=)/,/^(?:\.\.)/,/^(?:\.(?=([=~}\s\/.)|])))/,/^(?:[\/.])/,/^(?:\s+)/,/^(?:\}(~)?\}\})/,/^(?:(~)?\}\})/,/^(?:"(\\["]|[^"])*")/,/^(?:'(\\[']|[^'])*')/,/^(?:@)/,/^(?:true(?=([~}\s)])))/,/^(?:false(?=([~}\s)])))/,/^(?:undefined(?=([~}\s)])))/,/^(?:null(?=([~}\s)])))/,/^(?:-?[0-9]+(?:\.[0-9]+)?(?=([~}\s)])))/,/^(?:as\s+\|)/,/^(?:\|)/,/^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)|]))))/,/^(?:\[(\\\]|[^\]])*\])/,/^(?:.)/,/^(?:$)/],a.conditions={mu:{rules:[7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44],inclusive:!1},emu:{rules:[2],inclusive:!1},com:{rules:[6],inclusive:!1},raw:{rules:[3,4,5],inclusive:!1},INITIAL:{rules:[0,1,44],inclusive:!0}},a}();return b.lexer=c,a.prototype=b,b.Parser=a,new a}();b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(){var a=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.options=a}function e(a,b,c){void 0===b&&(b=a.length);var d=a[b-1],e=a[b-2];return d?"ContentStatement"===d.type?(e||!c?/\r?\n\s*?$/:/(^|\r?\n)\s*?$/).test(d.original):void 0:c}function f(a,b,c){void 0===b&&(b=-1);var d=a[b+1],e=a[b+2];return d?"ContentStatement"===d.type?(e||!c?/^\s*?\r?\n/:/^\s*?(\r?\n|$)/).test(d.original):void 0:c}function g(a,b,c){var d=a[null==b?0:b+1];if(d&&"ContentStatement"===d.type&&(c||!d.rightStripped)){var e=d.value;d.value=d.value.replace(c?/^\s+/:/^[ \t]*\r?\n?/,""),d.rightStripped=d.value!==e}}function h(a,b,c){var d=a[null==b?a.length-1:b-1];if(d&&"ContentStatement"===d.type&&(c||!d.leftStripped)){var e=d.value;return d.value=d.value.replace(c?/\s+$/:/[ \t]+$/,""),d.leftStripped=d.value!==e,d.leftStripped}}var i=c(1)["default"];b.__esModule=!0;var j=c(39),k=i(j);d.prototype=new k["default"],d.prototype.Program=function(a){var b=!this.options.ignoreStandalone,c=!this.isRootSeen;this.isRootSeen=!0;for(var d=a.body,i=0,j=d.length;i<j;i++){var k=d[i],l=this.accept(k);if(l){var m=e(d,i,c),n=f(d,i,c),o=l.openStandalone&&m,p=l.closeStandalone&&n,q=l.inlineStandalone&&m&&n;l.close&&g(d,i,!0),l.open&&h(d,i,!0),b&&q&&(g(d,i),h(d,i)&&"PartialStatement"===k.type&&(k.indent=/([ \t]+$)/.exec(d[i-1].original)[1])),b&&o&&(g((k.program||k.inverse).body),h(d,i)),b&&p&&(g(d,i),h((k.inverse||k.program).body))}}return a},d.prototype.BlockStatement=d.prototype.DecoratorBlock=d.prototype.PartialBlockStatement=function(a){this.accept(a.program),this.accept(a.inverse);var b=a.program||a.inverse,c=a.program&&a.inverse,d=c,i=c;if(c&&c.chained)for(d=c.body[0].program;i.chained;)i=i.body[i.body.length-1].program;var j={open:a.openStrip.open,close:a.closeStrip.close,openStandalone:f(b.body),closeStandalone:e((d||b).body)};if(a.openStrip.close&&g(b.body,null,!0),c){var k=a.inverseStrip;k.open&&h(b.body,null,!0),k.close&&g(d.body,null,!0),a.closeStrip.open&&h(i.body,null,!0),!this.options.ignoreStandalone&&e(b.body)&&f(d.body)&&(h(b.body),g(d.body))}else a.closeStrip.open&&h(b.body,null,!0);return j},d.prototype.Decorator=d.prototype.MustacheStatement=function(a){return a.strip},d.prototype.PartialStatement=d.prototype.CommentStatement=function(a){var b=a.strip||{};return{inlineStandalone:!0,open:b.open,close:b.close}},b["default"]=d,a.exports=b["default"]},function(a,b,c){"use strict";function d(){this.parents=[]}function e(a){this.acceptRequired(a,"path"),this.acceptArray(a.params),this.acceptKey(a,"hash")}function f(a){e.call(this,a),this.acceptKey(a,"program"),this.acceptKey(a,"inverse")}function g(a){this.acceptRequired(a,"name"),this.acceptArray(a.params),this.acceptKey(a,"hash")}var h=c(1)["default"];b.__esModule=!0;var i=c(6),j=h(i);d.prototype={constructor:d,mutating:!1,acceptKey:function(a,b){var c=this.accept(a[b]);if(this.mutating){if(c&&!d.prototype[c.type])throw new j["default"]('Unexpected node type "'+c.type+'" found when accepting '+b+" on "+a.type);a[b]=c}},acceptRequired:function(a,b){if(this.acceptKey(a,b),!a[b])throw new j["default"](a.type+" requires "+b)},acceptArray:function(a){for(var b=0,c=a.length;b<c;b++)this.acceptKey(a,b),a[b]||(a.splice(b,1),b--,c--)},accept:function(a){if(a){if(!this[a.type])throw new j["default"]("Unknown type: "+a.type,a);this.current&&this.parents.unshift(this.current),this.current=a;var b=this[a.type](a);return this.current=this.parents.shift(),!this.mutating||b?b:b!==!1?a:void 0}},Program:function(a){this.acceptArray(a.body)},MustacheStatement:e,Decorator:e,BlockStatement:f,DecoratorBlock:f,PartialStatement:g,PartialBlockStatement:function(a){g.call(this,a),this.acceptKey(a,"program")},ContentStatement:function(){},CommentStatement:function(){},SubExpression:e,PathExpression:function(){},StringLiteral:function(){},NumberLiteral:function(){},BooleanLiteral:function(){},UndefinedLiteral:function(){},NullLiteral:function(){},Hash:function(a){this.acceptArray(a.pairs)},HashPair:function(a){this.acceptRequired(a,"value")}},b["default"]=d,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b){if(b=b.path?b.path.original:b,a.path.original!==b){var c={loc:a.path.loc};throw new q["default"](a.path.original+" doesn't match "+b,c)}}function e(a,b){this.source=a,this.start={line:b.first_line,column:b.first_column},this.end={line:b.last_line,column:b.last_column}}function f(a){return/^\[.*\]$/.test(a)?a.substr(1,a.length-2):a}function g(a,b){return{open:"~"===a.charAt(2),close:"~"===b.charAt(b.length-3)}}function h(a){return a.replace(/^\{\{~?\!-?-?/,"").replace(/-?-?~?\}\}$/,"")}function i(a,b,c){c=this.locInfo(c);for(var d=a?"@":"",e=[],f=0,g="",h=0,i=b.length;h<i;h++){var j=b[h].part,k=b[h].original!==j;if(d+=(b[h].separator||"")+j,k||".."!==j&&"."!==j&&"this"!==j)e.push(j);else{if(e.length>0)throw new q["default"]("Invalid path: "+d,{loc:c});".."===j&&(f++,g+="../")}}return{type:"PathExpression",data:a,depth:f,parts:e,original:d,loc:c}}function j(a,b,c,d,e,f){var g=d.charAt(3)||d.charAt(2),h="{"!==g&&"&"!==g,i=/\*/.test(d);return{type:i?"Decorator":"MustacheStatement",path:a,params:b,hash:c,escaped:h,strip:e,loc:this.locInfo(f)}}function k(a,b,c,e){d(a,c),e=this.locInfo(e);var f={type:"Program",body:b,strip:{},loc:e};return{type:"BlockStatement",path:a.path,params:a.params,hash:a.hash,program:f,openStrip:{},inverseStrip:{},closeStrip:{},loc:e}}function l(a,b,c,e,f,g){e&&e.path&&d(a,e);var h=/\*/.test(a.open);b.blockParams=a.blockParams;var i=void 0,j=void 0;if(c){if(h)throw new q["default"]("Unexpected inverse block on decorator",c);c.chain&&(c.program.body[0].closeStrip=e.strip),j=c.strip,i=c.program}return f&&(f=i,i=b,b=f),{type:h?"DecoratorBlock":"BlockStatement",path:a.path,params:a.params,hash:a.hash,program:b,inverse:i,openStrip:a.strip,inverseStrip:j,closeStrip:e&&e.strip,loc:this.locInfo(g)}}function m(a,b){if(!b&&a.length){var c=a[0].loc,d=a[a.length-1].loc;c&&d&&(b={source:c.source,start:{line:c.start.line,column:c.start.column},end:{line:d.end.line,column:d.end.column}})}return{type:"Program",body:a,strip:{},loc:b}}function n(a,b,c,e){return d(a,c),{type:"PartialBlockStatement",name:a.path,params:a.params,hash:a.hash,program:b,openStrip:a.strip,closeStrip:c&&c.strip,loc:this.locInfo(e)}}var o=c(1)["default"];b.__esModule=!0,b.SourceLocation=e,b.id=f,b.stripFlags=g,b.stripComment=h,b.preparePath=i,b.prepareMustache=j,b.prepareRawBlock=k,b.prepareBlock=l,b.prepareProgram=m,b.preparePartialBlock=n;var p=c(6),q=o(p)},function(a,b,c){"use strict";function d(){}function e(a,b,c){if(null==a||"string"!=typeof a&&"Program"!==a.type)throw new k["default"]("You must pass a string or Handlebars AST to Handlebars.precompile. You passed "+a);b=b||{},"data"in b||(b.data=!0),b.compat&&(b.useDepths=!0);var d=c.parse(a,b),e=(new c.Compiler).compile(d,b);return(new c.JavaScriptCompiler).compile(e,b)}function f(a,b,c){function d(){var d=c.parse(a,b),e=(new c.Compiler).compile(d,b),f=(new c.JavaScriptCompiler).compile(e,b,void 0,!0);return c.template(f)}function e(a,b){return f||(f=d()),f.call(this,a,b)}if(void 0===b&&(b={}),null==a||"string"!=typeof a&&"Program"!==a.type)throw new k["default"]("You must pass a string or Handlebars AST to Handlebars.compile. You passed "+a);b=l.extend({},b),"data"in b||(b.data=!0),b.compat&&(b.useDepths=!0);var f=void 0;return e._setup=function(a){return f||(f=d()),f._setup(a)},e._child=function(a,b,c,e){return f||(f=d()),f._child(a,b,c,e)},e}function g(a,b){if(a===b)return!0;if(l.isArray(a)&&l.isArray(b)&&a.length===b.length){for(var c=0;c<a.length;c++)if(!g(a[c],b[c]))return!1;return!0}}function h(a){if(!a.path.parts){var b=a.path;a.path={type:"PathExpression",data:!1,depth:0,parts:[b.original+""],original:b.original+"",loc:b.loc}}}var i=c(1)["default"];b.__esModule=!0,b.Compiler=d,b.precompile=e,b.compile=f;var j=c(6),k=i(j),l=c(5),m=c(35),n=i(m),o=[].slice;d.prototype={compiler:d,equals:function(a){var b=this.opcodes.length;if(a.opcodes.length!==b)return!1;for(var c=0;c<b;c++){var d=this.opcodes[c],e=a.opcodes[c];if(d.opcode!==e.opcode||!g(d.args,e.args))return!1}b=this.children.length;for(var c=0;c<b;c++)if(!this.children[c].equals(a.children[c]))return!1;return!0},guid:0,compile:function(a,b){this.sourceNode=[],this.opcodes=[],this.children=[],this.options=b,this.stringParams=b.stringParams,this.trackIds=b.trackIds,b.blockParams=b.blockParams||[];var c=b.knownHelpers;if(b.knownHelpers={helperMissing:!0,blockHelperMissing:!0,each:!0,"if":!0,unless:!0,"with":!0,log:!0,lookup:!0},c)for(var d in c)d in c&&(this.options.knownHelpers[d]=c[d]);return this.accept(a)},compileProgram:function(a){var b=new this.compiler,c=b.compile(a,this.options),d=this.guid++;return this.usePartial=this.usePartial||c.usePartial,this.children[d]=c,this.useDepths=this.useDepths||c.useDepths,d},accept:function(a){if(!this[a.type])throw new k["default"]("Unknown type: "+a.type,a);this.sourceNode.unshift(a);var b=this[a.type](a);return this.sourceNode.shift(),b},Program:function(a){this.options.blockParams.unshift(a.blockParams);for(var b=a.body,c=b.length,d=0;d<c;d++)this.accept(b[d]);return this.options.blockParams.shift(),this.isSimple=1===c,this.blockParams=a.blockParams?a.blockParams.length:0,this},BlockStatement:function(a){h(a);var b=a.program,c=a.inverse;b=b&&this.compileProgram(b),c=c&&this.compileProgram(c);var d=this.classifySexpr(a);"helper"===d?this.helperSexpr(a,b,c):"simple"===d?(this.simpleSexpr(a),this.opcode("pushProgram",b),this.opcode("pushProgram",c),this.opcode("emptyHash"),this.opcode("blockValue",a.path.original)):(this.ambiguousSexpr(a,b,c),this.opcode("pushProgram",b),this.opcode("pushProgram",c),this.opcode("emptyHash"),this.opcode("ambiguousBlockValue")),this.opcode("append")},DecoratorBlock:function(a){var b=a.program&&this.compileProgram(a.program),c=this.setupFullMustacheParams(a,b,void 0),d=a.path;this.useDecorators=!0,this.opcode("registerDecorator",c.length,d.original)},PartialStatement:function(a){this.usePartial=!0;var b=a.program;b&&(b=this.compileProgram(a.program));var c=a.params;if(c.length>1)throw new k["default"]("Unsupported number of partial arguments: "+c.length,a);c.length||(this.options.explicitPartialContext?this.opcode("pushLiteral","undefined"):c.push({type:"PathExpression",parts:[],depth:0}));var d=a.name.original,e="SubExpression"===a.name.type;e&&this.accept(a.name),this.setupFullMustacheParams(a,b,void 0,!0);var f=a.indent||"";this.options.preventIndent&&f&&(this.opcode("appendContent",f),f=""),this.opcode("invokePartial",e,d,f),this.opcode("append")},PartialBlockStatement:function(a){this.PartialStatement(a)},MustacheStatement:function(a){this.SubExpression(a),a.escaped&&!this.options.noEscape?this.opcode("appendEscaped"):this.opcode("append")},Decorator:function(a){this.DecoratorBlock(a)},ContentStatement:function(a){a.value&&this.opcode("appendContent",a.value)},CommentStatement:function(){},SubExpression:function(a){h(a);var b=this.classifySexpr(a);"simple"===b?this.simpleSexpr(a):"helper"===b?this.helperSexpr(a):this.ambiguousSexpr(a)},ambiguousSexpr:function(a,b,c){var d=a.path,e=d.parts[0],f=null!=b||null!=c;this.opcode("getContext",d.depth),this.opcode("pushProgram",b),this.opcode("pushProgram",c),d.strict=!0,this.accept(d),this.opcode("invokeAmbiguous",e,f)},simpleSexpr:function(a){var b=a.path;b.strict=!0,this.accept(b),this.opcode("resolvePossibleLambda")},helperSexpr:function(a,b,c){var d=this.setupFullMustacheParams(a,b,c),e=a.path,f=e.parts[0];if(this.options.knownHelpers[f])this.opcode("invokeKnownHelper",d.length,f);else{if(this.options.knownHelpersOnly)throw new k["default"]("You specified knownHelpersOnly, but used the unknown helper "+f,a);e.strict=!0,e.falsy=!0,this.accept(e),this.opcode("invokeHelper",d.length,e.original,n["default"].helpers.simpleId(e))}},PathExpression:function(a){this.addDepth(a.depth),this.opcode("getContext",a.depth);var b=a.parts[0],c=n["default"].helpers.scopedId(a),d=!a.depth&&!c&&this.blockParamIndex(b);d?this.opcode("lookupBlockParam",d,a.parts):b?a.data?(this.options.data=!0,this.opcode("lookupData",a.depth,a.parts,a.strict)):this.opcode("lookupOnContext",a.parts,a.falsy,a.strict,c):this.opcode("pushContext")},StringLiteral:function(a){this.opcode("pushString",a.value)},NumberLiteral:function(a){this.opcode("pushLiteral",a.value)},BooleanLiteral:function(a){this.opcode("pushLiteral",a.value)},UndefinedLiteral:function(){this.opcode("pushLiteral","undefined")},NullLiteral:function(){this.opcode("pushLiteral","null")},Hash:function(a){var b=a.pairs,c=0,d=b.length;for(this.opcode("pushHash");c<d;c++)this.pushParam(b[c].value);for(;c--;)this.opcode("assignToHash",b[c].key);this.opcode("popHash")},opcode:function(a){this.opcodes.push({opcode:a,args:o.call(arguments,1),loc:this.sourceNode[0].loc})},addDepth:function(a){a&&(this.useDepths=!0)},classifySexpr:function(a){var b=n["default"].helpers.simpleId(a.path),c=b&&!!this.blockParamIndex(a.path.parts[0]),d=!c&&n["default"].helpers.helperExpression(a),e=!c&&(d||b);if(e&&!d){var f=a.path.parts[0],g=this.options;g.knownHelpers[f]?d=!0:g.knownHelpersOnly&&(e=!1)}return d?"helper":e?"ambiguous":"simple"},pushParams:function(a){for(var b=0,c=a.length;b<c;b++)this.pushParam(a[b])},pushParam:function(a){var b=null!=a.value?a.value:a.original||"";if(this.stringParams)b.replace&&(b=b.replace(/^(\.?\.\/)*/g,"").replace(/\//g,".")),a.depth&&this.addDepth(a.depth),this.opcode("getContext",a.depth||0),this.opcode("pushStringParam",b,a.type),"SubExpression"===a.type&&this.accept(a);else{if(this.trackIds){var c=void 0;if(!a.parts||n["default"].helpers.scopedId(a)||a.depth||(c=this.blockParamIndex(a.parts[0])),c){var d=a.parts.slice(1).join(".");this.opcode("pushId","BlockParam",c,d)}else b=a.original||b,b.replace&&(b=b.replace(/^this(?:\.|$)/,"").replace(/^\.\//,"").replace(/^\.$/,"")),this.opcode("pushId",a.type,b)}this.accept(a)}},setupFullMustacheParams:function(a,b,c,d){var e=a.params;return this.pushParams(e),this.opcode("pushProgram",b),this.opcode("pushProgram",c),a.hash?this.accept(a.hash):this.opcode("emptyHash",d),e},blockParamIndex:function(a){for(var b=0,c=this.options.blockParams.length;b<c;b++){var d=this.options.blockParams[b],e=d&&l.indexOf(d,a);if(d&&e>=0)return[b,e]}}}},function(a,b,c){"use strict";function d(a){this.value=a}function e(){}function f(a,b,c,d){var e=b.popStack(),f=0,g=c.length;for(a&&g--;f<g;f++)e=b.nameLookup(e,c[f],d);return a?[b.aliasable("container.strict"),"(",e,", ",b.quotedString(c[f]),")"]:e}var g=c(1)["default"];b.__esModule=!0;var h=c(4),i=c(6),j=g(i),k=c(5),l=c(43),m=g(l);e.prototype={nameLookup:function(a,b){return e.isValidJavaScriptVariableName(b)?[a,".",b]:[a,"[",JSON.stringify(b),"]"]},depthedLookup:function(a){return[this.aliasable("container.lookup"),'(depths, "',a,'")']},compilerInfo:function(){var a=h.COMPILER_REVISION,b=h.REVISION_CHANGES[a];return[a,b]},appendToBuffer:function(a,b,c){return k.isArray(a)||(a=[a]),a=this.source.wrap(a,b),this.environment.isSimple?["return ",a,";"]:c?["buffer += ",a,";"]:(a.appendToBuffer=!0,a)},initializeBuffer:function(){return this.quotedString("")},compile:function(a,b,c,d){this.environment=a,this.options=b,this.stringParams=this.options.stringParams,this.trackIds=this.options.trackIds,this.precompile=!d,this.name=this.environment.name,this.isChild=!!c,this.context=c||{decorators:[],programs:[],environments:[]},this.preamble(),this.stackSlot=0,this.stackVars=[],this.aliases={},this.registers={list:[]},this.hashes=[],this.compileStack=[],this.inlineStack=[],this.blockParams=[],this.compileChildren(a,b),this.useDepths=this.useDepths||a.useDepths||a.useDecorators||this.options.compat,this.useBlockParams=this.useBlockParams||a.useBlockParams;var e=a.opcodes,f=void 0,g=void 0,h=void 0,i=void 0;for(h=0,i=e.length;h<i;h++)f=e[h],this.source.currentLocation=f.loc,g=g||f.loc,this[f.opcode].apply(this,f.args);if(this.source.currentLocation=g,this.pushSource(""),this.stackSlot||this.inlineStack.length||this.compileStack.length)throw new j["default"]("Compile completed with content left on stack");this.decorators.isEmpty()?this.decorators=void 0:(this.useDecorators=!0,this.decorators.prepend("var decorators = container.decorators;\n"),this.decorators.push("return fn;"),d?this.decorators=Function.apply(this,["fn","props","container","depth0","data","blockParams","depths",this.decorators.merge()]):(this.decorators.prepend("function(fn, props, container, depth0, data, blockParams, depths) {\n"),this.decorators.push("}\n"),this.decorators=this.decorators.merge()));var k=this.createFunctionContext(d);if(this.isChild)return k;var l={compiler:this.compilerInfo(),main:k};this.decorators&&(l.main_d=this.decorators,l.useDecorators=!0);var m=this.context,n=m.programs,o=m.decorators;for(h=0,i=n.length;h<i;h++)n[h]&&(l[h]=n[h],o[h]&&(l[h+"_d"]=o[h],l.useDecorators=!0));return this.environment.usePartial&&(l.usePartial=!0),this.options.data&&(l.useData=!0),this.useDepths&&(l.useDepths=!0),this.useBlockParams&&(l.useBlockParams=!0),this.options.compat&&(l.compat=!0),d?l.compilerOptions=this.options:(l.compiler=JSON.stringify(l.compiler),this.source.currentLocation={start:{line:1,column:0}},l=this.objectLiteral(l),b.srcName?(l=l.toStringWithSourceMap({file:b.destName}),l.map=l.map&&l.map.toString()):l=l.toString()),l},preamble:function(){this.lastContext=0,this.source=new m["default"](this.options.srcName),this.decorators=new m["default"](this.options.srcName)},createFunctionContext:function(a){var b="",c=this.stackVars.concat(this.registers.list);c.length>0&&(b+=", "+c.join(", "));var d=0;for(var e in this.aliases){var f=this.aliases[e];this.aliases.hasOwnProperty(e)&&f.children&&f.referenceCount>1&&(b+=", alias"+ ++d+"="+e,f.children[0]="alias"+d)}var g=["container","depth0","helpers","partials","data"];(this.useBlockParams||this.useDepths)&&g.push("blockParams"),this.useDepths&&g.push("depths");var h=this.mergeSource(b);return a?(g.push(h),Function.apply(this,g)):this.source.wrap(["function(",g.join(","),") {\n ",h,"}"])},mergeSource:function(a){var b=this.environment.isSimple,c=!this.forceBuffer,d=void 0,e=void 0,f=void 0,g=void 0;return this.source.each(function(a){a.appendToBuffer?(f?a.prepend(" + "):f=a,g=a):(f&&(e?f.prepend("buffer += "):d=!0,g.add(";"),f=g=void 0),e=!0,b||(c=!1))}),c?f?(f.prepend("return "),g.add(";")):e||this.source.push('return "";'):(a+=", buffer = "+(d?"":this.initializeBuffer()),f?(f.prepend("return buffer + "),g.add(";")):this.source.push("return buffer;")),a&&this.source.prepend("var "+a.substring(2)+(d?"":";\n")),this.source.merge()},blockValue:function(a){var b=this.aliasable("helpers.blockHelperMissing"),c=[this.contextName(0)];this.setupHelperArgs(a,0,c);var d=this.popStack();c.splice(1,0,d),this.push(this.source.functionCall(b,"call",c))},ambiguousBlockValue:function(){var a=this.aliasable("helpers.blockHelperMissing"),b=[this.contextName(0)];this.setupHelperArgs("",0,b,!0),this.flushInline();var c=this.topStack();b.splice(1,0,c),this.pushSource(["if (!",this.lastHelper,") { ",c," = ",this.source.functionCall(a,"call",b),"}"])},appendContent:function(a){this.pendingContent?a=this.pendingContent+a:this.pendingLocation=this.source.currentLocation,this.pendingContent=a},append:function(){if(this.isInline())this.replaceStack(function(a){return[" != null ? ",a,' : ""']}),this.pushSource(this.appendToBuffer(this.popStack()));else{var a=this.popStack();this.pushSource(["if (",a," != null) { ",this.appendToBuffer(a,void 0,!0)," }"]),this.environment.isSimple&&this.pushSource(["else { ",this.appendToBuffer("''",void 0,!0)," }"])}},appendEscaped:function(){this.pushSource(this.appendToBuffer([this.aliasable("container.escapeExpression"),"(",this.popStack(),")"]))},getContext:function(a){this.lastContext=a},pushContext:function(){this.pushStackLiteral(this.contextName(this.lastContext))},lookupOnContext:function(a,b,c,d){var e=0;d||!this.options.compat||this.lastContext?this.pushContext():this.push(this.depthedLookup(a[e++])),this.resolvePath("context",a,e,b,c)},lookupBlockParam:function(a,b){this.useBlockParams=!0,this.push(["blockParams[",a[0],"][",a[1],"]"]),this.resolvePath("context",b,1)},lookupData:function(a,b,c){a?this.pushStackLiteral("container.data(data, "+a+")"):this.pushStackLiteral("data"),this.resolvePath("data",b,0,!0,c)},resolvePath:function(a,b,c,d,e){var g=this;if(this.options.strict||this.options.assumeObjects)return void this.push(f(this.options.strict&&e,this,b,a));for(var h=b.length;c<h;c++)this.replaceStack(function(e){
  107884. var f=g.nameLookup(e,b[c],a);return d?[" && ",f]:[" != null ? ",f," : ",e]})},resolvePossibleLambda:function(){this.push([this.aliasable("container.lambda"),"(",this.popStack(),", ",this.contextName(0),")"])},pushStringParam:function(a,b){this.pushContext(),this.pushString(b),"SubExpression"!==b&&("string"==typeof a?this.pushString(a):this.pushStackLiteral(a))},emptyHash:function(a){this.trackIds&&this.push("{}"),this.stringParams&&(this.push("{}"),this.push("{}")),this.pushStackLiteral(a?"undefined":"{}")},pushHash:function(){this.hash&&this.hashes.push(this.hash),this.hash={values:[],types:[],contexts:[],ids:[]}},popHash:function(){var a=this.hash;this.hash=this.hashes.pop(),this.trackIds&&this.push(this.objectLiteral(a.ids)),this.stringParams&&(this.push(this.objectLiteral(a.contexts)),this.push(this.objectLiteral(a.types))),this.push(this.objectLiteral(a.values))},pushString:function(a){this.pushStackLiteral(this.quotedString(a))},pushLiteral:function(a){this.pushStackLiteral(a)},pushProgram:function(a){null!=a?this.pushStackLiteral(this.programExpression(a)):this.pushStackLiteral(null)},registerDecorator:function(a,b){var c=this.nameLookup("decorators",b,"decorator"),d=this.setupHelperArgs(b,a);this.decorators.push(["fn = ",this.decorators.functionCall(c,"",["fn","props","container",d])," || fn;"])},invokeHelper:function(a,b,c){var d=this.popStack(),e=this.setupHelper(a,b),f=c?[e.name," || "]:"",g=["("].concat(f,d);this.options.strict||g.push(" || ",this.aliasable("helpers.helperMissing")),g.push(")"),this.push(this.source.functionCall(g,"call",e.callParams))},invokeKnownHelper:function(a,b){var c=this.setupHelper(a,b);this.push(this.source.functionCall(c.name,"call",c.callParams))},invokeAmbiguous:function(a,b){this.useRegister("helper");var c=this.popStack();this.emptyHash();var d=this.setupHelper(0,a,b),e=this.lastHelper=this.nameLookup("helpers",a,"helper"),f=["(","(helper = ",e," || ",c,")"];this.options.strict||(f[0]="(helper = ",f.push(" != null ? helper : ",this.aliasable("helpers.helperMissing"))),this.push(["(",f,d.paramsInit?["),(",d.paramsInit]:[],"),","(typeof helper === ",this.aliasable('"function"')," ? ",this.source.functionCall("helper","call",d.callParams)," : helper))"])},invokePartial:function(a,b,c){var d=[],e=this.setupParams(b,1,d);a&&(b=this.popStack(),delete e.name),c&&(e.indent=JSON.stringify(c)),e.helpers="helpers",e.partials="partials",e.decorators="container.decorators",a?d.unshift(b):d.unshift(this.nameLookup("partials",b,"partial")),this.options.compat&&(e.depths="depths"),e=this.objectLiteral(e),d.push(e),this.push(this.source.functionCall("container.invokePartial","",d))},assignToHash:function(a){var b=this.popStack(),c=void 0,d=void 0,e=void 0;this.trackIds&&(e=this.popStack()),this.stringParams&&(d=this.popStack(),c=this.popStack());var f=this.hash;c&&(f.contexts[a]=c),d&&(f.types[a]=d),e&&(f.ids[a]=e),f.values[a]=b},pushId:function(a,b,c){"BlockParam"===a?this.pushStackLiteral("blockParams["+b[0]+"].path["+b[1]+"]"+(c?" + "+JSON.stringify("."+c):"")):"PathExpression"===a?this.pushString(b):"SubExpression"===a?this.pushStackLiteral("true"):this.pushStackLiteral("null")},compiler:e,compileChildren:function(a,b){for(var c=a.children,d=void 0,e=void 0,f=0,g=c.length;f<g;f++){d=c[f],e=new this.compiler;var h=this.matchExistingProgram(d);if(null==h){this.context.programs.push("");var i=this.context.programs.length;d.index=i,d.name="program"+i,this.context.programs[i]=e.compile(d,b,this.context,!this.precompile),this.context.decorators[i]=e.decorators,this.context.environments[i]=d,this.useDepths=this.useDepths||e.useDepths,this.useBlockParams=this.useBlockParams||e.useBlockParams,d.useDepths=this.useDepths,d.useBlockParams=this.useBlockParams}else d.index=h.index,d.name="program"+h.index,this.useDepths=this.useDepths||h.useDepths,this.useBlockParams=this.useBlockParams||h.useBlockParams}},matchExistingProgram:function(a){for(var b=0,c=this.context.environments.length;b<c;b++){var d=this.context.environments[b];if(d&&d.equals(a))return d}},programExpression:function(a){var b=this.environment.children[a],c=[b.index,"data",b.blockParams];return(this.useBlockParams||this.useDepths)&&c.push("blockParams"),this.useDepths&&c.push("depths"),"container.program("+c.join(", ")+")"},useRegister:function(a){this.registers[a]||(this.registers[a]=!0,this.registers.list.push(a))},push:function(a){return a instanceof d||(a=this.source.wrap(a)),this.inlineStack.push(a),a},pushStackLiteral:function(a){this.push(new d(a))},pushSource:function(a){this.pendingContent&&(this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent),this.pendingLocation)),this.pendingContent=void 0),a&&this.source.push(a)},replaceStack:function(a){var b=["("],c=void 0,e=void 0,f=void 0;if(!this.isInline())throw new j["default"]("replaceStack on non-inline");var g=this.popStack(!0);if(g instanceof d)c=[g.value],b=["(",c],f=!0;else{e=!0;var h=this.incrStack();b=["((",this.push(h)," = ",g,")"],c=this.topStack()}var i=a.call(this,c);f||this.popStack(),e&&this.stackSlot--,this.push(b.concat(i,")"))},incrStack:function(){return this.stackSlot++,this.stackSlot>this.stackVars.length&&this.stackVars.push("stack"+this.stackSlot),this.topStackName()},topStackName:function(){return"stack"+this.stackSlot},flushInline:function(){var a=this.inlineStack;this.inlineStack=[];for(var b=0,c=a.length;b<c;b++){var e=a[b];if(e instanceof d)this.compileStack.push(e);else{var f=this.incrStack();this.pushSource([f," = ",e,";"]),this.compileStack.push(f)}}},isInline:function(){return this.inlineStack.length},popStack:function(a){var b=this.isInline(),c=(b?this.inlineStack:this.compileStack).pop();if(!a&&c instanceof d)return c.value;if(!b){if(!this.stackSlot)throw new j["default"]("Invalid stack pop");this.stackSlot--}return c},topStack:function(){var a=this.isInline()?this.inlineStack:this.compileStack,b=a[a.length-1];return b instanceof d?b.value:b},contextName:function(a){return this.useDepths&&a?"depths["+a+"]":"depth"+a},quotedString:function(a){return this.source.quotedString(a)},objectLiteral:function(a){return this.source.objectLiteral(a)},aliasable:function(a){var b=this.aliases[a];return b?(b.referenceCount++,b):(b=this.aliases[a]=this.source.wrap(a),b.aliasable=!0,b.referenceCount=1,b)},setupHelper:function(a,b,c){var d=[],e=this.setupHelperArgs(b,a,d,c),f=this.nameLookup("helpers",b,"helper"),g=this.aliasable(this.contextName(0)+" != null ? "+this.contextName(0)+" : (container.nullContext || {})");return{params:d,paramsInit:e,name:f,callParams:[g].concat(d)}},setupParams:function(a,b,c){var d={},e=[],f=[],g=[],h=!c,i=void 0;h&&(c=[]),d.name=this.quotedString(a),d.hash=this.popStack(),this.trackIds&&(d.hashIds=this.popStack()),this.stringParams&&(d.hashTypes=this.popStack(),d.hashContexts=this.popStack());var j=this.popStack(),k=this.popStack();(k||j)&&(d.fn=k||"container.noop",d.inverse=j||"container.noop");for(var l=b;l--;)i=this.popStack(),c[l]=i,this.trackIds&&(g[l]=this.popStack()),this.stringParams&&(f[l]=this.popStack(),e[l]=this.popStack());return h&&(d.args=this.source.generateArray(c)),this.trackIds&&(d.ids=this.source.generateArray(g)),this.stringParams&&(d.types=this.source.generateArray(f),d.contexts=this.source.generateArray(e)),this.options.data&&(d.data="data"),this.useBlockParams&&(d.blockParams="blockParams"),d},setupHelperArgs:function(a,b,c,d){var e=this.setupParams(a,b,c);return e=this.objectLiteral(e),d?(this.useRegister("options"),c.push("options"),["options=",e]):c?(c.push(e),""):e}},function(){for(var a="break else new var case finally return void catch for switch while continue function this with default if throw delete in try do instanceof typeof abstract enum int short boolean export interface static byte extends long super char final native synchronized class float package throws const goto private transient debugger implements protected volatile double import public let yield await null true false".split(" "),b=e.RESERVED_WORDS={},c=0,d=a.length;c<d;c++)b[a[c]]=!0}(),e.isValidJavaScriptVariableName=function(a){return!e.RESERVED_WORDS[a]&&/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(a)},b["default"]=e,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b,c){if(f.isArray(a)){for(var d=[],e=0,g=a.length;e<g;e++)d.push(b.wrap(a[e],c));return d}return"boolean"==typeof a||"number"==typeof a?a+"":a}function e(a){this.srcFile=a,this.source=[]}b.__esModule=!0;var f=c(5),g=void 0;try{}catch(h){}g||(g=function(a,b,c,d){this.src="",d&&this.add(d)},g.prototype={add:function(a){f.isArray(a)&&(a=a.join("")),this.src+=a},prepend:function(a){f.isArray(a)&&(a=a.join("")),this.src=a+this.src},toStringWithSourceMap:function(){return{code:this.toString()}},toString:function(){return this.src}}),e.prototype={isEmpty:function(){return!this.source.length},prepend:function(a,b){this.source.unshift(this.wrap(a,b))},push:function(a,b){this.source.push(this.wrap(a,b))},merge:function(){var a=this.empty();return this.each(function(b){a.add([" ",b,"\n"])}),a},each:function(a){for(var b=0,c=this.source.length;b<c;b++)a(this.source[b])},empty:function(){var a=this.currentLocation||{start:{}};return new g(a.start.line,a.start.column,this.srcFile)},wrap:function(a){var b=arguments.length<=1||void 0===arguments[1]?this.currentLocation||{start:{}}:arguments[1];return a instanceof g?a:(a=d(a,this,b),new g(b.start.line,b.start.column,this.srcFile,a))},functionCall:function(a,b,c){return c=this.generateList(c),this.wrap([a,b?"."+b+"(":"(",c,")"])},quotedString:function(a){return'"'+(a+"").replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")+'"'},objectLiteral:function(a){var b=[];for(var c in a)if(a.hasOwnProperty(c)){var e=d(a[c],this);"undefined"!==e&&b.push([this.quotedString(c),":",e])}var f=this.generateList(b);return f.prepend("{"),f.add("}"),f},generateList:function(a){for(var b=this.empty(),c=0,e=a.length;c<e;c++)c&&b.add(","),b.add(d(a[c],this));return b},generateArray:function(a){var b=this.generateList(a);return b.prepend("["),b.add("]"),b}},b["default"]=e,a.exports=b["default"]}])});
  107885. /***/ }),
  107886. /* 32 */
  107887. /***/ (function(module, exports, __webpack_require__) {
  107888. "use strict";
  107889. Object.defineProperty(exports, "__esModule", { value: true });
  107890. /**
  107891. * The EventManager is in charge of registering user interctions with the viewer.
  107892. * It is used in the TemplateManager
  107893. */
  107894. var EventManager = /** @class */ (function () {
  107895. function EventManager(_templateManager) {
  107896. var _this = this;
  107897. this._templateManager = _templateManager;
  107898. this._callbacksContainer = {};
  107899. this._templateManager.onEventTriggered.add(function (eventData) {
  107900. _this._eventTriggered(eventData);
  107901. });
  107902. }
  107903. /**
  107904. * Register a new callback to a specific template.
  107905. * The best example for the usage can be found in the DefaultViewer
  107906. *
  107907. * @param templateName the templateName to register the event to
  107908. * @param callback The callback to be executed
  107909. * @param eventType the type of event to register
  107910. * @param selector an optional selector. if not defined the parent object in the template will be selected
  107911. */
  107912. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  107913. if (!this._callbacksContainer[templateName]) {
  107914. this._callbacksContainer[templateName] = [];
  107915. }
  107916. this._callbacksContainer[templateName].push({
  107917. eventType: eventType,
  107918. callback: callback
  107919. });
  107920. };
  107921. /**
  107922. * This will remove a registered event from the defined template.
  107923. * Each one of the variables apart from the template name are optional, but one must be provided.
  107924. *
  107925. * @param templateName the templateName
  107926. * @param callback the callback to remove (optional)
  107927. * @param eventType the event type to remove (optional)
  107928. * @param selector the selector from which to remove the event (optional)
  107929. */
  107930. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  107931. var callbackDefs = this._callbacksContainer[templateName] || [];
  107932. this._callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  107933. };
  107934. EventManager.prototype._eventTriggered = function (data) {
  107935. var templateName = data.template.name;
  107936. var eventType = data.event.type;
  107937. var selector = data.selector;
  107938. var callbackDefs = this._callbacksContainer[templateName] || [];
  107939. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  107940. callbackDef.callback(data);
  107941. });
  107942. };
  107943. /**
  107944. * Dispose the event manager
  107945. */
  107946. EventManager.prototype.dispose = function () {
  107947. this._callbacksContainer = {};
  107948. };
  107949. return EventManager;
  107950. }());
  107951. exports.EventManager = EventManager;
  107952. /***/ }),
  107953. /* 33 */
  107954. /***/ (function(module, exports, __webpack_require__) {
  107955. "use strict";
  107956. Object.defineProperty(exports, "__esModule", { value: true });
  107957. var mappers_1 = __webpack_require__(3);
  107958. var types_1 = __webpack_require__(34);
  107959. var deepmerge = __webpack_require__(1);
  107960. var babylonjs_1 = __webpack_require__(0);
  107961. /**
  107962. * The configuration loader will load the configuration object from any source and will use the defined mapper to
  107963. * parse the object and return a conform ViewerConfiguration.
  107964. * It is a private member of the scene.
  107965. */
  107966. var ConfigurationLoader = /** @class */ (function () {
  107967. function ConfigurationLoader(_enableCache) {
  107968. if (_enableCache === void 0) { _enableCache = false; }
  107969. this._enableCache = _enableCache;
  107970. this._configurationCache = {};
  107971. this._loadRequests = [];
  107972. }
  107973. /**
  107974. * load a configuration object that is defined in the initial configuration provided.
  107975. * The viewer configuration can extend different types of configuration objects and have an extra configuration defined.
  107976. *
  107977. * @param initConfig the initial configuration that has the definitions of further configuration to load.
  107978. * @param callback an optional callback that will be called sync, if noconfiguration needs to be loaded or configuration is payload-only
  107979. * @returns A promise that delivers the extended viewer configuration, when done.
  107980. */
  107981. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  107982. var _this = this;
  107983. if (initConfig === void 0) { initConfig = {}; }
  107984. var loadedConfig = deepmerge({}, initConfig);
  107985. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  107986. loadedConfig = deepmerge(extendedConfiguration, loadedConfig);
  107987. if (loadedConfig.configuration) {
  107988. var mapperType_1 = "json";
  107989. return Promise.resolve().then(function () {
  107990. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  107991. // a file to load
  107992. var url = '';
  107993. if (typeof loadedConfig.configuration === "string") {
  107994. url = loadedConfig.configuration;
  107995. }
  107996. // if configuration is an object
  107997. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  107998. url = loadedConfig.configuration.url;
  107999. var type = loadedConfig.configuration.mapper;
  108000. // empty string?
  108001. if (!type) {
  108002. // load mapper type from filename / url
  108003. type = loadedConfig.configuration.url.split('.').pop();
  108004. }
  108005. mapperType_1 = type || mapperType_1;
  108006. }
  108007. return _this._loadFile(url);
  108008. }
  108009. else {
  108010. if (typeof loadedConfig.configuration === "object") {
  108011. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  108012. return loadedConfig.configuration.payload || {};
  108013. }
  108014. return {};
  108015. }
  108016. }).then(function (data) {
  108017. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  108018. var parsed = mapper.map(data);
  108019. var merged = deepmerge(loadedConfig, parsed);
  108020. if (callback)
  108021. callback(merged);
  108022. return merged;
  108023. });
  108024. }
  108025. else {
  108026. if (callback)
  108027. callback(loadedConfig);
  108028. return Promise.resolve(loadedConfig);
  108029. }
  108030. };
  108031. /**
  108032. * Dispose the configuration loader. This will cancel file requests, if active.
  108033. */
  108034. ConfigurationLoader.prototype.dispose = function () {
  108035. this._loadRequests.forEach(function (request) {
  108036. request.abort();
  108037. });
  108038. this._loadRequests.length = 0;
  108039. };
  108040. ConfigurationLoader.prototype._loadFile = function (url) {
  108041. var _this = this;
  108042. var cacheReference = this._configurationCache;
  108043. if (this._enableCache && cacheReference[url]) {
  108044. return Promise.resolve(cacheReference[url]);
  108045. }
  108046. return new Promise(function (resolve, reject) {
  108047. var fileRequest = babylonjs_1.Tools.LoadFile(url, function (result) {
  108048. var idx = _this._loadRequests.indexOf(fileRequest);
  108049. if (idx !== -1)
  108050. _this._loadRequests.splice(idx, 1);
  108051. if (_this._enableCache)
  108052. cacheReference[url] = result;
  108053. resolve(result);
  108054. }, undefined, undefined, false, function (request, error) {
  108055. var idx = _this._loadRequests.indexOf(fileRequest);
  108056. if (idx !== -1)
  108057. _this._loadRequests.splice(idx, 1);
  108058. reject(error);
  108059. });
  108060. _this._loadRequests.push(fileRequest);
  108061. });
  108062. };
  108063. return ConfigurationLoader;
  108064. }());
  108065. exports.ConfigurationLoader = ConfigurationLoader;
  108066. /***/ }),
  108067. /* 34 */
  108068. /***/ (function(module, exports, __webpack_require__) {
  108069. "use strict";
  108070. Object.defineProperty(exports, "__esModule", { value: true });
  108071. var minimal_1 = __webpack_require__(35);
  108072. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  108073. var default_1 = __webpack_require__(36);
  108074. exports.defaultConfiguration = default_1.defaultConfiguration;
  108075. var extended_1 = __webpack_require__(41);
  108076. var shadowLight_1 = __webpack_require__(42);
  108077. var environmentMap_1 = __webpack_require__(43);
  108078. var deepmerge = __webpack_require__(1);
  108079. var getConfigurationType = function (types) {
  108080. var config = {};
  108081. var typesSeparated = types.split(",");
  108082. typesSeparated.forEach(function (type) {
  108083. switch (type.trim()) {
  108084. case 'environmentMap':
  108085. config = deepmerge(config, environmentMap_1.environmentMapConfiguration);
  108086. break;
  108087. case 'shadowDirectionalLight':
  108088. config = deepmerge(config, shadowLight_1.shadowDirectionalLightConfiguration);
  108089. break;
  108090. case 'shadowSpotLight':
  108091. config = deepmerge(config, shadowLight_1.shadowSpotlLightConfiguration);
  108092. break;
  108093. case 'extended':
  108094. config = deepmerge(config, extended_1.extendedConfiguration);
  108095. break;
  108096. case 'minimal':
  108097. config = deepmerge(config, minimal_1.minimalConfiguration);
  108098. break;
  108099. case 'none':
  108100. break;
  108101. case 'default':
  108102. default:
  108103. config = deepmerge(config, default_1.defaultConfiguration);
  108104. break;
  108105. }
  108106. if (config.extends) {
  108107. config = deepmerge(config, getConfigurationType(config.extends));
  108108. }
  108109. });
  108110. return config;
  108111. };
  108112. exports.getConfigurationType = getConfigurationType;
  108113. /***/ }),
  108114. /* 35 */
  108115. /***/ (function(module, exports, __webpack_require__) {
  108116. "use strict";
  108117. Object.defineProperty(exports, "__esModule", { value: true });
  108118. exports.minimalConfiguration = {
  108119. version: "0.1",
  108120. templates: {
  108121. main: {
  108122. html: __webpack_require__(11)
  108123. },
  108124. loadingScreen: {
  108125. html: __webpack_require__(12),
  108126. params: {
  108127. backgroundColor: "#000000",
  108128. loadingImage: __webpack_require__(13) //"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAYq0lEQVR4Xu2dCZRcVZnHScAJUZSwjSOIbAJmEAZwQCCMoAInYRGIg8AwegQx7AFzUBBmzAFlE4EAwxz2GRk2w7AnAURZBiEOZgyEQDAQAjmEJqTpNd3V1V3Vmd+/6utKV7/1vnpVXd2p/zn3vOV+27vfu/fd/W3QQAPrBZqbm7fJZrN79vf3T+/r67uf4wO9vb37WXQDIwWtra0Tenp6voQTv5XP56/BkfcR3iLk1g6B7hEeI+zP5V+ZiAbqBZ2dnZ8lV+6Gg87CobfhpOc4byf0FjwYE9DneBkWcXrM2tmzNzTxDdQKJPyETCazI46YgiMuI9zJuXJltuChFIHsP/PSfIfTjU19A2mira1tcxy3ey6XO5vEnkV4kes11XBmENDVj97XOT2O03FmWgMuoNLzGRJva8IUnPkzjjcT/kLoKCZzfQB7XiX8M2G8md7AUJgzJ+Z6e88gZ1xGuj3HsY17PcVkrG9gp7CUF/F8PUvxqdZDrFq1ahNVfKjwTCYxZuDE2wjKlc2WViMePM+HPNsFPOdf22OPblD5OZQHvphnV65cjTMzxaQY3eA5V9OO/hmnm1lSjE7woFsQbiXki4++foHnXkW4mLC1JUl947333tsMY3emqfB9jtPJlXN5U0+bOXPmWCPxgOccSy4+AfqPio+9/oFnbyatbqVE28GSZfjQ1NT0KQzaHMcdyPfyaNoE12HcvdxT29K3Fkv8A2vWrPmcifAFZNtD91yRY+SBZ+9UsMtEgD+jTpeenp6JXI6xpKkuUDqRcA6Kr0Wpens+InQTnIpV6Fdi+BQT64ulS5eOIzefD62na7CeoGcnLCM8ykt5OWlzcPv772/BS/w3nP+K+xU11+DvQe5dcrQlTfWAwbNMb8XA8AyGX80xtLlA6TAJuteMbVhhia1v5VMcr+LWMeoZ4xiYw7q6urbhHbgG+paCkIRQehHu4pO3O5fVydEomF5Ulx548JfVD2wqfKE2I3R3ob/f2GoC1DWhdz7HG3i5j2pvb9+Z24m6HvVZQtYsZFWcowlzePEP4jJdR/OQhxTVpAs9NMXxmZxuZKo8IG4s+v8R2tUFphSBTBWzH+OAFwn/gS3TuN55xYoVqfc6dXd3fwHZ1xFaTX0iyGbwjJqXXAammxP00EXx6UMGEx7ram7+vKnzBZ/87Xiwp40tEdDTgYwlHG/CmadSjO7L+XiialOZAej7POFG2VK0Khngl6Pn8/LL0YEtlFh4n8oDAqvaAYH8tzH2iNDm1IIFn8Ax50G7xtgCAU07CfAG4RHOz+vLZL7e0dGxlYlKHaj8BHo25xgrsfV5wrYH4KmouxV+ZZDnCUdwmXxMGgFvFUVWD+jQuOot6rI0tb4gcfaG9v+MrcAn+wj38gL8C7cObmlp2ZRjOkWYD6ypuAf6zjFHLSJ0c/6YQ813DM/yZXgehreiVgP8cvSfsOeExYsXuzs6n8v9j8mqBRZQmdjXVPuira1NHSpn8UDf4Xu0vd2uCtDzacJOlDDf5ng94X8JTWarB8R1EK7ju7udiYgEz/v3pLFKm4oHUHhh3iZdfshpaEYpA4pvKLLXBujLYKRq71XLhUHg27z12rW9B6L/QhLrWWxRH7nzeDK8awi/5HRTEx0K6MZQ694LHk0DqrgfADkreIYz1q5c+UlTEQzesIuMryrggYQWjNL3RGO7p2tuFMeqjaOidgzyCz1yJMTJ6L6d66WEVCcHIO/dQkI75Chs2g97Hoc3jRz9Lge1ED5l4r0gckqRPB0gTw34t1B+h3IqxZkmrn2SULUa7ezZszdE5xfR9130Xsm5ilrnHrmkQOcKvrkncxqrIiY6wlewbw7BOUfDo/b84zzvj9C7J7eCS0NrUiRKCPjUE7ScMBdlF/B2HqBi0ERXBcuXL99YnQz9fX2ah3Up4UnsWGEmDRuUhoTn+Z5PfvbZZ2N/fuCZRJgnfhNVBu73EZoIKt7l0L2UBsYeDZg016nb5EUCWuXQewinUtTuyq2aTStF14a8SD+VDQVj6hDYxjuXf4Hjl83sSMCmTp8j4FtoMuRQ5dAZcii3kk/0s2bBhxIcBxjxUlib1hWInEDO/6qKV+y4geO5HAMntEE/pq+nZyo0ywsG1SmwL4Orf+0yqGCfmvR73LAn9lAeBjQTEhkA+1h49a08iRflcq4H5iuXFU9cz4lqihC/LXS/NZa6Bc+pz5gql5ub6VXD2tZWTSPeyS7XgeLhXrMnEhj6MSHSwaIhFGZH8oA/JzzFeexvJbRN2HW03moT6cEChx6w4QY2rurn85JWrxsiCy0FwjcIqos8w7GZNPulkawDEbFHlaBtjzODEDrVztuKXMmADPWA3RaljyJeNdKq98ilAez8iJdyGqfO31V4NoV/EvyaCqR54V2EshE5Lqcb+TrkstkTLD4WKB4PNNZQ8P05HAelMXNSPWChC8JsYvwthJo0jSoF6fIqjjqe08Aat+LIkd+AVjn09zxbZFqK3tjXAUbXUaWDjTUSyN4J45YZX2Igo4cEOVfFson2ALIxSjR0jog5YNgpfNHM90BxIjDyWIB8Z2NfB01HISJ20wPaw4w1FlavXq1v8aPGXhFw9JNRFTDItifU/RwwpfmKxYsDK180kU4x0lhAXvOSJUs+bezlIDL2N4xi4GpjK4MGCuzUA+SPxzn3m4iKgKyV2DCV08DeMWg0B+zHHOt2DpjS3Mz1BfFOM25C5ZH4LxldJBB0g7GVARkaXgv8VsKqZtIMPpN9RUnJgRzU5Wfp22vifcG3+2vQvmdsdQXsX2pm+oKX+GYjjQXkPWqsXshpRhcJ0RpbGShSHiSuheP37ZYHsGusVHOrU1lMxkO9od4eE+8LlSzQqfetpnPAooBN/2Um+gISp89MkF8K4G3RrMJYoOhbYGxlQEGhSOGogfoLwipExGtUZVVBYIVAluaAaUpuWA+YujlPF22Ra/iBLYEOsV6tV4w0FiitfmLsXiBMU0NiAVrfsp77Zd8MHPgbDoHtva6uLs1jiv1piAKy5tCG+4KJ9wVO/p6RDzvy+b5rzSwP9Okh/WKPERiCWzfk4K8bUSTiOljAyCdx5DZG4gE8W5Dov+NYUfsV/j50fUC4dmXIQDh0qQ6PVgJsOcLM8oA410Ggvo6Ojr81di+g2TKuQOiyJOKWxlpCJpM5zUjKAL3awTsamQfEbYhjtDGKa5tPsyn/wAuiURftlBO56h6aunEwCMxxvV1d+2Fr7Jce2vAu5LUtLeoGi/19gtbToCaR97BoD6BvUs+WkXqgbw6OuhC6wH5l4rRGaCFOvYnjYbyxnpcsCvDVhYOxo6+zszNwSNHVTtJEmSiwzlMAQmNPwIPW42Dds2hfEK/5WJo0Fth+5VNxFHSlkoTzFRh/N3wnq0OGWxXtdoO8enFwaI4jsyidYgNZTxhrMEjEJ4w+En65ESWRXZ7Q4K/COqDAPlhka87WedB8KawmngTIHREOJs5pMiRp+p/GGgxL1FiA9hxjK6G1tVVdhJGAV15+cPXq1f7dahVC20Wg4miCp0uTe3Xh4Hwu93rY1B7SR/t7xQbP5R1FGgpy8IlKe+MJhZ9Aa7u5jPm+pGLX2BMDOZ+hDXgQiXIJ5xoXHZg96anEEFcvOTi0SMUXS4w0FijSTzTWYEA3hkTSEtDI2qw6RoytDLA6jctCvzKqJ8oPFOO7kAhnYe9cZGiWiZ/N9ezguWaSL4h3TUfvKJIfoN0I4sjigYSdZyxlcDVMgEczEY41ER6oZFBOh2Yqegf2zYoziFC3DuZZrjSTPLDtMlxaNPmPP/54W2OPxksrVozP5fLPGr8vEOpbxJCr3jQSJyDvGRNRhv7iHh8vE5LMpKznHBz4zSTOaXwe+mXGGh9tbWvVQf+iyfCAON/ZlTj4v43ECfB94Le4CuMrWVpTtw7O9fZOM5M8oD7xVSOLBdLuNWN1g7bgJUF8+4qpBjf7Te9M6hD4tBDc0289Wh2MHbuaSR7gsHOMLBaQ9W/G6o5MJrNDPu9dcYdQ33Yc95I6OFV5hnp2cGCliDingX5KU+9MShd0dmqta/k8J4zwnV2JsuuNxAnI83VwNpO52kiSoC4djA255cuXBzYPycGzjTQWkPdNY00OfRcQVLafRnd39ySLLsG1i20AyPZ3cDb7AyNJgnp1cOhUHUhcFiL045v9jTUa8Gjlm29fsQQhb3DzJLUEhC+oiK7EISPOwapoEh+7JQJti5YfGXs0YNC62ouC1h9lsrlToClsjc/RM7uSe0kd3EmlzTO/Kqk8Q106mM/Yw2aOB9jnOg6sWTHxJ9FraSJMy6nGz7RbZUDYmN7e3BnQ5Gisez7u3J9c0JwA6Pb0aCFvNObgwKk6NoU59uJwaJ8y1viAT4vCtEFXYO8SFQGtCZpllyXQtNqL+4lmZ/BN/5qJKQFZozEHe9JtAGSaw4wsFnie4JmUQcjleh8yZq0Fnmq3y0D02IzPMgnonYqYIfA4pC+TcXrgIahLB+PEb5s5HrjaR0b7kbHGB0pK7TDO1/T39x1lUZGAPlUH0xTbz+KSoC4dDDx2DQCHzTCaWOB5zjbW+KCSpW0IS0BIJmy6zWCk7WDuxZ4r5oO6dHB7e/sBZo4H2OfUsYOv9jHW+ECJdkAtA/c6MpmMd+XaEKj7km9M4F5TEfBzSKovDLKG1cHobw+b6EDa3WOksYBPAhevBUJMxl8GJTRhFyMLBKSJFn5ls9nvmogS0DfaHOzb3h8AcUuNNBLQNiWa0gRv4MwMMyBwCqxAfCIH82JdYSJKQN+ocjA5NHD2I/e1aj/23iPyhbG6A+bAgXsZoUEII/UAkkQORu71JqIE7o22HBw4VaelpWU74mPPDc/39d1trO5Qb4vJ8QXxbwat06WofcTInMCzeToAtN4VXUn/l1AXDkan9tDSfmL6C81BZooHxDkN9CMveLFZFFAWWZtDwVta3G0sJcAbe3bmYEiniShBXabcL+wflQDD5mD0yKlvk0b/Tk33AG5F7idG+/ibRe54oEl1nLG6A+ZYe1jyAIuG/u2LB3MazxwAfL5vJFGJinxQUwcju6c/n3+FNPm5JhJyy2k/sQTp5nm+2HBJCGi1X1WpwzuBoQXAN+IcjDz8mdePKi/WhH1uxd7GcCjIVBcWpUYDfZ0VbclEJSr2akMBhVrdX6j+Jx3DpSh7vKB8CIiqKwcrcXGqdr05k3RKbU9ryTQVkUB3aHMrEshw7kGCXiv8xxG0h6Uzent6Fpn6MhA17A6GT/3yTxNO1coJbgWur3JFf1fXNuTes5AZe18xXobFHJKv04JZc3O7CtIcgGL9KW03u3QCfL4D4b292dhrpoYgsYOhEz4kaOuHqXKqiagYiN9QnUlyKgX84JUYsQFP9GKzMFRSe8XJb9upE9Dn62CK/KQT75wdTLz+NXgPNdrDuYzeUd0ByN4Wp07n+EdCRZuTY1/ymZQDwIjQye9pA32xdw6IiUgHc639mN8kzCLRjkxzQRzitUpkZ8LZBP1CILUd55EVvdgsCrzJl5i8mgCja+Zgjst4Pq3DUnMmtSWqyNIuQruRU3+CbO08n+pvBAZAjf1IU5kcGJc0YRMBfVV3MPd2RN4+YbvYukI/3sSpe+LUmbw0ryG/6ts1oSLeYrMw6C0xeaFAGc+Wq3hbfeRk582b55lrzf3UHJwWkD0Wp+6BQ3+BfXEXw6UCdHX4TVB0BoJi9Y1Cp59XbUWN8HW7lRjLli3zbINE+1hNiCRI1cGakIhT99ani/A6z1z1nDoUqNQfbO40kyqDfrCBwMg3E5rsCy+8sFlHR8dEnFzRTq/I8hQ9NFFOtGhXVOxgFeUqfknUK7Ctpjl1ANKJ/vmUkvrdwRZmWjpA4J9MTyja2toKY8TQa/ufxP/Whdd5c5cQJHIwfBsTvkKiaqd6/fRyOHKqavdL0H+V2sxmWvrQCAeKItfmQlNyDG/8SVwnetMHyxmA7lm0K2I7GFrlVBW/V6FPP9GqeU4V0Kt2+O2yhctUN6AJBEWD9ngMnessJxh5AfCoQe+8q+xQOYLuWbQrQh2MXP1XYh8S9DKC2sI1z6kCatW3/RCZ6Vj9fNPMqx2wQVNJQlcNEl/mGG5pv48bi7HxMVSOoHsW7QqPg5GlvnJtk6/B9+HMqYUfaXE6rampqWy4dVhgi8FfLprnBXEex+i/wCSkNiSNDSpUxxt7Ccj2nQQYAwUHc9yE3HEotuifDklnfFYMdGNC/lWCxotDf4PvB/jHZTs71c+f2n+ryqCPPcb5/pKdGrTvbH2MUjH4ByOLBDpON9YSFi5cuI1FOwFbbyTox5T6y+iwFL8CqvWvwVtolWgSv/N4sXbl5ZP3r8hRLT50d56KgYJDCYXVhYOhtqqReKDdZuGJtSQSOk8f67x581SspvH3lpoBe9Vefbg/lzveaXmnAf6tEDMNGRp3LnV3ch29o10lQIf+bOKZc+XnmMGARF2EK4vUwQiSw33n7ZlqDWwcaK9Ob29vd26vwj+OT8m3kKFxdd9tlILSJ1Wo8Y8RZT/YiKOY4le5P3SGZJAc7telg7FroL16Jc/n/a1cBBCxsSblwT8LOfofcCh4AQ4x1uoCXZtgVKnYDXLMUECnPSQD29VBcrhfVw7GHrVXb6WylGg0SvUZcrr+YPYuwWVfaE9ltmpA2Q6EQq2UY+yigzf2oqCH4v4MIysD94fdwdig9uqDnB4T5/d+gwHPGNVFcOopyJiPLOfmGTwa0Ek8qS8RKDKORLFWH95utwbDd94SRqqN/Cv4PDXbTFfXfUZWBvRUPJCRBJiIqfnnccy0Dz74wHkWoypY2D4ZGU8gK+kKjQKQ8RcTW1uQI2fmc7nH7LIMFEW+sw6xdyN4CgvNByNIDjp+ZyRVhzlV7dVLaZc7t1cRoW0w9of/No6ptbuRdZupqC3QPZY33HchMkbJiRPssgyaHkN82XaJXPtOJuN+JRuixQI6Cu1VXiZtJehcFGpeNPyXI6cqPWTIvsxU1R7o912akevre4OHfTHot3fEfRbD3y8+Qu0djO5Ce5UXNGl7dTt4z0RGqnOuhgLZgmcPk2FHrrd3jgwkAVQ58e1ioxjcHeMLPWQcq+5gZKm9+hJHjXo5z4xQBQsxxyDjEfir+nNq5GfQo/nYh6f9e4NUgGEFx3DEzvw1nPrOhSJ+kh6GUBUHw6//Kmls96dJ2qv6FxNF9z8g405kVLVXDfkaiFAd4JIkttYUGFpyDOf91Ch/YVEe8DA/gORpuywDfLNMjBOQt4qEupbTPTX4YeJig+/qrnoxkfMeIdH2UHGBfP0H6kFepElc1rY5lBQYXZbzuO7BWYH7b3V3d/+TX1FEG/JSExEJdOi7qsnrx3DuNM8Zdg2NqnN/BjK0EXlVhxORr56wP6Lv/DT+X1FzYLynaOWe2s1TjCQW4An9t6Jk4hBVdH6YpB9YNXoS+SRk/JaQZHd5J2CnesLuyGaze3KZ2hTemoNcpO+uB3pAQuzvC7SeJSfc0258Wo97aX9PT+TmMEMB73jsO0wJzXnVx4llL7pe5kWaFtSqGHHgu6rpPr5jsdx+hyI59G+hA4C25GDO1V69mbf/77h0+lZpzZX44B+Ye1X1cWKz92pKrYlcjtzc6gfN+ufhApd/ErcwTvuTRNI0m4c4Tg77u6gfbCHdTuQcrRFaRKiFU7Xl1O/RqX9RObevRxR43gmEBYUn9wEJIMeF/jk0yVKTta2tE0jg43kx1OatWifEYKDrHYKGDnfkMrU1xHUPaoh7k8i+030EvoV3c6i4aTCoc/9+9NVkFgh6BmZFaig08he3oxYkwBEkQGCzg7gfG6kzaDvuSyLfgIyqt1cF6SAspoS4iJf3c9xaf3JrGEgUzZcOGgvO4agzjTQUkI9V5z4851MuLhBvUUp1gR7tjXEHL+shXFZnduNIBomi6T73FVLLByQePu4N3CxMbVxyzfeQUTYZrdpA3yvoPVf/1jdTGggC6aXx0ieLSecFcWoj72vkhU4IcswU7gVORksb6FHnufbouJ4Xbv+gf1g0EADav9uSeO9YenpA3IfURFVZ0gqEms1rRg0qCzM4TuYy1T061jt0dXXpX0xJ96FMDXIqQXtJ3tSfze6OaY0KU1ogfTUgUJMK0lBIL06dS/F/LJeRe0k2kAAk7BgSWN2GVW/aCOjRuPCbBHVGBG6J3ECKIN3VlfjroguqA+RrMsFvCNqisf5mRox2qPlB4s8vuiMdIE/fVjVvLlRnhKlqYLig7QIpOiva40PAqR2E22neJFrN10AVgWMOIDgPuMOjmRFa+HVaR0fHliaugXoEOe80nBWrZg2dZkZoYffuaW5u1kCVkadmbT70AGdqJodWOhxHqP2eFg1UDvsLatnSFq41M+KKnp6eXbhsdB2OdGiCeX8+/2ecqgnmk/VXNYtqYLSAnNposzpjgw3+H/belpVa8J7TAAAAAElFTkSuQmCC"
  108129. }
  108130. },
  108131. viewer: {
  108132. html: __webpack_require__(14),
  108133. },
  108134. overlay: {
  108135. html: __webpack_require__(15),
  108136. params: {
  108137. closeImage: __webpack_require__(16),
  108138. closeText: 'Close'
  108139. }
  108140. },
  108141. error: {
  108142. html: __webpack_require__(17)
  108143. }
  108144. },
  108145. engine: {
  108146. antialiasing: true
  108147. }
  108148. };
  108149. /***/ }),
  108150. /* 36 */
  108151. /***/ (function(module, exports, __webpack_require__) {
  108152. "use strict";
  108153. Object.defineProperty(exports, "__esModule", { value: true });
  108154. exports.defaultConfiguration = {
  108155. version: "3.2.0-alpha4",
  108156. templates: {
  108157. main: {
  108158. html: __webpack_require__(11)
  108159. },
  108160. loadingScreen: {
  108161. html: __webpack_require__(12),
  108162. params: {
  108163. backgroundColor: "#000000",
  108164. loadingImage: __webpack_require__(13)
  108165. }
  108166. },
  108167. viewer: {
  108168. html: __webpack_require__(14),
  108169. events: {
  108170. pointerout: true,
  108171. pointerdown: true,
  108172. pointerup: true
  108173. }
  108174. },
  108175. navBar: {
  108176. html: __webpack_require__(37),
  108177. params: {
  108178. buttons: {
  108179. /*"help-button": {
  108180. altText: "Help",
  108181. image: require('../../../assets/img/help-circle.png')
  108182. },*/
  108183. "fullscreen-button": {
  108184. altText: "Fullscreen",
  108185. image: __webpack_require__(38)
  108186. }
  108187. },
  108188. visibilityTimeout: 2000
  108189. },
  108190. events: {
  108191. pointerdown: { 'fullscreen-button': true /*, '#help-button': true*/ },
  108192. pointerover: true,
  108193. change: { 'animation-selector': true }
  108194. }
  108195. },
  108196. overlay: {
  108197. html: __webpack_require__(15),
  108198. params: {
  108199. closeImage: __webpack_require__(16),
  108200. closeText: 'Close'
  108201. }
  108202. },
  108203. help: {
  108204. html: __webpack_require__(39)
  108205. },
  108206. share: {
  108207. html: __webpack_require__(40)
  108208. },
  108209. error: {
  108210. html: __webpack_require__(17)
  108211. }
  108212. },
  108213. camera: {
  108214. behaviors: {
  108215. autoRotate: 0,
  108216. framing: {
  108217. type: 2,
  108218. zoomOnBoundingInfo: true,
  108219. zoomStopsAnimation: false
  108220. },
  108221. bouncing: 1
  108222. },
  108223. wheelPrecision: 200,
  108224. },
  108225. skybox: {
  108226. /*cubeTexture: {
  108227. url: 'https://playground.babylonjs.com/textures/environment.dds',
  108228. gammaSpace: false
  108229. },*/
  108230. pbr: true,
  108231. blur: 0.7,
  108232. infiniteDistance: false,
  108233. },
  108234. ground: {
  108235. receiveShadows: true
  108236. },
  108237. engine: {
  108238. antialiasing: true
  108239. },
  108240. scene: {
  108241. imageProcessingConfiguration: {
  108242. exposure: 1.4,
  108243. contrast: 1.66,
  108244. toneMappingEnabled: true
  108245. }
  108246. }
  108247. };
  108248. /***/ }),
  108249. /* 37 */
  108250. /***/ (function(module, exports) {
  108251. module.exports = "<style>nav-bar{position:absolute;height:160px;width:100%;bottom:0;background-color:rgba(0,0,0,.3);color:#fff;transition:1s;align-items:flex-start;justify-content:space-around;display:flex;flex-direction:column}@media screen and (min-width:768px){nav-bar{align-items:center;flex-direction:row;justify-content:space-between;height:80px}}div.flex-container{display:flex;width:100%}div.thumbnail{position:relative;overflow:hidden;display:block;width:40px;height:40px;background-size:cover;background-position:center;border-radius:20px;margin:0 10px}div.title-container{flex-direction:column;display:flex;justify-content:space-between}span.model-title{font-size:125%}span.model-subtitle{font-size:90%}div.animation-container,div.button-container{align-items:center;justify-content:flex-end}div.button{cursor:pointer;height:30px;margin:0 10px}div.button img{height:100%}</style> {{#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=flex-container id=model-metadata> <div class=thumbnail> </div> <div class=title-container> <span class=model-title>{{#if title}}{{title}}{{/if}}</span> <span class=model-subtitle> {{#if subtitle}}{{subtitle}} {{/if}}</span> </div> </div> {{#if animations}} {{#if hideAnimations}}{{else}} <div class=\"animation-container flex-container\"> <select id=animation-selector name=animations> {{#each animations}} <option value={{this}}>{{this}}</option>> {{/each}} </select> </div> {{/if}} {{/if}} <div class=\"button-container flex-container\"> {{#eachInMap buttons}} <div id={{id}} class=button> {{#if text}} <span>{{text}}</span>> {{/if}} {{#if image}} <img src={{image}} alt={{altText}}> {{/if}} </div> {{/eachInMap}} </div>";
  108252. /***/ }),
  108253. /* 38 */
  108254. /***/ (function(module, exports) {
  108255. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII="
  108256. /***/ }),
  108257. /* 39 */
  108258. /***/ (function(module, exports) {
  108259. module.exports = "HELP";
  108260. /***/ }),
  108261. /* 40 */
  108262. /***/ (function(module, exports) {
  108263. module.exports = "SHARE";
  108264. /***/ }),
  108265. /* 41 */
  108266. /***/ (function(module, exports, __webpack_require__) {
  108267. "use strict";
  108268. Object.defineProperty(exports, "__esModule", { value: true });
  108269. exports.extendedConfiguration = {
  108270. version: "3.2.0",
  108271. extends: "default",
  108272. camera: {
  108273. radius: 2,
  108274. alpha: -1.5708,
  108275. beta: Math.PI * 0.5 - 0.2618,
  108276. wheelPrecision: 300,
  108277. minZ: 0.1,
  108278. maxZ: 50,
  108279. },
  108280. lights: {
  108281. "light1": {
  108282. type: 0,
  108283. shadowEnabled: false,
  108284. position: { x: -1.78, y: 2.298, z: 2.62 },
  108285. diffuse: { r: 0.8, g: 0.8, b: 0.8 },
  108286. intensity: 3,
  108287. intensityMode: 0,
  108288. radius: 3.135,
  108289. },
  108290. "light3": {
  108291. type: 2,
  108292. shadowEnabled: false,
  108293. position: { x: -4, y: 2, z: -2.23 },
  108294. diffuse: { r: 0.718, g: 0.772, b: 0.749 },
  108295. intensity: 2.052,
  108296. intensityMode: 0,
  108297. radius: 0.5,
  108298. spotAngle: 42.85
  108299. }
  108300. },
  108301. ground: {
  108302. receiveShadows: true
  108303. },
  108304. scene: {
  108305. imageProcessingConfiguration: {
  108306. colorCurves: {
  108307. shadowsHue: 43.359,
  108308. shadowsDensity: 1,
  108309. shadowsSaturation: -25,
  108310. shadowsExposure: -3.0,
  108311. midtonesHue: 93.65,
  108312. midtonesDensity: -15.24,
  108313. midtonesExposure: 7.37,
  108314. midtonesSaturation: -15,
  108315. highlightsHue: 37.2,
  108316. highlightsDensity: -22.43,
  108317. highlightsExposure: 45.0,
  108318. highlightsSaturation: -15
  108319. }
  108320. },
  108321. mainColor: {
  108322. r: 0.7,
  108323. g: 0.7,
  108324. b: 0.7
  108325. }
  108326. },
  108327. loaderPlugins: {
  108328. extendedMaterial: true,
  108329. minecraft: true,
  108330. msftLod: true,
  108331. telemetry: true
  108332. },
  108333. model: {
  108334. rotationOffsetAxis: {
  108335. x: 0,
  108336. y: 1,
  108337. z: 0
  108338. },
  108339. rotationOffsetAngle: 3.66519,
  108340. material: {
  108341. directEnabled: true,
  108342. directIntensity: 0.884,
  108343. emissiveIntensity: 1.04,
  108344. environmentIntensity: 0.868
  108345. },
  108346. normalize: true,
  108347. castShadow: true,
  108348. receiveShadows: true
  108349. },
  108350. lab: {
  108351. renderingPipelines: {
  108352. default: {
  108353. bloomEnabled: true,
  108354. bloomThreshold: 1.0,
  108355. fxaaEnabled: true
  108356. }
  108357. }
  108358. }
  108359. };
  108360. /***/ }),
  108361. /* 42 */
  108362. /***/ (function(module, exports, __webpack_require__) {
  108363. "use strict";
  108364. Object.defineProperty(exports, "__esModule", { value: true });
  108365. exports.shadowDirectionalLightConfiguration = {
  108366. model: {
  108367. receiveShadows: true,
  108368. castShadow: true
  108369. },
  108370. ground: {
  108371. receiveShadows: true
  108372. },
  108373. lights: {
  108374. shadowDirectionalLight: {
  108375. type: 1,
  108376. shadowEnabled: true,
  108377. target: { x: 0, y: 0, z: 0.5 },
  108378. position: { x: 1.49, y: 2.39, z: -1.33 },
  108379. diffuse: { r: 0.867, g: 0.816, b: 0.788 },
  108380. intensity: 4.887,
  108381. intensityMode: 0,
  108382. shadowBufferSize: 1024,
  108383. shadowFrustumSize: 8.0,
  108384. shadowFieldOfView: 50.977,
  108385. shadowMinZ: 0.1,
  108386. shadowMaxZ: 12.0,
  108387. shadowConfig: {
  108388. blurKernel: 32,
  108389. useBlurExponentialShadowMap: true
  108390. }
  108391. }
  108392. }
  108393. };
  108394. exports.shadowSpotlLightConfiguration = {
  108395. model: {
  108396. receiveShadows: true,
  108397. castShadow: true
  108398. },
  108399. ground: {
  108400. receiveShadows: true
  108401. },
  108402. lights: {
  108403. shadowSpotLight: {
  108404. type: 2,
  108405. intensity: 2,
  108406. shadowEnabled: true,
  108407. target: { x: 0, y: 0, z: 0.5 },
  108408. position: { x: 0, y: 3.5, z: 3.7 },
  108409. angle: 1,
  108410. shadowOrthoScale: 0.5,
  108411. shadowBufferSize: 1024,
  108412. shadowMinZ: 0.1,
  108413. shadowMaxZ: 50.0,
  108414. shadowConfig: {
  108415. frustumEdgeFalloff: 0.5,
  108416. blurKernel: 32,
  108417. useBlurExponentialShadowMap: true
  108418. }
  108419. }
  108420. }
  108421. };
  108422. /***/ }),
  108423. /* 43 */
  108424. /***/ (function(module, exports, __webpack_require__) {
  108425. "use strict";
  108426. Object.defineProperty(exports, "__esModule", { value: true });
  108427. exports.environmentMapConfiguration = {
  108428. lab: {
  108429. environmentAssetsRootURL: '/assets/environment/',
  108430. environmentMap: {
  108431. texture: 'EnvMap_2.0-256.env',
  108432. rotationY: 0,
  108433. tintLevel: 0.4
  108434. }
  108435. }
  108436. };
  108437. /***/ }),
  108438. /* 44 */
  108439. /***/ (function(module, exports, __webpack_require__) {
  108440. "use strict";
  108441. Object.defineProperty(exports, "__esModule", { value: true });
  108442. var telemetryLoaderPlugin_1 = __webpack_require__(45);
  108443. var msftLodLoaderPlugin_1 = __webpack_require__(46);
  108444. var extendedMaterialLoaderPlugin_1 = __webpack_require__(47);
  108445. var pluginCache = {};
  108446. function getLoaderPluginByName(name) {
  108447. if (!pluginCache[name]) {
  108448. switch (name) {
  108449. case 'telemetry':
  108450. pluginCache[name] = new telemetryLoaderPlugin_1.TelemetryLoaderPlugin();
  108451. break;
  108452. case 'msftLod':
  108453. pluginCache[name] = new msftLodLoaderPlugin_1.MSFTLodLoaderPlugin();
  108454. break;
  108455. case 'minecraft':
  108456. pluginCache[name] = new msftLodLoaderPlugin_1.MSFTLodLoaderPlugin();
  108457. break;
  108458. case 'extendedMaterial':
  108459. pluginCache[name] = new extendedMaterialLoaderPlugin_1.ExtendedMaterialLoaderPlugin();
  108460. break;
  108461. }
  108462. }
  108463. return pluginCache[name];
  108464. }
  108465. exports.getLoaderPluginByName = getLoaderPluginByName;
  108466. /***/ }),
  108467. /* 45 */
  108468. /***/ (function(module, exports, __webpack_require__) {
  108469. "use strict";
  108470. Object.defineProperty(exports, "__esModule", { value: true });
  108471. var telemetryManager_1 = __webpack_require__(4);
  108472. var babylonjs_1 = __webpack_require__(0);
  108473. var TelemetryLoaderPlugin = /** @class */ (function () {
  108474. function TelemetryLoaderPlugin() {
  108475. }
  108476. TelemetryLoaderPlugin.prototype.onInit = function (loader, model) {
  108477. this._model = model;
  108478. this._loadStart = babylonjs_1.Tools.Now;
  108479. };
  108480. TelemetryLoaderPlugin.prototype.onLoaded = function (model) {
  108481. telemetryManager_1.telemetryManager.broadcast("Load First LOD Complete", model.getViewer(), {
  108482. model: model,
  108483. loadTime: babylonjs_1.Tools.Now - this._loadStart
  108484. });
  108485. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.getViewer());
  108486. };
  108487. TelemetryLoaderPlugin.prototype.onError = function (message, exception) {
  108488. this._loadEnd = babylonjs_1.Tools.Now;
  108489. telemetryManager_1.telemetryManager.broadcast("Load Error", this._model.getViewer(), {
  108490. model: this._model,
  108491. loadTime: this._loadEnd - this._loadStart
  108492. });
  108493. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.getViewer());
  108494. };
  108495. TelemetryLoaderPlugin.prototype.onComplete = function () {
  108496. this._loadEnd = babylonjs_1.Tools.Now;
  108497. telemetryManager_1.telemetryManager.broadcast("Load Complete", this._model.getViewer(), {
  108498. model: this._model,
  108499. loadTime: this._loadEnd - this._loadStart
  108500. });
  108501. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.getViewer());
  108502. };
  108503. return TelemetryLoaderPlugin;
  108504. }());
  108505. exports.TelemetryLoaderPlugin = TelemetryLoaderPlugin;
  108506. /***/ }),
  108507. /* 46 */
  108508. /***/ (function(module, exports, __webpack_require__) {
  108509. "use strict";
  108510. Object.defineProperty(exports, "__esModule", { value: true });
  108511. var MSFTLodLoaderPlugin = /** @class */ (function () {
  108512. function MSFTLodLoaderPlugin() {
  108513. }
  108514. MSFTLodLoaderPlugin.prototype.onInit = function (loader, model) {
  108515. this._model = model;
  108516. };
  108517. MSFTLodLoaderPlugin.prototype.onExtensionLoaded = function (extension) {
  108518. if (extension.name === "MSFT_lod" && this._model.configuration.loaderConfiguration) {
  108519. var MSFT_lod = extension;
  108520. MSFT_lod.enabled = !!this._model.configuration.loaderConfiguration.progressiveLoading;
  108521. MSFT_lod.maxLODsToLoad = this._model.configuration.loaderConfiguration.maxLODsToLoad || Number.MAX_VALUE;
  108522. }
  108523. };
  108524. return MSFTLodLoaderPlugin;
  108525. }());
  108526. exports.MSFTLodLoaderPlugin = MSFTLodLoaderPlugin;
  108527. /***/ }),
  108528. /* 47 */
  108529. /***/ (function(module, exports, __webpack_require__) {
  108530. "use strict";
  108531. Object.defineProperty(exports, "__esModule", { value: true });
  108532. var babylonjs_1 = __webpack_require__(0);
  108533. var ExtendedMaterialLoaderPlugin = /** @class */ (function () {
  108534. function ExtendedMaterialLoaderPlugin() {
  108535. }
  108536. ExtendedMaterialLoaderPlugin.prototype.onMaterialLoaded = function (baseMaterial) {
  108537. var material = baseMaterial;
  108538. material.alphaMode = babylonjs_1.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  108539. };
  108540. return ExtendedMaterialLoaderPlugin;
  108541. }());
  108542. exports.ExtendedMaterialLoaderPlugin = ExtendedMaterialLoaderPlugin;
  108543. /***/ }),
  108544. /* 48 */
  108545. /***/ (function(module, exports, __webpack_require__) {
  108546. /*!
  108547. * PEP v0.4.3 | https://github.com/jquery/PEP
  108548. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  108549. */
  108550. !function(a,b){ true?module.exports=b():"function"==typeof define&&define.amd?define(b):a.PointerEventsPolyfill=b()}(this,function(){"use strict";function a(a,b){b=b||Object.create(null);var c=document.createEvent("Event");c.initEvent(a,b.bubbles||!1,b.cancelable||!1);
  108551. // define inherited MouseEvent properties
  108552. // skip bubbles and cancelable since they're set above in initEvent()
  108553. for(var d,e=2;e<m.length;e++)d=m[e],c[d]=b[d]||n[e];c.buttons=b.buttons||0;
  108554. // Spec requires that pointers without pressure specified use 0.5 for down
  108555. // state and 0 for up state.
  108556. var f=0;
  108557. // add x/y properties aliased to clientX/Y
  108558. // define the properties of the PointerEvent interface
  108559. return f=b.pressure&&c.buttons?b.pressure:c.buttons?.5:0,c.x=c.clientX,c.y=c.clientY,c.pointerId=b.pointerId||0,c.width=b.width||0,c.height=b.height||0,c.pressure=f,c.tiltX=b.tiltX||0,c.tiltY=b.tiltY||0,c.twist=b.twist||0,c.tangentialPressure=b.tangentialPressure||0,c.pointerType=b.pointerType||"",c.hwTimestamp=b.hwTimestamp||0,c.isPrimary=b.isPrimary||!1,c}function b(){this.array=[],this.size=0}function c(a,b,c,d){this.addCallback=a.bind(d),this.removeCallback=b.bind(d),this.changedCallback=c.bind(d),A&&(this.observer=new A(this.mutationWatcher.bind(this)))}function d(a){return"body /shadow-deep/ "+e(a)}function e(a){return'[touch-action="'+a+'"]'}function f(a){return"{ -ms-touch-action: "+a+"; touch-action: "+a+"; }"}function g(){if(F){D.forEach(function(a){String(a)===a?(E+=e(a)+f(a)+"\n",G&&(E+=d(a)+f(a)+"\n")):(E+=a.selectors.map(e)+f(a.rule)+"\n",G&&(E+=a.selectors.map(d)+f(a.rule)+"\n"))});var a=document.createElement("style");a.textContent=E,document.head.appendChild(a)}}function h(){
  108560. // only activate if this platform does not have pointer events
  108561. if(!window.PointerEvent){if(window.PointerEvent=a,window.navigator.msPointerEnabled){var b=window.navigator.msMaxTouchPoints;Object.defineProperty(window.navigator,"maxTouchPoints",{value:b,enumerable:!0}),u.registerSource("ms",_)}else Object.defineProperty(window.navigator,"maxTouchPoints",{value:0,enumerable:!0}),u.registerSource("mouse",N),void 0!==window.ontouchstart&&u.registerSource("touch",V);u.register(document)}}function i(a){if(!u.pointermap.has(a)){var b=new Error("InvalidPointerId");throw b.name="InvalidPointerId",b}}function j(a){for(var b=a.parentNode;b&&b!==a.ownerDocument;)b=b.parentNode;if(!b){var c=new Error("InvalidStateError");throw c.name="InvalidStateError",c}}function k(a){var b=u.pointermap.get(a);return 0!==b.buttons}function l(){window.Element&&!Element.prototype.setPointerCapture&&Object.defineProperties(Element.prototype,{setPointerCapture:{value:W},releasePointerCapture:{value:X},hasPointerCapture:{value:Y}})}/**
  108562. * This is the constructor for new PointerEvents.
  108563. *
  108564. * New Pointer Events must be given a type, and an optional dictionary of
  108565. * initialization properties.
  108566. *
  108567. * Due to certain platform requirements, events returned from the constructor
  108568. * identify as MouseEvents.
  108569. *
  108570. * @constructor
  108571. * @param {String} inType The type of the event to create.
  108572. * @param {Object} [inDict] An optional dictionary of initial event properties.
  108573. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  108574. */
  108575. var m=["bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget","pageX","pageY"],n=[!1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,0,0],o=window.Map&&window.Map.prototype.forEach,p=o?Map:b;b.prototype={set:function(a,b){return void 0===b?this["delete"](a):(this.has(a)||this.size++,void(this.array[a]=b))},has:function(a){return void 0!==this.array[a]},"delete":function(a){this.has(a)&&(delete this.array[a],this.size--)},get:function(a){return this.array[a]},clear:function(){this.array.length=0,this.size=0},
  108576. // return value, key, map
  108577. forEach:function(a,b){return this.array.forEach(function(c,d){a.call(b,c,d,this)},this)}};var q=[
  108578. // MouseEvent
  108579. "bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget",
  108580. // DOM Level 3
  108581. "buttons",
  108582. // PointerEvent
  108583. "pointerId","width","height","pressure","tiltX","tiltY","pointerType","hwTimestamp","isPrimary",
  108584. // event instance
  108585. "type","target","currentTarget","which","pageX","pageY","timeStamp"],r=[
  108586. // MouseEvent
  108587. !1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,
  108588. // DOM Level 3
  108589. 0,
  108590. // PointerEvent
  108591. 0,0,0,0,0,0,"",0,!1,
  108592. // event instance
  108593. "",null,null,0,0,0,0],s={pointerover:1,pointerout:1,pointerenter:1,pointerleave:1},t="undefined"!=typeof SVGElementInstance,u={pointermap:new p,eventMap:Object.create(null),captureInfo:Object.create(null),
  108594. // Scope objects for native events.
  108595. // This exists for ease of testing.
  108596. eventSources:Object.create(null),eventSourceList:[],/**
  108597. * Add a new event source that will generate pointer events.
  108598. *
  108599. * `inSource` must contain an array of event names named `events`, and
  108600. * functions with the names specified in the `events` array.
  108601. * @param {string} name A name for the event source
  108602. * @param {Object} source A new source of platform events.
  108603. */
  108604. registerSource:function(a,b){var c=b,d=c.events;d&&(d.forEach(function(a){c[a]&&(this.eventMap[a]=c[a].bind(c))},this),this.eventSources[a]=c,this.eventSourceList.push(c))},register:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  108605. // call eventsource register
  108606. b.register.call(b,a)},unregister:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  108607. // call eventsource register
  108608. b.unregister.call(b,a)},contains:/*scope.external.contains || */function(a,b){try{return a.contains(b)}catch(c){
  108609. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  108610. return!1}},
  108611. // EVENTS
  108612. down:function(a){a.bubbles=!0,this.fireEvent("pointerdown",a)},move:function(a){a.bubbles=!0,this.fireEvent("pointermove",a)},up:function(a){a.bubbles=!0,this.fireEvent("pointerup",a)},enter:function(a){a.bubbles=!1,this.fireEvent("pointerenter",a)},leave:function(a){a.bubbles=!1,this.fireEvent("pointerleave",a)},over:function(a){a.bubbles=!0,this.fireEvent("pointerover",a)},out:function(a){a.bubbles=!0,this.fireEvent("pointerout",a)},cancel:function(a){a.bubbles=!0,this.fireEvent("pointercancel",a)},leaveOut:function(a){this.out(a),this.propagate(a,this.leave,!1)},enterOver:function(a){this.over(a),this.propagate(a,this.enter,!0)},
  108613. // LISTENER LOGIC
  108614. eventHandler:function(a){
  108615. // This is used to prevent multiple dispatch of pointerevents from
  108616. // platform events. This can happen when two elements in different scopes
  108617. // are set up to create pointer events, which is relevant to Shadow DOM.
  108618. if(!a._handledByPE){var b=a.type,c=this.eventMap&&this.eventMap[b];c&&c(a),a._handledByPE=!0}},
  108619. // set up event listeners
  108620. listen:function(a,b){b.forEach(function(b){this.addEvent(a,b)},this)},
  108621. // remove event listeners
  108622. unlisten:function(a,b){b.forEach(function(b){this.removeEvent(a,b)},this)},addEvent:/*scope.external.addEvent || */function(a,b){a.addEventListener(b,this.boundHandler)},removeEvent:/*scope.external.removeEvent || */function(a,b){a.removeEventListener(b,this.boundHandler)},
  108623. // EVENT CREATION AND TRACKING
  108624. /**
  108625. * Creates a new Event of type `inType`, based on the information in
  108626. * `inEvent`.
  108627. *
  108628. * @param {string} inType A string representing the type of event to create
  108629. * @param {Event} inEvent A platform event with a target
  108630. * @return {Event} A PointerEvent of type `inType`
  108631. */
  108632. makeEvent:function(b,c){
  108633. // relatedTarget must be null if pointer is captured
  108634. this.captureInfo[c.pointerId]&&(c.relatedTarget=null);var d=new a(b,c);return c.preventDefault&&(d.preventDefault=c.preventDefault),d._target=d._target||c.target,d},
  108635. // make and dispatch an event in one call
  108636. fireEvent:function(a,b){var c=this.makeEvent(a,b);return this.dispatchEvent(c)},/**
  108637. * Returns a snapshot of inEvent, with writable properties.
  108638. *
  108639. * @param {Event} inEvent An event that contains properties to copy.
  108640. * @return {Object} An object containing shallow copies of `inEvent`'s
  108641. * properties.
  108642. */
  108643. cloneEvent:function(a){for(var b,c=Object.create(null),d=0;d<q.length;d++)b=q[d],c[b]=a[b]||r[d],
  108644. // Work around SVGInstanceElement shadow tree
  108645. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  108646. // This is the behavior implemented by Firefox.
  108647. !t||"target"!==b&&"relatedTarget"!==b||c[b]instanceof SVGElementInstance&&(c[b]=c[b].correspondingUseElement);
  108648. // keep the semantics of preventDefault
  108649. return a.preventDefault&&(c.preventDefault=function(){a.preventDefault()}),c},getTarget:function(a){var b=this.captureInfo[a.pointerId];return b?a._target!==b&&a.type in s?void 0:b:a._target},propagate:function(a,b,c){
  108650. // Order of conditions due to document.contains() missing in IE.
  108651. for(var d=a.target,e=[];d!==document&&!d.contains(a.relatedTarget);)
  108652. // Touch: Do not propagate if node is detached.
  108653. if(e.push(d),d=d.parentNode,!d)return;c&&e.reverse(),e.forEach(function(c){a.target=c,b.call(this,a)},this)},setCapture:function(b,c,d){this.captureInfo[b]&&this.releaseCapture(b,d),this.captureInfo[b]=c,this.implicitRelease=this.releaseCapture.bind(this,b,d),document.addEventListener("pointerup",this.implicitRelease),document.addEventListener("pointercancel",this.implicitRelease);var e=new a("gotpointercapture");e.pointerId=b,e._target=c,d||this.asyncDispatchEvent(e)},releaseCapture:function(b,c){var d=this.captureInfo[b];if(d){this.captureInfo[b]=void 0,document.removeEventListener("pointerup",this.implicitRelease),document.removeEventListener("pointercancel",this.implicitRelease);var e=new a("lostpointercapture");e.pointerId=b,e._target=d,c||this.asyncDispatchEvent(e)}},/**
  108654. * Dispatches the event to its target.
  108655. *
  108656. * @param {Event} inEvent The event to be dispatched.
  108657. * @return {Boolean} True if an event handler returns true, false otherwise.
  108658. */
  108659. dispatchEvent:/*scope.external.dispatchEvent || */function(a){var b=this.getTarget(a);if(b)return b.dispatchEvent(a)},asyncDispatchEvent:function(a){requestAnimationFrame(this.dispatchEvent.bind(this,a))}};u.boundHandler=u.eventHandler.bind(u);var v={shadow:function(a){if(a)return a.shadowRoot||a.webkitShadowRoot},canTarget:function(a){return a&&Boolean(a.elementFromPoint)},targetingShadow:function(a){var b=this.shadow(a);if(this.canTarget(b))return b},olderShadow:function(a){var b=a.olderShadowRoot;if(!b){var c=a.querySelector("shadow");c&&(b=c.olderShadowRoot)}return b},allShadows:function(a){for(var b=[],c=this.shadow(a);c;)b.push(c),c=this.olderShadow(c);return b},searchRoot:function(a,b,c){if(a){var d,e,f=a.elementFromPoint(b,c);for(
  108660. // is element a shadow host?
  108661. e=this.targetingShadow(f);e;){if(
  108662. // find the the element inside the shadow root
  108663. d=e.elementFromPoint(b,c)){
  108664. // shadowed element may contain a shadow root
  108665. var g=this.targetingShadow(d);return this.searchRoot(g,b,c)||d}
  108666. // check for older shadows
  108667. e=this.olderShadow(e)}
  108668. // light dom element is the target
  108669. return f}},owner:function(a){
  108670. // walk up until you hit the shadow root or document
  108671. for(var b=a;b.parentNode;)b=b.parentNode;
  108672. // the owner element is expected to be a Document or ShadowRoot
  108673. return b.nodeType!==Node.DOCUMENT_NODE&&b.nodeType!==Node.DOCUMENT_FRAGMENT_NODE&&(b=document),b},findTarget:function(a){var b=a.clientX,c=a.clientY,d=this.owner(a.target);
  108674. // if x, y is not in this root, fall back to document search
  108675. return d.elementFromPoint(b,c)||(d=document),this.searchRoot(d,b,c)}},w=Array.prototype.forEach.call.bind(Array.prototype.forEach),x=Array.prototype.map.call.bind(Array.prototype.map),y=Array.prototype.slice.call.bind(Array.prototype.slice),z=Array.prototype.filter.call.bind(Array.prototype.filter),A=window.MutationObserver||window.WebKitMutationObserver,B="[touch-action]",C={subtree:!0,childList:!0,attributes:!0,attributeOldValue:!0,attributeFilter:["touch-action"]};c.prototype={watchSubtree:function(a){
  108676. // Only watch scopes that can target find, as these are top-level.
  108677. // Otherwise we can see duplicate additions and removals that add noise.
  108678. //
  108679. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  108680. // a removal without an insertion when a node is redistributed among
  108681. // shadows. Since it all ends up correct in the document, watching only
  108682. // the document will yield the correct mutations to watch.
  108683. this.observer&&v.canTarget(a)&&this.observer.observe(a,C)},enableOnSubtree:function(a){this.watchSubtree(a),a===document&&"complete"!==document.readyState?this.installOnLoad():this.installNewSubtree(a)},installNewSubtree:function(a){w(this.findElements(a),this.addElement,this)},findElements:function(a){return a.querySelectorAll?a.querySelectorAll(B):[]},removeElement:function(a){this.removeCallback(a)},addElement:function(a){this.addCallback(a)},elementChanged:function(a,b){this.changedCallback(a,b)},concatLists:function(a,b){return a.concat(y(b))},
  108684. // register all touch-action = none nodes on document load
  108685. installOnLoad:function(){document.addEventListener("readystatechange",function(){"complete"===document.readyState&&this.installNewSubtree(document)}.bind(this))},isElement:function(a){return a.nodeType===Node.ELEMENT_NODE},flattenMutationTree:function(a){
  108686. // find children with touch-action
  108687. var b=x(a,this.findElements,this);
  108688. // flatten the list
  108689. // make sure the added nodes are accounted for
  108690. return b.push(z(a,this.isElement)),b.reduce(this.concatLists,[])},mutationWatcher:function(a){a.forEach(this.mutationHandler,this)},mutationHandler:function(a){if("childList"===a.type){var b=this.flattenMutationTree(a.addedNodes);b.forEach(this.addElement,this);var c=this.flattenMutationTree(a.removedNodes);c.forEach(this.removeElement,this)}else"attributes"===a.type&&this.elementChanged(a.target,a.oldValue)}};var D=["none","auto","pan-x","pan-y",{rule:"pan-x pan-y",selectors:["pan-x pan-y","pan-y pan-x"]}],E="",F=window.PointerEvent||window.MSPointerEvent,G=!window.ShadowDOMPolyfill&&document.head.createShadowRoot,H=u.pointermap,I=25,J=[1,4,2,8,16],K=!1;try{K=1===new MouseEvent("test",{buttons:1}).buttons}catch(L){}
  108691. // handler block for native mouse events
  108692. var M,N={POINTER_ID:1,POINTER_TYPE:"mouse",events:["mousedown","mousemove","mouseup","mouseover","mouseout"],register:function(a){u.listen(a,this.events)},unregister:function(a){u.unlisten(a,this.events)},lastTouches:[],
  108693. // collide with the global mouse listener
  108694. isEventSimulatedFromTouch:function(a){for(var b,c=this.lastTouches,d=a.clientX,e=a.clientY,f=0,g=c.length;f<g&&(b=c[f]);f++){
  108695. // simulated mouse events will be swallowed near a primary touchend
  108696. var h=Math.abs(d-b.x),i=Math.abs(e-b.y);if(h<=I&&i<=I)return!0}},prepareEvent:function(a){var b=u.cloneEvent(a),c=b.preventDefault;return b.preventDefault=function(){a.preventDefault(),c()},b.pointerId=this.POINTER_ID,b.isPrimary=!0,b.pointerType=this.POINTER_TYPE,b},prepareButtonsForMove:function(a,b){var c=H.get(this.POINTER_ID);
  108697. // Update buttons state after possible out-of-document mouseup.
  108698. 0!==b.which&&c?a.buttons=c.buttons:a.buttons=0,b.buttons=a.buttons},mousedown:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=H.get(this.POINTER_ID),c=this.prepareEvent(a);K||(c.buttons=J[c.button],b&&(c.buttons|=b.buttons),a.buttons=c.buttons),H.set(this.POINTER_ID,a),b&&0!==b.buttons?u.move(c):u.down(c)}},mousemove:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=this.prepareEvent(a);K||this.prepareButtonsForMove(b,a),b.button=-1,H.set(this.POINTER_ID,a),u.move(b)}},mouseup:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=H.get(this.POINTER_ID),c=this.prepareEvent(a);if(!K){var d=J[c.button];
  108699. // Produces wrong state of buttons in Browsers without `buttons` support
  108700. // when a mouse button that was pressed outside the document is released
  108701. // inside and other buttons are still pressed down.
  108702. c.buttons=b?b.buttons&~d:0,a.buttons=c.buttons}H.set(this.POINTER_ID,a),
  108703. // Support: Firefox <=44 only
  108704. // FF Ubuntu includes the lifted button in the `buttons` property on
  108705. // mouseup.
  108706. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  108707. c.buttons&=~J[c.button],0===c.buttons?u.up(c):u.move(c)}},mouseover:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=this.prepareEvent(a);K||this.prepareButtonsForMove(b,a),b.button=-1,H.set(this.POINTER_ID,a),u.enterOver(b)}},mouseout:function(a){if(!this.isEventSimulatedFromTouch(a)){var b=this.prepareEvent(a);K||this.prepareButtonsForMove(b,a),b.button=-1,u.leaveOut(b)}},cancel:function(a){var b=this.prepareEvent(a);u.cancel(b),this.deactivateMouse()},deactivateMouse:function(){H["delete"](this.POINTER_ID)}},O=u.captureInfo,P=v.findTarget.bind(v),Q=v.allShadows.bind(v),R=u.pointermap,S=2500,T=200,U="touch-action",V={events:["touchstart","touchmove","touchend","touchcancel"],register:function(a){M.enableOnSubtree(a)},unregister:function(){},elementAdded:function(a){var b=a.getAttribute(U),c=this.touchActionToScrollType(b);c&&(a._scrollType=c,u.listen(a,this.events),
  108708. // set touch-action on shadows as well
  108709. Q(a).forEach(function(a){a._scrollType=c,u.listen(a,this.events)},this))},elementRemoved:function(a){a._scrollType=void 0,u.unlisten(a,this.events),
  108710. // remove touch-action from shadow
  108711. Q(a).forEach(function(a){a._scrollType=void 0,u.unlisten(a,this.events)},this)},elementChanged:function(a,b){var c=a.getAttribute(U),d=this.touchActionToScrollType(c),e=this.touchActionToScrollType(b);
  108712. // simply update scrollType if listeners are already established
  108713. d&&e?(a._scrollType=d,Q(a).forEach(function(a){a._scrollType=d},this)):e?this.elementRemoved(a):d&&this.elementAdded(a)},scrollTypes:{EMITTER:"none",XSCROLLER:"pan-x",YSCROLLER:"pan-y",SCROLLER:/^(?:pan-x pan-y)|(?:pan-y pan-x)|auto$/},touchActionToScrollType:function(a){var b=a,c=this.scrollTypes;return"none"===b?"none":b===c.XSCROLLER?"X":b===c.YSCROLLER?"Y":c.SCROLLER.exec(b)?"XY":void 0},POINTER_TYPE:"touch",firstTouch:null,isPrimaryTouch:function(a){return this.firstTouch===a.identifier},setPrimaryTouch:function(a){
  108714. // set primary touch if there no pointers, or the only pointer is the mouse
  108715. (0===R.size||1===R.size&&R.has(1))&&(this.firstTouch=a.identifier,this.firstXY={X:a.clientX,Y:a.clientY},this.scrolling=!1,this.cancelResetClickCount())},removePrimaryPointer:function(a){a.isPrimary&&(this.firstTouch=null,this.firstXY=null,this.resetClickCount())},clickCount:0,resetId:null,resetClickCount:function(){var a=function(){this.clickCount=0,this.resetId=null}.bind(this);this.resetId=setTimeout(a,T)},cancelResetClickCount:function(){this.resetId&&clearTimeout(this.resetId)},typeToButtons:function(a){var b=0;return"touchstart"!==a&&"touchmove"!==a||(b=1),b},touchToPointer:function(a){var b=this.currentTouchEvent,c=u.cloneEvent(a),d=c.pointerId=a.identifier+2;c.target=O[d]||P(c),c.bubbles=!0,c.cancelable=!0,c.detail=this.clickCount,c.button=0,c.buttons=this.typeToButtons(b.type),c.width=2*(a.radiusX||a.webkitRadiusX||0),c.height=2*(a.radiusY||a.webkitRadiusY||0),c.pressure=a.force||a.webkitForce||.5,c.isPrimary=this.isPrimaryTouch(a),c.pointerType=this.POINTER_TYPE,
  108716. // forward modifier keys
  108717. c.altKey=b.altKey,c.ctrlKey=b.ctrlKey,c.metaKey=b.metaKey,c.shiftKey=b.shiftKey;
  108718. // forward touch preventDefaults
  108719. var e=this;return c.preventDefault=function(){e.scrolling=!1,e.firstXY=null,b.preventDefault()},c},processTouches:function(a,b){var c=a.changedTouches;this.currentTouchEvent=a;for(var d,e=0;e<c.length;e++)d=c[e],b.call(this,this.touchToPointer(d))},
  108720. // For single axis scrollers, determines whether the element should emit
  108721. // pointer events or behave as a scroller
  108722. shouldScroll:function(a){if(this.firstXY){var b,c=a.currentTarget._scrollType;if("none"===c)
  108723. // this element is a touch-action: none, should never scroll
  108724. b=!1;else if("XY"===c)
  108725. // this element should always scroll
  108726. b=!0;else{var d=a.changedTouches[0],e=c,f="Y"===c?"X":"Y",g=Math.abs(d["client"+e]-this.firstXY[e]),h=Math.abs(d["client"+f]-this.firstXY[f]);
  108727. // if delta in the scroll axis > delta other axis, scroll instead of
  108728. // making events
  108729. b=g>=h}return this.firstXY=null,b}},findTouch:function(a,b){for(var c,d=0,e=a.length;d<e&&(c=a[d]);d++)if(c.identifier===b)return!0},
  108730. // In some instances, a touchstart can happen without a touchend. This
  108731. // leaves the pointermap in a broken state.
  108732. // Therefore, on every touchstart, we remove the touches that did not fire a
  108733. // touchend event.
  108734. // To keep state globally consistent, we fire a
  108735. // pointercancel for this "abandoned" touch
  108736. vacuumTouches:function(a){var b=a.touches;
  108737. // pointermap.size should be < tl.length here, as the touchstart has not
  108738. // been processed yet.
  108739. if(R.size>=b.length){var c=[];R.forEach(function(a,d){
  108740. // Never remove pointerId == 1, which is mouse.
  108741. // Touch identifiers are 2 smaller than their pointerId, which is the
  108742. // index in pointermap.
  108743. if(1!==d&&!this.findTouch(b,d-2)){var e=a.out;c.push(e)}},this),c.forEach(this.cancelOut,this)}},touchstart:function(a){this.vacuumTouches(a),this.setPrimaryTouch(a.changedTouches[0]),this.dedupSynthMouse(a),this.scrolling||(this.clickCount++,this.processTouches(a,this.overDown))},overDown:function(a){R.set(a.pointerId,{target:a.target,out:a,outTarget:a.target}),u.enterOver(a),u.down(a)},touchmove:function(a){this.scrolling||(this.shouldScroll(a)?(this.scrolling=!0,this.touchcancel(a)):(a.preventDefault(),this.processTouches(a,this.moveOverOut)))},moveOverOut:function(a){var b=a,c=R.get(b.pointerId);
  108744. // a finger drifted off the screen, ignore it
  108745. if(c){var d=c.out,e=c.outTarget;u.move(b),d&&e!==b.target&&(d.relatedTarget=b.target,b.relatedTarget=e,
  108746. // recover from retargeting by shadow
  108747. d.target=e,b.target?(u.leaveOut(d),u.enterOver(b)):(
  108748. // clean up case when finger leaves the screen
  108749. b.target=e,b.relatedTarget=null,this.cancelOut(b))),c.out=b,c.outTarget=b.target}},touchend:function(a){this.dedupSynthMouse(a),this.processTouches(a,this.upOut)},upOut:function(a){this.scrolling||(u.up(a),u.leaveOut(a)),this.cleanUpPointer(a)},touchcancel:function(a){this.processTouches(a,this.cancelOut)},cancelOut:function(a){u.cancel(a),u.leaveOut(a),this.cleanUpPointer(a)},cleanUpPointer:function(a){R["delete"](a.pointerId),this.removePrimaryPointer(a)},
  108750. // prevent synth mouse events from creating pointer events
  108751. dedupSynthMouse:function(a){var b=N.lastTouches,c=a.changedTouches[0];
  108752. // only the primary finger will synth mouse events
  108753. if(this.isPrimaryTouch(c)){
  108754. // remember x/y of last touch
  108755. var d={x:c.clientX,y:c.clientY};b.push(d);var e=function(a,b){var c=a.indexOf(b);c>-1&&a.splice(c,1)}.bind(null,b,d);setTimeout(e,S)}}};M=new c(V.elementAdded,V.elementRemoved,V.elementChanged,V);var W,X,Y,Z=u.pointermap,$=window.MSPointerEvent&&"number"==typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE,_={events:["MSPointerDown","MSPointerMove","MSPointerUp","MSPointerOut","MSPointerOver","MSPointerCancel","MSGotPointerCapture","MSLostPointerCapture"],register:function(a){u.listen(a,this.events)},unregister:function(a){u.unlisten(a,this.events)},POINTER_TYPES:["","unavailable","touch","pen","mouse"],prepareEvent:function(a){var b=a;return $&&(b=u.cloneEvent(a),b.pointerType=this.POINTER_TYPES[a.pointerType]),b},cleanup:function(a){Z["delete"](a)},MSPointerDown:function(a){Z.set(a.pointerId,a);var b=this.prepareEvent(a);u.down(b)},MSPointerMove:function(a){var b=this.prepareEvent(a);u.move(b)},MSPointerUp:function(a){var b=this.prepareEvent(a);u.up(b),this.cleanup(a.pointerId)},MSPointerOut:function(a){var b=this.prepareEvent(a);u.leaveOut(b)},MSPointerOver:function(a){var b=this.prepareEvent(a);u.enterOver(b)},MSPointerCancel:function(a){var b=this.prepareEvent(a);u.cancel(b),this.cleanup(a.pointerId)},MSLostPointerCapture:function(a){var b=u.makeEvent("lostpointercapture",a);u.dispatchEvent(b)},MSGotPointerCapture:function(a){var b=u.makeEvent("gotpointercapture",a);u.dispatchEvent(b)}},aa=window.navigator;aa.msPointerEnabled?(W=function(a){i(a),j(this),k(a)&&(u.setCapture(a,this,!0),this.msSetPointerCapture(a))},X=function(a){i(a),u.releaseCapture(a,!0),this.msReleasePointerCapture(a)}):(W=function(a){i(a),j(this),k(a)&&u.setCapture(a,this)},X=function(a){i(a),u.releaseCapture(a)}),Y=function(a){return!!u.captureInfo[a]},g(),h(),l();var ba={dispatcher:u,Installer:c,PointerEvent:a,PointerMap:p,targetFinding:v};return ba});
  108756. /***/ }),
  108757. /* 49 */
  108758. /***/ (function(module, exports, __webpack_require__) {
  108759. "use strict";
  108760. Object.defineProperty(exports, "__esModule", { value: true });
  108761. var defaultViewer_1 = __webpack_require__(8);
  108762. var mappers_1 = __webpack_require__(3);
  108763. var _1 = __webpack_require__(5);
  108764. /**
  108765. * Will attach an init function the the DOMContentLoaded event.
  108766. * The init function will be removed automatically after the event was triggered.
  108767. */
  108768. function initListeners() {
  108769. document.addEventListener("DOMContentLoaded", init);
  108770. function init(event) {
  108771. document.removeEventListener("DOMContentLoaded", init);
  108772. if (_1.viewerGlobals.disableInit || _1.disableInit)
  108773. return;
  108774. InitTags();
  108775. }
  108776. }
  108777. exports.initListeners = initListeners;
  108778. /**
  108779. * Select all HTML tags on the page that match the selector and initialize a viewer
  108780. *
  108781. * @param selector the selector to initialize the viewer on (default is 'babylon')
  108782. */
  108783. function InitTags(selector) {
  108784. if (selector === void 0) { selector = 'babylon'; }
  108785. var elements = document.querySelectorAll(selector);
  108786. for (var i = 0; i < elements.length; ++i) {
  108787. var element = elements.item(i);
  108788. // get the html configuration
  108789. var configMapper = mappers_1.mapperManager.getMapper('dom');
  108790. var config = configMapper.map(element);
  108791. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  108792. }
  108793. }
  108794. exports.InitTags = InitTags;
  108795. /***/ })
  108796. /******/ ]);
  108797. return BabylonViewer;
  108798. });